query
stringlengths 9
34k
| document
stringlengths 8
5.39M
| negatives
sequencelengths 19
20
| metadata
dict |
---|---|---|---|
Gets or sets the position at which to stop rendering the minor tickmarks as a value from 0 to 1, measured from the front/bottom of the linear gauge. Values further from zero than 1 can be used to make this extend further than the normal size of the linear gauge. | get minorTickEndExtent() {
return this.i.b6;
} | [
"function beforeSetTickPositions() {\n // If autoConnect is true, polygonal grid lines are connected, and\n // one closestPointRange is added to the X axis to prevent the last\n // point from overlapping the first.\n this.autoConnect = (this.isCircular &&\n typeof pick(this.userMax, this.options.max) === 'undefined' &&\n correctFloat(this.endAngleRad - this.startAngleRad) ===\n correctFloat(2 * Math.PI));\n // This will lead to add an extra tick to xAxis in order to display\n // a correct range on inverted polar\n if (!this.isCircular && this.chart.inverted) {\n this.max++;\n }\n if (this.autoConnect) {\n this.max += ((this.categories && 1) ||\n this.pointRange ||\n this.closestPointRange ||\n 0); // #1197, #2260\n }\n }",
"_increaseY() {\n if (!this._invertedY()) {\n this.valueY = Math.min(this.maxY, this.valueY + this.stepY);\n } else {\n this.valueY = Math.min(this.minY, this.valueY + this.stepY);\n }\n }",
"_decreaseY() {\n if (!this._invertedY()) {\n this.valueY = Math.max(this.minY, this.valueY - this.stepY);\n } else {\n this.valueY = Math.max(this.maxY, this.valueY - this.stepY);\n }\n }",
"_valueYChanged(value) {\n if (this.enableY) {\n this._handle.style.top = (this._canvas.scrollHeight)\n * ((value - this.minY) / (this.maxY - this.minY)) + 'px';\n }\n }",
"yTickDelta() {\n return 1;\n }",
"get position() {\n const now = this.now();\n\n const ticks = this._clock.getTicksAtTime(now);\n\n return new _Ticks.TicksClass(this.context, ticks).toBarsBeatsSixteenths();\n }",
"getMaxY(){ return this.y + this.height }",
"function yLabelPosFormatter(y) {\n if (isNaN(y)) { return 'n/a'; }\n y = Math.round(y);\n return y === 0 ? 'P1' : 'P' + -y;\n }",
"_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 }",
"_updateKnobPosition() {\n this._setKnobPosition(this._valueToPosition(this.getValue()));\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 }",
"static yAxis() { return newVec(0.0,1.0,0.0); }",
"get centrey(){ return this.pos.y + this.size.height/2;}",
"function textPosition (d) {\n\t\tif (y(d.value) + 16 > settings.hm) {\n\t\t\treturn y(d.value) - 2;\n\t\t}\n\t\treturn y(d.value) + 12;\n\t}",
"set minLines(value) {}",
"_valueXChanged(value) {\n if (this.enableX) {\n this._handle.style.left = (this._canvas.scrollWidth)\n * ((value - this.minX) / (this.maxX - this.minX)) + 'px';\n }\n }",
"getMaxX(){ return this.x + this.width }",
"function adjustTickAmount() {\n\n\t\t\tif (maxTicks && !isDatetimeAxis && !categories && !isLinked && options.alignTicks !== false) { // only apply to linear scale\n\t\t\t\tvar oldTickAmount = tickAmount,\n\t\t\t\t\tcalculatedTickAmount = tickPositions.length;\n\n\t\t\t\t// set the axis-level tickAmount to use below\n\t\t\t\ttickAmount = maxTicks[xOrY];\n\n\t\t\t\tif (calculatedTickAmount < tickAmount) {\n\t\t\t\t\twhile (tickPositions.length < tickAmount) {\n\t\t\t\t\t\ttickPositions.push( correctFloat(\n\t\t\t\t\t\t\ttickPositions[tickPositions.length - 1] + tickInterval\n\t\t\t\t\t\t));\n\t\t\t\t\t}\n\t\t\t\t\ttransA *= (calculatedTickAmount - 1) / (tickAmount - 1);\n\t\t\t\t\tmax = tickPositions[tickPositions.length - 1];\n\n\t\t\t\t}\n\t\t\t\tif (defined(oldTickAmount) && tickAmount !== oldTickAmount) {\n\t\t\t\t\taxis.isDirty = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t}",
"async getToggleIndicatorPosition() {\n // By default the expansion indicator will show \"after\" the panel header content.\n if (await (await this._header()).hasClass('mat-expansion-toggle-indicator-before')) {\n return 'before';\n }\n return 'after';\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Move cell to the position of the current cell, and if the values are the same their values merge | transitionTo(otherCell) {
var newX = this.x + 0;
var newY = this.y + 0;
this.x = otherCell.x + 0;
this.y = otherCell.y + 0;
otherCell.x = newX;
otherCell.y = newY;
if (otherCell.value == this.value) {
otherCell.value = 0;
otherCell.reset();
otherCell.clear();
this.value += this.value;
this.combined = true;
}
} | [
"function moveNumberCellToEmpty(cell, playingOrShuffling) {\n // Checks if selected cell has number\n if (cell.className != \"empty\") {\n // Tries to get empty adjacent cell\n let emptyCell = getEmptyAdjacentCellIfExists(cell);\n \n if (emptyCell) {\n if (playingOrShuffling === 1) {\n // noOfMoves++;\n // document.getElementById(\"counter\").innerText = noOfMoves;\n // new Audio(\"../sound/fire_bow_sound-mike-koenig.mp3\").play();\n }\n // There is empty adjacent cell..\n // styling and id of the number cell\n let tempCell = { style: cell.style.cssText, id: cell.id };\n \n // Exchanges id and style values\n cell.style.cssText = emptyCell.style.cssText;\n cell.id = emptyCell.id;\n emptyCell.style.cssText = tempCell.style;\n emptyCell.id = tempCell.id;\n \n if (state == 1) {\n // Checks the order of numbers\n checkSolvedState();\n }\n }\n }\n }",
"mergeable(direction)\n {\n let indices = [];\n\n switch (direction) \n {\n // up\n case \"u\":\n for (let j = 0; j < 4; ++j)\n {\n let flag = true;\n let flag_moveable = false;\n for (let i = 0; i < 3; ++i)\n {\n if (this.numbers[i][j] === 0)\n flag_moveable = true;\n if (this.numbers[i][j] !== 0 && !flag_moveable && flag && this.numbers[i][j] === this.numbers[i + 1][j])\n {\n if (this.merge_status[j] || i != 0)\n indices.push([i, j]);\n flag = false;\n }\n else\n flag = true;\n }\n }\n break;\n // down\n case \"d\":\n for (let j = 0; j < 4; ++j)\n {\n let flag = true;\n let flag_moveable = false;\n for (let i = 3; i > 0; --i)\n {\n if (this.numbers[i][j] === 0)\n flag_moveable = true;\n if (this.numbers[i][j] !== 0 && !flag_moveable && flag && this.numbers[i][j] === this.numbers[i - 1][j])\n {\n if (this.merge_status[j] || i != 3)\n indices.push([i, j]);\n flag = false;\n }\n else\n flag = true;\n }\n }\n break;\n // left\n case \"l\":\n for (let i = 0; i < 4; ++i)\n {\n let flag = true;\n let flag_moveable = false;\n for (let j = 0; j < 3; ++j)\n {\n if (this.numbers[i][j] === 0)\n flag_moveable = true;\n if (this.numbers[i][j] !== 0 && !flag_moveable && flag && this.numbers[i][j] === this.numbers[i][j + 1])\n {\n if (this.merge_status[i] || j != 0)\n indices.push([i, j]);\n flag = false;\n }\n else\n flag = true;\n }\n }\n break;\n // right\n case \"r\":\n for (let i = 0; i < 4; ++i)\n {\n let flag = true;\n let flag_moveable = false;\n for (let j = 3; j > 0; --j)\n {\n if (this.numbers[i][j] === 0)\n flag_moveable = true;\n if (this.numbers[i][j] !== 0 && !flag_moveable && flag && this.numbers[i][j] === this.numbers[i][j - 1])\n {\n if (this.merge_status[i] || j != 3)\n indices.push([i, j]);\n flag = false;\n }\n else\n flag = true;\n }\n }\n break;\n default:\n throw \"Invalid direction!\";\n }\n\n return indices;\n }",
"commit() {\n if (this.isDirty && this.elt) {\n let top = ((this.cellSize * this.y) + this.padding) + \"px\";\n let left = ((this.cellSize * this.x) + this.padding) + \"px\";\n this.elt.css({\n top: top,\n left: left\n });\n }\n this.reset();\n }",
"isSingleCell() {\n return this.fromRow == this.toRow && this.fromCell == this.toCell;\n }",
"function shift(x, y, dx, dy, hasMerged = false) {\n const tileValue = gameState[x][y]\n\n // make sure that nothing happens if the tile has reached the edge or is an empty tile\n const hasReachedBorder = x + dx == -1 || x + dx == 4 || y + dy == -1 || y + dy == 4\n if(hasReachedBorder || tileValue == 0) return false\n // make sure that false is returned if the tile is blocked from movement\n const isBlocked = gameState[x + dx][y + dy] != tileValue && gameState[x + dx][y + dy] != 0\n if(isBlocked) return false\n\n // move the tile only if it is unblocked or merging is allowed\n const isNotBlocked = gameState[x + dx][y + dy] == 0\n const isBlockedByEqualTile = gameState[x + dx][y + dy] == tileValue\n const mergingAllowed = !hasMerged && !tiles[x + dx][y + dy].justMerged\n if(isNotBlocked || isBlockedByEqualTile && mergingAllowed) {\n // set merging status to ensure that duplicate merges cannot happen\n const justMerged = gameState[x + dx][y + dy] == tileValue\n tiles[x + dx][y + dy].justMerged = justMerged\n\n gameState[x][y] = 0\n gameState[x + dx][y + dy] += tileValue\n shift(x + dx, y + dy, dx, dy, justMerged)\n }\n return true\n}",
"function swapSelectedCells(p) {\n\n p.cell0.text(p.cell1Text)\n .attr(\"rowspan\", p.cell1RowSpan)\n .attr(\"colspan\", p.cell1ColSpan)\n .attr(\"class\", p.cell1Class)\n .attr(\"style\", p.cell1Styles);\n\n\n p.cell1.text(p.cell0Text)\n .attr(\"rowspan\", p.cell0RowSpan)\n .attr(\"colspan\", p.cell0ColSpan)\n .attr(\"class\", p.cell0Class)\n .attr(\"style\", p.cell0Styles);\n\n }",
"moveUp() {\r\n let tempGrid = [];\r\n for (let i = 0; i < this.gridSize; i++) {\r\n let tempIx = 0;\r\n let tempList = [];\r\n for (let j = 0; j < this.gridSize; j++) {\r\n tempList.push(this.board[tempIx][i]);\r\n tempIx += 1;\r\n }\r\n let tempListMerged = this.reduceRow(tempList);\r\n tempGrid.push(tempListMerged);\r\n }\r\n\r\n for (let i = 0; i < this.gridSize; i++) {\r\n for (let j = 0; j < this.gridSize; j++) {\r\n this.board[i][j] = tempGrid[j][i];\r\n }\r\n }\r\n this.afterMove();\r\n }",
"swapRows(i, j) {\n if (i < 0 || i >= this.numRows || j < 0 || j >= this.numRows)\n throw new RangeError(\"Index out of bounds\");\n const temp = this.cells[i];\n this.cells[i] = this.cells[j];\n this.cells[j] = temp;\n }",
"function updateMovingScorePosition(){\n\tlet direction = Math.floor(Math.random() * 4);\n\tlet xPosition = movingScore.i;\n\tlet yPosition = movingScore.j;\n\n\t// up\n\tif (direction == 0 && yPosition-1 > 0 && board[xPosition][yPosition-1] != 1){\n\t\tmovingScore.j--;\n\t}\n\n\t// down\n\telse if (direction == 1 && yPosition+1 < 9 && board[xPosition][yPosition+1] != 1){\n\t\tmovingScore.j++;\n\t}\n\n\t// left\n\telse if (direction == 2 && xPosition-1 > 0 && board[xPosition-1][yPosition] != 1){\n\t\tmovingScore.i--;\n\t}\n\n\t// right\n\telse if (direction == 3 && xPosition+1 < 9 && board[xPosition+1][yPosition] != 1){\n\t\tmovingScore.i++;\n\t}\n}",
"function makeBlockMove(blockSection) {\n\t\tvar cells = []\n\t\tfor(var cell in blockSection) {\n\t\t\tcells.push(blockSection[cell])\n\t\t}\n\t\t//same column\n\t\tif(cells[0].x === cells[1].x){\n\t\t\tvar y;\n\t\t\tvar sumYs = cells[0].y + cells[1].y\n\t\t\tif(sumYs === 3) {\n\t\t\t\ty = 0;\n\t\t\t} else if(sumYs === 2) {\n\t\t\t\ty = 1;\n\t\t\t} else {\n\t\t\t\ty = 2;\n\t\t\t}\n\t\t\tvar coordinates = '#x' + cells[0].x + '-y' + y;\n\t\t\t$(coordinates).html('o');\n\t\t\t$(coordinates).off('click');\n\t\t\taddCellToBoardsFromCoordinates(cells[0].x,y);\n\t\t\t\n\t\t} else if(cells[0].y === cells[1].y) { //same row\n\t\t\tvar x;\n\t\t\tvar sumXs = cells[0].x + cells[1].x\n\t\t\tif(sumXs === 3) {\n\t\t\t\tx = 0;\n\t\t\t} else if(sumXs === 2) {\n\t\t\t\tx = 1;\n\t\t\t} else {\n\t\t\t\tx = 2;\n\t\t\t}\n\t\t\tvar coordinates = '#x' + x + '-y' + cells[0].y;\n\t\t\t$(coordinates).html('o');\n\t\t\t$(coordinates).off('click');\n\t\t\taddCellToBoardsFromCoordinates(x,cells[0].y);\n\t\t\t\n\t\t} else { //same diagonal\n\t\t\tvar x, y; \n\t\t\tif((cells[0].x === 0 && cells[0].y === 0) || \n\t\t\t\t (cells[1].x === 2 && cells[1].y === 2) ||\n\t\t\t\t (cells[1].x === 0 && cells[1].y === 0) ||\n\t\t\t\t (cells[0].x === 2 && cells[0].y === 2)\n\t\t\t\t) {\n\t\t\t\tvar sum = cells[0].x + cells[0].y + cells[1].x + cells[1].y;\n\t\t\t\tif(sum === 6) {\n\t\t\t\t\tx = 0;\n\t\t\t\t\ty = 0;\n\t\t\t\t} else if(sum === 4) {\n\t\t\t\t\tx = 1;\n\t\t\t\t\ty = 1;\n\t\t\t\t} else {\n\t\t\t\t\tx = 2;\n\t\t\t\t\ty = 2;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tvar sumXs = cells[0].x + cells[1].x;\n\t\t\t\tvar sumYs = cells[0].y + cells[1].y;\n\t\t\t\tif(sumXs === 3 && sumYs === 1) {\n\t\t\t\t\tx = 0;\n\t\t\t\t\ty = 2;\n\t\t\t\t} else if(sumXs === 1 && sumYs === 3) {\n\t\t\t\t\tx = 2;\n\t\t\t\t\ty = 0;\n\t\t\t\t} else {\n\t\t\t\t\tx = 1;\n\t\t\t\t\ty = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\tvar coordinates = '#x' + x + '-y' + y;\n\t\t\t$(coordinates).html('o');\n\t\t\t$(coordinates).off('click');\n\t\t\taddCellToBoardsFromCoordinates(x,y);\n\t\t}\n\t}",
"moveRight() {\r\n let tempGrid = [];\r\n for (let i = 0; i < this.gridSize; i++) {\r\n let tempIx = this.gridSize - 1;\r\n let tempList = [];\r\n for (let j = 0; j < this.gridSize; j++) {\r\n tempList.push(this.board[i][tempIx]);\r\n tempIx -= 1;\r\n }\r\n let tempListMerged = this.reduceRow(tempList);\r\n tempGrid.push(tempListMerged);\r\n }\r\n\r\n for (let i = 0; i < this.gridSize; i++) {\r\n for (let j = 0; j < this.gridSize; j++) {\r\n this.board[i][j] = tempGrid[i][this.gridSize - 1 - j];\r\n }\r\n }\r\n this.afterMove();\r\n }",
"function equalCells(cell1, cell2) {\n return cell1.row === cell2.row && cell1.column === cell2.column;\n}",
"function mergeFlexCell(item) {\r\n const className = $(item).attr(\"class\");\r\n // console.log(`merge cell ${className}`);\r\n console.assert($(item).children().length === 1);\r\n const child = $(item).children()[0];\r\n $(child)\r\n .unwrap() \r\n .addClass(className)\r\n .css('width', 'unset')\r\n .css('height', 'unset') // unset height from 100%\r\n .css('flex-basis', 'auto');\r\n}",
"swapRows() {\n Performance.start('swapRows');\n if (this.rows.length > 998) {\n let temp = this.rows[1];\n this.rows[1] = this.rows[998];\n this.rows[998] = temp;\n }\n Performance.stop();\n }",
"function fillCell(cell_pos, text_info) {\n\tvar table_data = [];\n\n\t// propagate and fill the table\n\tfor (var i = 0; i < cell_pos.length; i++) {\n\t\tvar cell_data = [];\n\t\tfor (var j = 0; j < cell_pos[0].length; j++) {\n\t\t\tvar table_data_row = [];\n\t\t\tvar cell_info = cell_pos[i][j];\n\t\t\tvar curr_cell_upper_left_x = cell_info[0][0];\n\t\t\tvar curr_cell_upper_left_y = cell_info[0][1];\n\t\t\tvar curr_cell_lower_right_x = cell_info[1][0];\n\t\t\tvar curr_cell_lower_right_y = cell_info[1][1];\n\n\t\t\tvar append = \"\";\n\n\t\t\tfor (var k = 0; k < text_info.length; k++) {\n\t\t\t\tvar textbox = text_info[k];\n\t\t\t\tvar text_x = textbox[0][0];\n\t\t\t\tvar text_y = textbox[0][1];\n\t\t\t\t\n\t\t\t\tif (text_x >= curr_cell_upper_left_x && text_x <= curr_cell_lower_right_x && text_y >= curr_cell_upper_left_y && text_y < curr_cell_lower_right_y) {\n\t\t\t\t\tappend += textbox[1];\n\t\t\t\t}\n\t\t\t}\n\t\t\tcell_data.push(append);\n\t\t}\n\t\ttable_data.push(cell_data);\n\t}\n\n\tfor (var i = 0; i < table_data.length;) {\n\t\tvar flag = true;\n\t\t// sometimes the it will generate an entire empty row. need to remove the row in this case.\n\t\tfor (var j = 0; j < table_data[i].length; j++) {\n\t\t\tif (table_data[i][j] != '')\tflag = false;\n\t\t}\n\t\tif (flag) {\n\t\t\ttable_data.splice(i,1);\n\t\t}\n\t\telse {\n\t\t\t//remove redundant tab from the beginning\n\t\t\tfor (var j = 0; j < table_data[i].length;) {\n\t\t\t\tif (table_data[i][j] == '') {\n\t\t\t\t\ttable_data[i].splice(j,1);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tj++;\n\t\t\t\t}\n\t\t\t}\n\t\t\ti++;\n\t\t}\n\t}\n\treturn table_data;\n}",
"function getAdjacentCells(cell){\n\tvar cellCopy;\n\tif(cell.location.row+1 < mazeSize ){ // down\n\t\tcellCopy = new Cell(maze[cell.location.row+1][cell.location.col].location.row, maze[cell.location.row+1][cell.location.col].location.col,maze[cell.location.row+1][cell.location.col].id);\n\t\tcell.adjacentCells.push(cellCopy);\n\t}\n\tif(cell.location.row-1 > -1){ // up\n\t\tcellCopy = new Cell(maze[cell.location.row-1][cell.location.col].location.row, maze[cell.location.row-1][cell.location.col].location.col,maze[cell.location.row-1][cell.location.col].id);\n\t\tcell.adjacentCells.push(cellCopy);\n\t}\n\tif(cell.location.col+1 < mazeSize){ // right \n\t\tcellCopy = new Cell(maze[cell.location.row][cell.location.col+1].location.row, maze[cell.location.row][cell.location.col+1].location.col,maze[cell.location.row][cell.location.col+1].id);\n\t\tcell.adjacentCells.push(cellCopy);\n\t}\n\tif(cell.location.col-1 > -1){ // left\n\t\tcellCopy = new Cell(maze[cell.location.row][cell.location.col-1].location.row, maze[cell.location.row][cell.location.col-1].location.col,maze[cell.location.row][cell.location.col-1].id);\n\t\tcell.adjacentCells.push(cellCopy);\n\t}\n}",
"changeCellRight() {\n const cells = this.get('cells');\n const hoverIndex = this.get('hoverIndex');\n const lastIndex = cells.length > 0 ? cells.length - 1 : 0;\n const isLoop = this.get('isLoop');\n const noSwitch = this.get('noSwitchRight');\n const inheritPosition = this.get('parentWindow.inheritPosition');\n\n if (hoverIndex === lastIndex) {\n if (isLoop) {\n this.set('hoverIndex', 0);\n this.trigger('cellDidChange', { direction: 'right' });\n } else {\n this.trigger('focusOnLastCell');\n\n if (!noSwitch) {\n this.get('frameService').trigger(\n 'rowFocusRight',\n this.get('parentWindow')\n );\n }\n }\n\n return;\n }\n\n this.incrementProperty('hoverIndex');\n this.trigger('cellDidChange', { direction: 'right' });\n }",
"function pushNextBallsToBoard() {\r\n\tvar nNewEmptyCellKey;\r\n\tvar sNewEmptyCellID;\r\n\r\n\tfor (var i = 0; (i < 3); i++) {\r\n\t\tif ((aNextBalls[i].toAppear !== \"\")\r\n\t\t\t\t&& (!isEmpty(aNextBalls[i].toAppear))) {\r\n\t\t\t// find an empty cell\r\n\t\t\tnNewEmptyCellKey = Math.floor(Math.random() * aEmptyCellIDs.length);\r\n\t\t\tsNewEmptyCellID = aEmptyCellIDs[nNewEmptyCellKey];\r\n\t\t} else {\r\n\t\t\tsNewEmptyCellID = aNextBalls[i].toAppear;\r\n\t\t}\r\n\t\t// set new color, place the ball\r\n\t\tsetColor(aNextBalls[i].color, aCellByIDs[sNewEmptyCellID]); // \r\n\t\tfindColorBlocks(sNewEmptyCellID);\r\n\t\tif (aEmptyCellIDs.length === 0) {\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\tif (aEmptyCellIDs.length === 0) {\r\n\t\talert(\"No more empty cells, game ends.\");\r\n\t\tif (nTotalScore > oGameSettings.nHighScore) {\r\n\t\t\twindow.localStorage.highScore = nTotalScore;\r\n\t\t\toGameSettings.nHighScore = nTotalScore;\r\n\r\n\t\t\talert(\"congratulation! you have made a new high score.\")\r\n\t\t}\r\n\t\tnewGame();\r\n\t\treturn true;\r\n\t} else {\r\n\t\tgetNextBallColors();\r\n\t}\r\n\treturn true;\r\n}",
"interchange(col) {\n if (this._matrix !== col.matrix) {\n throw new Error(\"Row interchange operation is not compatable with rows of two different matrices.\");\n }\n else {\n for (let i = 0; i < this._matrix.height(); i++) {\n let temp = this._matrix.get(i, col.index);\n this._matrix.put(i, col.index, this._matrix.get(i, this._index));\n this._matrix.put(i, this._index, temp);\n }\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Resolve a component by its name string. Supports nested components delimited by a "/" | resolveComponent(name) {
if (typeof name !== "string") return false;
name = name.split("/");
return name.reduce((acc, chunk) => (acc[chunk]), this.components);
} | [
"AliasComponent(string, string, string, string, string) {\n\n }",
"ImportComponent(string, string) {\n\n }",
"function componentize(name) {\n let dasherized = dasherize(name);\n return hasDash(dasherized) ? dasherized : `${dasherized}-app`;\n}",
"function parseWebModuleSpecifier(specifier, knownDependencies) {\n const webModulesIndex = specifier.indexOf('web_modules/');\n if (webModulesIndex === -1) {\n return null;\n }\n // check if the resolved specifier (including file extension) is a known package.\n const resolvedSpecifier = specifier.substring(webModulesIndex + 'web_modules/'.length);\n if (knownDependencies.includes(resolvedSpecifier)) {\n return resolvedSpecifier;\n }\n // check if the resolved specifier (without extension) is a known package.\n const resolvedSpecifierWithoutExtension = stripJsExtension(resolvedSpecifier);\n if (knownDependencies.includes(resolvedSpecifierWithoutExtension)) {\n return resolvedSpecifierWithoutExtension;\n }\n // Otherwise, this is an explicit import to a file within a package.\n return resolvedSpecifier;\n}",
"function parseAlias(id) {\n var alias = config['alias'];\n\n var parts = id.split('/');\n var last = parts.length - 1;\n\n parse(parts, 0);\n if (last) parse(parts, last);\n\n function parse(parts, i) {\n var part = parts[i];\n var m;\n\n if (alias && alias.hasOwnProperty(part)) {\n parts[i] = alias[part];\n }\n // jquery:1.6.1 => jquery/1.6.1/jquery\n // jquery:1.6.1-debug => jquery/1.6.1/jquery-debug\n else if ((m = part.match(/(.+):([\\d\\.]+)(-debug)?/))) {\n parts[i] = m[1] + '/' + m[2] + '/' + m[1] + (m[3] ? m[3] : '');\n }\n }\n\n return parts.join('/');\n }",
"resolveId ( id, importer = location.href ) {\n\t\t\t// don't touch absolute paths\n\t\t\tif ( absolutePath.test( id ) ) return id;\n\n\t\t\t// add '.js' to paths without extensions\n\t\t\tif ( extname( id ) === '' ) id += '.js';\n\n\t\t\t// keep everything before the last '/' in `importer`\n\t\t\tconst base = importer.slice(0, importer.lastIndexOf('/') + 1);\n\n\t\t\t// resolve `id` relative to `base`\n\t\t\treturn resolve( base + id );\n\t\t}",
"resolve(path) {\n path = path || this.pathname();\n var routes = this._routes;\n var route = Object.keys(routes).reduce(function(p, name) {\n return p || (routes[name].paths.reduce(function(m, rule) {\n rule = rule instanceof RegExp ? rule : new RegExp(`^\\\\/?${rule}`);\n return m || rule.test(path);\n }, false) && name);\n }, null);\n return route;\n }",
"static getComponentName() {\n const name = this.name;\n if (typeof name === 'string' && name !== '') {\n return name;\n }\n throw new Error('The name of the component is missing');\n }",
"function resolveAlias(name, counter) {\n counter = counter || 0;\n if (counter > 100) {\n throw \"Too many aliases returned by Respec\";\n }\n if (chunkRes[name].aliasOf) {\n return resolveAlias(chunkRes[name].aliasOf, counter + 1);\n }\n else {\n return name;\n }\n }",
"function resolve$3() {\n var resolvedPath = '',\n resolvedAbsolute = false;\n\n for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {\n var path = (i >= 0) ? arguments[i] : '/';\n\n // Skip empty and invalid entries\n if (typeof path !== 'string') {\n throw new TypeError('Arguments to path.resolve must be strings');\n } else if (!path) {\n continue;\n }\n\n resolvedPath = path + '/' + resolvedPath;\n resolvedAbsolute = path.charAt(0) === '/';\n }\n\n // At this point the path should be resolved to a full absolute path, but\n // handle relative paths to be safe (might happen when process.cwd() fails)\n\n // Normalize the path\n resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {\n return !!p;\n }), !resolvedAbsolute).join('/');\n\n return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';\n }",
"function resolve (cid, path, callback) {\n let value\n\n doUntil(\n (cb) => {\n self.block.get(cid, (err, block) => {\n if (err) return cb(err)\n\n const r = self._ipld.resolvers[cid.codec]\n\n if (!r) {\n return cb(new Error(`No resolver found for codec \"${cid.codec}\"`))\n }\n\n r.resolver.resolve(block.data, path, (err, result) => {\n if (err) return cb(err)\n value = result.value\n path = result.remainderPath\n cb()\n })\n })\n },\n () => {\n const endReached = !path || path === '/'\n\n if (endReached) {\n return true\n }\n\n if (value) {\n cid = new CID(value['/'])\n }\n\n return false\n },\n (err) => {\n if (err) return callback(err)\n if (value && value['/']) return callback(null, new CID(value['/']))\n callback()\n }\n )\n }",
"function _expandComponent(component)\n {\n return expandComponents([component]);\n }",
"static locate(module) {\n // Initialize name & default sources\n let name = module.toLowerCase();\n let repository = \"internal\";\n\n // Slice name and look for repository\n let slices = name.split(\":\");\n\n // Make sure there are exactly two slices\n if (slices.length === 2) {\n // Update name\n name = slices.pop();\n // Update sources\n repository = slices.pop();\n }\n\n // Query repository element\n let element = document.querySelector(`meta[name=\"repository-${repository}\"]`);\n\n // Make sure repository exists\n if (element !== null)\n return `${element.content}/${name}.js`;\n\n // Return null\n return null;\n }",
"function findChildByName(element, name) {\n if (element.name !== undefined && element.name === name) return element;\n\n\ttry {\n\t\treturn element.querySelector(\"[name='\" + name + \"']\");\n\t} catch (err) {\n\t\tdebugger;\n\t}\n}",
"pickComponent(scope, identifier) {\n const identifiers = getOrSet(this.repository, scope, () => new Map());\n return getOrSet(identifiers, identifier, () => {\n return new Component(scope);\n });\n }",
"async fieldMain(x, j) {\n assert(typeof x === 'string');\n assert(isAbsolute(x));\n assert(isObject(j));\n\n const y = dirname(x);\n const b = j[this.field];\n\n if (b === false || isString(b))\n return this.normalize(b, y);\n\n if (isString(j.main) && isObject(b)) {\n const m = await this.normalize(j.main, y);\n\n if (!m)\n return null;\n\n for (const k of Object.keys(b)) {\n const v = b[k];\n\n if (v !== false && !isString(v))\n continue;\n\n const x = await this.normalize(k, y);\n\n if (x && m === x)\n return this.normalize(v, y);\n }\n }\n\n return null;\n }",
"function field(obj, pathString) {\n if (!obj || typeof pathString !== 'string') return '';\n function fn(obj, path) {\n var prop = path.shift();\n if (!(prop in obj) || obj[prop] == null) return '';\n if (path.length) {\n return fn(obj[prop], path);\n }\n return String(obj[prop]);\n }\n return fn(obj, pathString.split('.'));\n}",
"function fromDotSeparatedString(path) {\n var found = path.search(RESERVED);\n if (found >= 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid field path (\" + path + \"). Paths must not contain \" +\n \"'~', '*', '/', '[', or ']'\");\n }\n try {\n return new (FieldPath$1.bind.apply(FieldPath$1, [void 0].concat(path.split('.'))))();\n }\n catch (e) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid field path (\" + path + \"). Paths must not be empty, \" +\n \"begin with '.', end with '.', or contain '..'\");\n }\n}",
"function getProductFromTemplate(string) {\n if (string.indexOf('governance') >= 0) {\n return 'idg';\n }\n else if (string.indexOf('commons') >= 0) {\n return 'commons';\n }\n else if (string.indexOf('access-request') >= 0) {\n return 'access-request';\n }\n else {\n __.requestError(\"template ids must include 'governance', 'access-request', or 'commons' in them.\", 500);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Stick to center top | setStickToCenterTop() {
this.logger.debug('setStickToCenterTop');
this.view.get$item().stickToCenterTop(this.controller.getContainment());
} | [
"setStickToCenterBottom() {\n this.logger.debug('setStickToCenterBottom');\n this.view.get$item().stickToCenterBottom(this.controller.getContainment());\n }",
"setStickToTopLeft() {\n this.logger.debug('setStickToTopLeft');\n this.view.get$item().stickToTopLeft(this.controller.getContainment());\n }",
"setStickToTopRight() {\n this.logger.debug('setStickToTopRight');\n this.view.get$item().stickToTopRight(this.controller.getContainment());\n }",
"setStickToCenterLeft() {\n this.logger.debug('setStickToCenterLeft');\n this.view.get$item().stickToCenterLeft(this.controller.getContainment());\n }",
"centerInParent() {\n this._x = (100 - this._width) / 2;\n this._y = (100 - this._height) / 2;\n }",
"setStickToBottomLeft() {\n this.logger.debug('setStickToBottomLeft');\n this.view.get$item().stickToBottomLeft(this.controller.getContainment());\n }",
"goToTopView() {\n this._camera.position.set(0, 1.5, 0);\n }",
"function moveLegTop(){\n if(leg.moveDone){\n // reset motion\n leg.vy=0;\n leg.move1=false;\n leg.move3=false;\n\n // paw facing down\n // invert shapes\n leg.paw=-abs(leg.paw);\n leg.h=-abs(leg.h);\n leg.extend=-abs(leg.extend);\n // set position\n legStartPos=-200;\n // start motion\n leg.move3=true;\n leg.moveDone=false;\n\n }\n}",
"goToTheTop () {\n window.scrollTo(0, 0)\n }",
"center() {\n if (this._fromFront) {\n this._updatePositionAndTarget(this._front, this._back);\n } else {\n this._updatePositionAndTarget(this._back, this._front);\n }\n\n this._updateMatrices();\n this._updateDirections();\n }",
"refreshCenter()\n {\n let { x, y } = this.editing == \"start\"? { x: this.rect.x1, y: this.rect.y1 }: { x: this.rect.x2, y: this.rect.y2 };\n x *= this.width;\n y *= this.height;\n this._handle.querySelector(\".crosshair\").setAttribute(\"transform\", `translate(${x} ${y})`);\n }",
"get top() {\n return this.pos.y - this.size.y / 2; // ball reflects\n }",
"setStickToBottomRight() {\n this.logger.debug('setStickToBottomRight');\n this.view.get$item().stickToBottomRight(this.controller.getContainment());\n }",
"function updateZeroForcePosition() {\n var pusherY = 362 - visibleNode.height;\n var x = layoutWidth / 2 + (model.pusherPosition - model.position) * MotionConstants.POSITION_SCALE;\n\n //To save processor time, don't update the image if it is too far offscreen\n if ( x > -2000 && x < 2000 ) {\n visibleNode.translate( x - visibleNode.getCenterX(), pusherY - visibleNode.y, true );\n }\n }",
"setCenter(x, y){ this.center.setPoint(x, y) }",
"function setSelfPosition() {\r\n var s = $self[0].style;\r\n\r\n // reset CSS so width is re-calculated for margin-left CSS\r\n $self.css({left: '50%', marginLeft: ($self.outerWidth() / 2) * -1, zIndex: (opts.zIndex + 3) });\r\n\r\n\r\n /* we have to get a little fancy when dealing with height, because lightbox_me\r\n is just so fancy.\r\n */\r\n\r\n // if the height of $self is bigger than the window and self isn't already position absolute\r\n if (($self.height() + 80 >= $(window).height()) && ($self.css('position') != 'absolute')) {\r\n\r\n // we are going to make it positioned where the user can see it, but they can still scroll\r\n // so the top offset is based on the user's scroll position.\r\n var topOffset = $(document).scrollTop() + 40;\r\n $self.css({position: 'absolute', top: topOffset + 'px', marginTop: 0})\r\n } else if ($self.height()+ 80 < $(window).height()) {\r\n //if the height is less than the window height, then we're gonna make this thing position: fixed.\r\n if (opts.centered) {\r\n $self.css({ position: 'fixed', top: '50%', marginTop: ($self.outerHeight() / 2) * -1})\r\n } else {\r\n $self.css({ position: 'fixed'}).css(opts.modalCSS);\r\n }\r\n if (opts.preventScroll) {\r\n $('body').css('overflow', 'hidden');\r\n }\r\n }\r\n }",
"setTopHalf() {\n let viewPort = {};\n viewPort.x = 0;\n viewPort.y = 0;\n viewPort.width = global.screen_width;\n viewPort.height = global.screen_height / 2;\n this._setViewPort(viewPort);\n this._screenPosition = GDesktopEnums.MagnifierScreenPosition.TOP_HALF;\n }",
"function centerModal() {\n var $dialog = $(this).find('.modal-dialog'),\n offset = ($('body').height() - $dialog.height()) / 2;\n $dialog.css(\"margin-top\", offset);\n }",
"function setMapContainerPosition()\n{\n var $top=($(window).height()-$('#map_container').height())/2;\n if($top<50)\n $top=50;\n $('#map_container').animate( { top: $top }, \"fast\");\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
`_isHeading` returns true if the given element is a ``. | _isHeading(elem) {
return elem.tagName.toLowerCase() === 'howto-accordion-heading';
} | [
"function getHeadingInfo(cell) {\n if (!(cell instanceof MarkdownCell)) {\n return { isHeading: false, headingLevel: 7 };\n }\n let level = cell.headingInfo.level;\n let collapsed = cell.headingCollapsed;\n return { isHeading: level > 0, headingLevel: level, collapsed: collapsed };\n }",
"function fnH5oGetSectionHeadingText(eltHeading) {\n var sEmpty = '', sTxt;\n if (fnH5oIsElmHeading(eltHeading)) {\n if (fnH5oGetTagName(eltHeading) === 'HGROUP') {\n eltHeading = eltHeading.getElementsByTagName('h' + (-fnH5oGetHeadingElmRank(eltHeading)))[0];\n }\n /* @todo: try to resolve text content from img[alt] or *[title] */\n sTxt = eltHeading.textContent;\n /* removes from heading the \"classHide\" content */\n sTxt = sTxt.replace(/\\n *¶$/, \"\");\n /* wikipedia specific */\n sTxt = sTxt.replace(/\\[edit\\]$/, \"\");\n sTxt = sTxt.replace(/\\[edit.*\\]$/, \"\");\n sTxt = sTxt.replace(/\\[Επεξεργασία.*\\]$/, \"\");\n return sTxt\n || eltHeading.innerText\n || \"<i>No text content inside \" + eltHeading.nodeName + \"</i>\";\n }\n return sEmpty + eltHeading;\n }",
"function guessHeader( data, isNumeric ) {\n\n // if there is just one row, we do not consider it a header\n if( data.length < 2 ) {\n return false;\n }\n\n // if we have at least one col, where the col is numeric and the first row is not,\n // then we assume, there is a header row\n if( data.length > 0 ) {\n for( var i=0; i<isNumeric.length; i++ ) {\n\n var cellIsNumeric = regexpNum.test( data[0][i].trim() );\n\n if( !cellIsNumeric && isNumeric[i] ) {\n return true;\n }\n\n }\n }\n\n return false;\n }",
"isEmpty(editor, element) {\n var {\n children\n } = element;\n var [first] = children;\n return children.length === 0 || children.length === 1 && Text.isText(first) && first.text === '' && !editor.isVoid(element);\n }",
"function _isLineBreakOrBlockElement(element) {\r\n if (_isLineBreak(element)) {\r\n return true;\r\n }\r\n\r\n if (wysihtml5.dom.getStyle(\"display\").from(element) === \"block\") {\r\n return true;\r\n }\r\n\r\n return false;\r\n }",
"function isStartOfSlide(elt)\n{\n if (elt.nodeType != 1) return false;\t\t// Not an element\n if (elt.classList.contains(\"slide\")) return true;\n if (window.getComputedStyle(elt).getPropertyValue('page-break-before') ==\n 'always') return true;\n if (elt.nodeName != \"H1\") return false;\n\n /* The element is an H1. It starts a slide unless it is inside class=slide */\n while (true) {\n elt = elt.parentNode;\n if (!elt || elt.nodeType != 1) return true;\n if (elt.classList.contains(\"slide\")) return false;\n }\n}",
"function extUtils_isCollapsibleTag(theTag)\n{\n var retVal = false;\n\n var collapsibleTagNames = \" P H1 H2 H3 H4 H5 H6 PRE BLOCKQUOTE TD TH DT DD CAPTION \";\n\n var upperTag = theTag.toString().toUpperCase();\n\n retVal = (collapsibleTagNames.indexOf(\" \"+upperTag+\" \") != -1);\n\n return retVal;\n}",
"containsHeaders(){\n return this.headerRow.length !== 0;\n }",
"function singleChildContentTagExists(element)\n{\n // Define a list of alloed tags for the inner content tag. There should be one and only one of these tags as element child\n var allowedContentTags = [\"blockquote\", \"dd\", \"div\", \"form\", \"center\", \"table\", \"span\", \"input\", \"textarea\", \"select\", \"img\"];\n\n\tif(element == undefined || element == null)\n\t\treturn false;\n\n\tif(element.hasChildNodes())\n\t{\n\t\tvar childCnt = element.childNodes.length;\n\t\tvar eltCount = 0;\n\n\t\tfor(var i=0; i<childCnt; i++)\n\t\t{\n\t\t\tvar potChildCurr = element.childNodes[i];\n\t\t\tvar nodeType = potChildCurr.nodeType;\n\t\t\tif(nodeType == 1) // element node\n\t\t\t{\n\t\t\t\ttagNameStr = potChildCurr.tagName.toLowerCase();\n if(dwscripts.findInArray(allowedContentTags, tagNameStr) == -1)\n\t\t\t\t\treturn false;\n\n\t\t\t\tif(eltCount == 0)\n\t\t\t\t\teltCount++\n\t\t\t\telse\n\t\t\t\t\treturn false;\n\t\t\t}\n\t\t\telse if(nodeType == 3) // Node.TEXT_NODE\n\t\t\t{\n\t\t\t\tif(potChildCurr.data.search(/\\S/) >= 0) // there is a non whitespace character available\n\t\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tif(eltCount==1)\n\t\t\treturn true;\n\t}\n\n\treturn false;\n}",
"function isHashtagTextChar(char) {\n return char === '_' || alphaNumericAndMarksRe.test(char);\n }",
"function headingRule(n) {\n\t var type = MarkupIt.BLOCKS['HEADING_' + n];\n\t return HTMLRule(type, 'h' + n);\n\t}",
"_panelForHeading(heading) {\n const next = heading.nextElementSibling;\n if (next.tagName.toLowerCase() !== 'howto-accordion-panel') {\n console.error('Sibling element to a heading need to be a panel.');\n return;\n }\n return next;\n }",
"function isElementDecorative(element, elementData) {\n if ($(element).attr(\"aria-hidden\") === \"true\") {\n return true;\n //TODO: this logic may need to change if screen readers support spec that says aria-label\n //\t\tshould override role=presentation, thus making it not decorative\n } else {\n if (elementData.role === \"presentation\" || elementData.role === \"none\") { //role is presentation or none\n return true;\n } else if ($(element).is(\"img\") && elementData.empty && elementData.empty.alt) { //<img> and empty alt\n return true;\n }\n }\n return false;\n }",
"function checkElementIsDisplayed(element) {\r\n if (element.tagName.toLowerCase() == \"title\") {\r\n //Always visible\r\n return;\r\n }\r\n if (!Utils.isDisplayed(element)) {\r\n throw {statusCode: 11, value: {message: \"Element was not visible\"}};\r\n }\r\n}",
"function extUtils_isAContainerTag(theTagName)\n{\n if ( !theTagName )\n return false;\n\n var tag = \" \" + theTagName.toUpperCase() + \" \";\n var containerTags = \" P H1 H2 H3 H4 H5 H6 LI LAYER DIV TD TABLE FORM PRE BLOCKQUOTE OL UL PRE BODY \";\n\n return ( containerTags.indexOf(tag) != -1);\n}",
"eatSpace() {\n let start = this.pos\n while (/[\\s\\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos\n return this.pos > start\n }",
"function determineHeading(){\n let player = determineTitle();\n\n // these conditions will never be true at the same time\n let checkMate = (props.checkMate ? \": CHECKMATE\" : \"\");\n let staleMate = (props.staleMate ? \": STALEMATE\" : \"\");\n\n // will not display \"CHECK\" if state is checkmate or stalemate\n let check = \"\";\n if ( !props.checkMate && !props.staleMate ){\n if ( props.inCheck )\n check = \": CHECK\";\n }\n else{\n check = \"\";\n }\n\n return player + checkMate + staleMate + check\n }",
"_expandHeading(heading) {\n heading.expanded = true;\n }",
"function isIdentifier(node) {\n return node.type === \"Identifier\";\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
close function for hamburger | function closeMenu(){
/*This remove the hamburger bar after body is clicked
$('.toggle').fadeOut(200);*/
$('.item').removeClass('active');
} | [
"function closeBurgerMenu() {\n $menuBurgerOverlay.removeClass('open');\n $body.removeClass('overflow');\n }",
"function openHamburger() {\n\t\t$(\"#hamburgerClass\").css(\"width\", \"250px\");\n}//end function openHamburger",
"function close()\n{\n\tif(menuitem) menuitem.style.visibility = 'hidden'; // hide the sub menu\n} // end function",
"function w3_close() {\n mySidebar.style.display = \"none\";\n }",
"function closeMobileMenu() {\n navMenuMobile.style.maxHeight = null;\n navMenuMobile.style.pointerEvents = 'none';\n bodyOverlay.style.opacity = 0;\n document.querySelector('body').style.overflow = 'unset';\n bodyOverlay.style.pointerEvents = 'none';\n navTriangle.style.display = 'none';\n}",
"function addCloseButtonFunctionality(){\n\t\t\t\n\t\t\t\n\t\t}",
"static openBarMenu(){\n $('.hamburger-menu').replaceWith('<i class=\"hamburger-menu fas fa-times fa-5x\"></i>');\n $('.projects-picker').toggleClass('visible');\n $('.projects-picker').toggleClass('hidden');\n $('.project-area').toggleClass('visible');\n $('.project-area').toggleClass('hidden');\n $('.hamburger-menu').on('click',this.closeBarMenu.bind(this));\n }",
"function closeAsideMenu_() {\n\n if ( asideBtn.classList.contains('presentation__aside-open--opened') )\n asideBtn.classList.remove('presentation__aside-open--opened');\n\n }",
"function collapseHamburger() {\n $('.nav-right-hamburger').toggleClass('on');\n $('.nav-right-collapse').toggleClass('on');\n }",
"function w3int_menu_close(evt)\n{\n //event_dump(evt, 'MENU-CLOSE');\n if ((evt.type == 'keyup' && evt.key == 'Escape') ||\n (evt.type == 'click' && evt.button != 2 )) {\n //console.log('w3int_menu_close '+ evt.type +' button='+ evt.button);\n w3int_menu_onclick(null, w3int_menu_close_cur_id);\n }\n}",
"async closeMenu() {\n const closeMenuLocator = await this.components.menuCloseButton()\n await closeMenuLocator.click()\n }",
"function handleBurgerMenu() {\n // console.log('`handleBurgerMenu` ran')\n $('.hamburger').on('click', function(event) {\n $('.navbar').toggleClass('menu-open')\n })\n}",
"function closeFavHandler(e){\n if(e.target.className === \"joke-finder joke-finder--not-active\"){\n toggleFav()\n }\n}",
"function openMenu() {\n if (header.classList.contains('open')) { // Open Hamburger Menu\n header.classList.remove('open');\n body.classList.remove('noscroll');\n fadeState('hidden');\n } else { // Close Hamburger Menu\n header.classList.add('open');\n body.classList.add('noscroll');\n fadeState('visible');\n }\n}",
"function closeUpdateUserInfoMenu() {\n console.log(\"Is closing\");\n\n // Remove the update backdrop and update menu from the view\n $(\"div\").remove('#update-user-info-backdrop');\n $(\"div\").remove('#update-user-info-menu');\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 _closeOpenManager() {\n $('#Roadin-step-manager--opener').click(function(e) {\n if($(this).hasClass('ion-ios-arrow-up')) {\n $(this).removeClass('ion-ios-arrow-up');\n $(this).addClass('ion-ios-arrow-down');\n $('.Roadin-step-manager').css({\n 'bottom' : 30 + 'px',\n 'transition-duration' : 0.3 + 's'\n });\n } else {\n $(this).removeClass('ion-ios-arrow-down');\n $(this).addClass('ion-ios-arrow-up');\n $('.Roadin-step-manager').css({\n 'bottom' : -150 + 'px',\n 'transition-duration' : 0.3 + 's'\n });\n }\n });\n }",
"close() {\n\t\tif( $('#gantt_container').css('bottom') != '-450px'){\n\t\t\t$('#not_gantt_container').addClass('full_height').removeClass('partial_height');\n\t\t\t$('#gantt_container').animate({bottom:'-450px'}, \"slow\", function() {\n\t\t\t\t$( '#gantt_button_text' ).addClass('rotate_0').removeClass('rotate_180');\n G.ganttManager.open = false;\n\t\t\t});\n\t\t\t$('#gantt_button').animate({bottom:'0px'}, \"slow\");\n\t\t}\n\t}",
"function closeLyrics() {\n lyricsBackdrop.classList.remove('visible');\n document.body.classList.remove('no-scroll');\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Yargs command handler for building a release. | function handler(args) {
return __awaiter(this, void 0, void 0, function* () {
const { npmPackages } = getReleaseConfig();
let builtPackages = yield buildReleaseOutput(true);
// If package building failed, print an error and exit with an error code.
if (builtPackages === null) {
error(red(` ✘ Could not build release output. Please check output above.`));
process.exit(1);
}
// If no packages have been built, we assume that this is never correct
// and exit with an error code.
if (builtPackages.length === 0) {
error(red(` ✘ No release packages have been built. Please ensure that the`));
error(red(` build script is configured correctly in ".ng-dev".`));
process.exit(1);
}
const missingPackages = npmPackages.filter(pkgName => !builtPackages.find(b => b.name === pkgName));
// Check for configured release packages which have not been built. We want to
// error and exit if any configured package has not been built.
if (missingPackages.length > 0) {
error(red(` ✘ Release output missing for the following packages:`));
missingPackages.forEach(pkgName => error(red(` - ${pkgName}`)));
process.exit(1);
}
if (args.json) {
process.stdout.write(JSON.stringify(builtPackages, null, 2));
}
else {
info(green(' ✓ Built release packages.'));
builtPackages.forEach(({ name }) => info(green(` - ${name}`)));
}
});
} | [
"function createRelease(envName, cb){\n mess.load(\"Creating/Updating release branch\");\n perf.start(\"Creating/Updating release branch\");\n git.getCurrentBranch((startingBranch) => {\n var releaseBranch = config.releaseName();\n if(startingBranch === releaseBranch) startingBranch = 'master';\n git.changes((changes) => {\n var ignored = config.ignoredFiles();\n if(changes && changes.ignored && ignored){\n ignored = ignored.filter((item) => {\n if(changes.ignored.indexOf(item) !== -1) return true;\n return false;\n })\n }else{\n ignored = null\n }\n git.hasBranch(releaseBranch, (hasBranch) => {\n addChangesToReleaseBranch(hasBranch, releaseBranch, ignored, () => {\n mess.status(\"Committing all changes\");\n git.commit(envName, () => {\n if(!hasBranch) mess.status(\"Publishing release branch\");\n else mess.status(\"Pushing release branch to remote\");\n git.push(releaseBranch, () => {\n mess.stopLoad(true);\n perf.end(\"Creating/Updating release branch\");\n mess.success(\"Finished creating/updating release branch\");\n return cb(startingBranch);\n })\n })\n })\n })\n })\n })\n}",
"function release() {\n /* get commits and make release note */\n githubHelper\n .getTags()\n .then(tags => githubHelper.getTagRange(tags))\n .then(_getCommitLogs)\n .then(_getCommitsWithExistingGroup)\n .then(_makeReleaseNote)\n .then(releaseNote => githubHelper.publishReleaseNote(releaseNote))\n ['catch'](error => console.error(error.message));\n}",
"addRelease({ addToStart = true, date, status, version }) {\n if (!version) {\n throw new Error('Version required');\n }\n else if (semver_1.default.valid(version) === null) {\n throw new Error(`Not a valid semver version: '${version}'`);\n }\n else if (this._changes[version]) {\n throw new Error(`Release already exists: '${version}'`);\n }\n this._changes[version] = {};\n const newRelease = { version, date, status };\n if (addToStart) {\n this._releases.unshift(newRelease);\n }\n else {\n this._releases.push(newRelease);\n }\n }",
"async build (opts) {\n const wrapper = path.join(this.root, 'gradlew');\n const args = this.getArgs(opts.buildType === 'debug' ? 'debug' : 'release', opts);\n\n events.emit('verbose', `Running Gradle Build: ${wrapper} ${args.join(' ')}`);\n\n try {\n return await execa(wrapper, args, { stdio: 'inherit', cwd: path.resolve(this.root) });\n } catch (error) {\n if (error.toString().includes('failed to find target with hash string')) {\n // Add hint from check_android_target to error message\n try {\n await check_reqs.check_android_target(this.root);\n } catch (checkAndroidTargetError) {\n error.message += '\\n' + checkAndroidTargetError.message;\n }\n }\n throw error;\n }\n }",
"function url_build () {\n return spawn('python',\n ['./lib/python/change_url.py', 'build'], {stdio: 'inherit'})\n}",
"function prepare() {\n var releases = [];\n\n // release:env\n envs.forEach(function (env) {\n var _tasks = [];\n // all apps with `env` settings\n apps.forEach(function (app) {\n _tasks.push('release:' + app + ':' + env);\n });\n releases.push({\n task: 'release:' + env,\n arr : _tasks\n });\n });\n\n // release:app1\n apps.forEach(function (app) {\n // `app` with dev settings\n releases.push({\n task: 'release:' + app,\n arr : ['release:' + app + ':dev']\n });\n });\n\n // release:app1:env\n apps.forEach(function (app) {\n envs.forEach(function (env) {\n releases.push({\n task: 'release:' + app + ':' + env,\n arr : ['release:' + app + ':' + env]\n });\n });\n });\n\n var _tasks = [];\n apps.forEach(function (app) {\n _tasks.push('release:' + app + ':dev');\n });\n\n releases.push({\n task: 'release',\n arr : _tasks\n });\n\n return releases;\n}",
"async createBuild({\n resources = []\n } = {}) {\n this.log.debug('Creating a new build...');\n return this.post('builds', {\n data: {\n type: 'builds',\n attributes: {\n branch: this.env.git.branch,\n 'target-branch': this.env.target.branch,\n 'target-commit-sha': this.env.target.commit,\n 'commit-sha': this.env.git.sha,\n 'commit-committed-at': this.env.git.committedAt,\n 'commit-author-name': this.env.git.authorName,\n 'commit-author-email': this.env.git.authorEmail,\n 'commit-committer-name': this.env.git.committerName,\n 'commit-committer-email': this.env.git.committerEmail,\n 'commit-message': this.env.git.message,\n 'pull-request-number': this.env.pullRequest,\n 'parallel-nonce': this.env.parallel.nonce,\n 'parallel-total-shards': this.env.parallel.total,\n partial: this.env.partial\n },\n relationships: {\n resources: {\n data: resources.map(r => ({\n type: 'resources',\n id: r.sha || (0, _utils2.sha256hash)(r.content),\n attributes: {\n 'resource-url': r.url,\n 'is-root': r.root || null,\n mimetype: r.mimetype || null\n }\n }))\n }\n }\n }\n });\n }",
"function publishDist() {\n log('Running NPM publish');\n return runNPMProcess('release');\n }",
"static create(ndrVersion, ...args) {\n\n }",
"async function checkoutRelease(alternate) {\n console.log(\"Checking out the release branch...\");\n\n // Make sure we're on a release branch that matches dev\n if (shell.exec('git checkout release').code !== 0) {\n if (shell.exec('git checkout -b release').code !== 0) {\n console.log('Could not switch to the release branch. Make sure the branch exists locally.');\n process.exit(1);\n }\n }\n\n // Make sure we have the latest from the remote\n if (shell.exec('git fetch --all').code !== 0) {\n console.log('Could not fetch from remote servers.');\n process.exit(1);\n }\n\n console.log(\"Resetting the release branch to the latest contents in dev...\");\n // Make sure we are exactly what is in dev\n if (shell.exec(`git reset --hard ${ENSURE_REMOTE}/dev${alternate ? `-${alternate}` : \"\"}`).code !== 0) {\n console.log(`Could not reset branch to dev${alternate ? `-${alternate}` : \"\"}`);\n process.exit(1);\n }\n}",
"function getTargetVersion(currentVersion, release) {\n if (['major', 'premajor', 'minor', 'preminor', 'patch', 'prepatch', 'prerelease'].includes(release)) {\n return semver.inc(currentVersion, release);\n } else {\n return semver.valid(release);\n }\n}",
"__build_topic(house_id, from_module, to_module, command, args) {\r\n if (args == \"\") args = \"null\"\r\n return [\"egeoffrey\", \"v\"+this.__module.gateway_version, house_id, from_module, to_module, command, args].join(\"/\")\r\n }",
"function createYargsTemplate(yargs) {\n return yargs\n .help()\n .option('number', {\n alias: 'n',\n type: 'number',\n default: 1,\n description: 'The number of generated data'\n }).option('model', {\n alias: 'm',\n type: 'string',\n coerce: it => it ? path.resolve(it) : undefined,\n describe: 'The file to input the data model'\n }).option('output', {\n alias: 'o',\n type: 'string',\n coerce: it => it ? path.resolve(it) : undefined,\n describe: 'The file to write the output'\n })\n}",
"function runPublishScript() {\n\n const script = [];\n\n // merge dev -> master\n script.push(\n \"git checkout dev\",\n \"git pull\",\n \"git checkout master\",\n \"git pull\",\n \"git merge dev\",\n \"npm install\");\n\n // version here to all subsequent actions have the new version available in package.json\n script.push(\"npm version patch\");\n\n // push the updates to master (version info)\n script.push(\"git push\");\n\n // package and publish to npm\n script.push(\"gulp publish:packages\");\n\n // merge master back to dev for updated version #\n script.push(\n \"git checkout master\",\n \"git pull\",\n \"git checkout dev\",\n \"git pull\",\n \"git merge master\",\n \"git push\");\n\n // always leave things on the dev branch\n script.push(\"git checkout dev\");\n\n return chainCommands(script);\n}",
"function main() {\n\tconsole.log('Abacus iPad App Generator.');\n console.log('Create flat basic styled app from converted spreadhseet.');\n\tDU.displayTag();\n\n\tif(ops.version){\n\t\tprocess.exit();\n\t}\n\n\tif(!ops.repoPath){\n\t\tconsole.error('Missing argument: --repoPath');\n\t\tops.printHelp();\n\t\tprocess.exit(-2);\n\t}\n\n\tif(!ops.engine){\n\t\tconsole.error('Missing argument: --engine');\n\t\tops.printHelp();\n\t\tprocess.exit(-2);\n\t}\n\n\tif (ops.instance){\n\t\tconfig.instance = S(ops.instance).slugify().s;\n\t}\n\n\tif(ops.language){\n\t\tconfig.language = ops.language;\n\t}\n\n\tif(ops.noExtract){\n\t\tconfig.extractEngine = false;\n\t}\n\n\tif(ops.numeric){\n\t\tconfig.usePageNames = false;\n\t}\n\n\t// mandatory arguments\n\tconfig.repoPath = ops.repoPath;\n\tconfig.engineFile = ops.engine;\n\n\t// call extract, pass in config\n\tAG.generate(config);\n}",
"function openRelease() {\n jetpack.tabs.open(releaseLink);\n jetpack.tabs[jetpack.tabs.length - 1].focus();\n}",
"postArchitectDependencytrackingBuild() { \n\n\t\treturn this.apiClient.callApi(\n\t\t\t'/api/v2/architect/dependencytracking/build', \n\t\t\t'POST', \n\t\t\t{ },\n\t\t\t{ },\n\t\t\t{ },\n\t\t\t{ },\n\t\t\tnull, \n\t\t\t['PureCloud OAuth'], \n\t\t\t['application/json'],\n\t\t\t['application/json']\n\t\t);\n\t}",
"function makeArgChanges() {\n //Only do the alterations if the arguments indicate a real or preview\n //run of the program will be executed.\n validateArgs();\n if (-1 !== aargsGiven.indexOf('-repo')) {\n oresult.srepo = PATH.normalize(oresult.srepo);\n if ('' === oresult.sdest) {\n oresult.sdest = oresult.srepo;\n } else {\n oresult.sdest = PATH.normalize(oresult.sdest);\n }\n oresult.sdest = oresult.sdest + PATH.sep +\n oresult.srepo.split(PATH.sep).pop() + '_cDivFiles';\n oresult.aign.push(CDIVUTILS.createGlobRegex(oresult.sdest + '*'));\n }\n }",
"function buildAndPushImage(name, pathOrBuild, args, opts) {\n const repo = new Repository(name, args, opts);\n const image = repo.buildAndPushImage(pathOrBuild);\n return new repositoryImage_1.RepositoryImage(repo, image);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate an external link (icon only) | function setExternalLinkIcon(url) {
return '<a href="'+url+'" class="glyphicon glyphicon-new-window external-link" title="External link" target="_blank"></a>';
} | [
"function getIconUrl(entry) {\n\tvar url = entry.iconurl;\n\tif (!url)\n\t\t// unknown - relative to HTML\n\t\treturn \"icons/_blank.png\";\n\t\n\t// Used on this device: \n\t// build global address (with prefix), \n\t// but try cache if possible (from cache path and prefix)\n\tif (entry.iconpath && entry.prefix) {\n\t\treturn entry.prefix+entry.iconpath;\n\t}\n\treturn getInternetUrl(entry, url);\n}",
"function complianceURL(name, url) {\n return '<a href=\"' + url + '\" target=\"_blank\">' + ' <i class=\"far fa-3x fa-folder-open\"></i></a>'\n }",
"_getLinkURL() {\n let href = this.context.link.href;\n\n if (href) {\n // Handle SVG links:\n if (typeof href == \"object\" && href.animVal) {\n return this._makeURLAbsolute(this.context.link.baseURI, href.animVal);\n }\n\n return href;\n }\n\n href = this.context.link.getAttribute(\"href\") ||\n this.context.link.getAttributeNS(\"http://www.w3.org/1999/xlink\", \"href\");\n\n if (!href || !href.match(/\\S/)) {\n // Without this we try to save as the current doc,\n // for example, HTML case also throws if empty\n throw \"Empty href\";\n }\n\n return this._makeURLAbsolute(this.context.link.baseURI, href);\n }",
"function getLink() {\n var instruction = gettext(\"This link will open the interactive with your set productions:\");\n var productions = $(\"#cfg-grammar-input\").val().trim();\n if (productions.length <= 0) {\n $(\"#cfg-grammar-link\").html(\"\");\n return;\n }\n var productionsParameter = percentEncode(productions.replace(/\\n/g, ' '));\n var otherParameters = \"\";\n if ($(\"#examples-checkbox\").prop('checked')){\n var examples = $(\"#cfg-example-input\").val().trim();\n if (examples.length > 0) {\n otherParameters += '&examples=' + percentEncode(examples.replace(/\\n/g, '|'));\n }\n }\n if (!$(\"#generator-checkbox\").prop('checked')){\n otherParameters += '&hide-generator=true';\n if (!$(\"#examples-checkbox\").prop('checked')) {\n otherParameters += '&editable-target=true';\n }\n }\n // When the user switches between generator types a # appears at the end of the url\n // This needs to be removed for the new link, or not added in the first place:\n var basePath = window.location.href.split('?', 1)[0].replace(/\\#+$/g, '');\n var fullUrl = basePath + \"?productions=\" + productionsParameter + otherParameters;\n $(\"#cfg-grammar-link\").html(`${instruction}<br><a target=\"_blank\" href=${fullUrl}>${fullUrl}</a>`);\n}",
"function dmlWriteShapeInfoLink(myLinkText, myLinkUrl) {\n\tvar myResult;\n\tif (myLinkText == '.' || myLinkUrl == '.') {\n\t\tmyResult = '';\n\t} else {\n\t\tmyResult = '<a href=\"' + myLinkUrl + '\" target=\"blank\">' + myLinkText + '</a><br>';\n\t}\n\treturn myResult;\n}",
"function guest_airbnb_url_create(data, type, row, meta) {\n url = \"https://www.airbnb.com/users/show/\" + row.id + \"\";\n data = '<a target=\"_blank\" href=\"' + url + '\">' + data + \"</a>\";\n return data;\n}",
"get icon_url() {\n return this.args.icon_url;\n }",
"function guest_url_create(data, type, row, meta) {\n url = \"https://app.guesty.com/reservations/\" + row._id + \"/inbox\"\n data = '<a target=\"_blank\" href=\"' + url + '\">' + data + '</a>';\n return data;\n}",
"function build_pintrest_link(img_src,domain) {\n\n // https://pinterest.com/pin/create/button/?url=http://hopetracker.com/inspiration/?og_img=/site/public/images/quotes/quote.choosing_peace.jpg&media=http://hopetracker.com/site/public/images/quotes/quote.choosing_peace.jpg\n /** base part of the pintrest share url */\n var returnValue = \"https://pinterest.com/pin/create/button/?url=\" + domain + \"/inspiration/?og_img=\";\n\n /** add the current image slide to the share link*/\n returnValue += img_src;\n\n /** add final part of the pintrest url */\n returnValue += \"&media=\" + domain + \"/\" + img_src;\n\n /** Sets the pintrest share link value */\n $(pintrest_link).attr('href',returnValue);\n\n }",
"function repoLink(name) {\n return '<a class=\"repo\" href=\"https://github.com/'+name+'\">'+name+'</a>';\n}",
"linkMD( text, url ) {\n if (url && url.trim()) { return (`[${text}](${url})`); } else { return text; }\n }",
"function displayWebsiteLink() {\n\t\tvar formattedWebsite = HTMLwebsite.replace('%data%', bio.contacts.website).replace('#', bio.contacts.websiteURL);\n\t\t$('#topContacts').append(formattedWebsite);\n\t\t$('#footerContacts').append(formattedWebsite);\n\t}",
"function createIconWrapper(i, locationObject) {\n let tempIcon = locationObject.siteIcon;\n let tempName = locationObject.siteName;\n let tempURL = locationObject.url;\n let wrapper = \"\";\n if (tempURL === null) {\n // DISPLAY NONE\n wrapper = `<a href=\"${tempURL}\" class=\"iz-i m-s d-n\">\n <img src=\"${tempIcon}\" alt=\"${tempName}\" title=\"${tempName}\" class=\"br bd-g e-g-hv h-f w-f s-hv d-n\">\n </a>`;\n }\n else {\n wrapper = `<a href=\"${tempURL}\" class=\"iz-i m-s\">\n <img src=\"${tempIcon}\" alt=\"${tempName}\" title=\"${tempName}\" class=\"br bd-g e-g-hv h-f w-f p-s s-hv\">\n </a>`;\n }\n return wrapper;\n }",
"function mapUrlLink(photo) {\n return 'https://farm' + photo.farm + '.staticflickr.com/' + photo.server + '/' + photo.id + '_' + photo.secret + '_b.jpg';\n }",
"function SocialLink(icon, link, tooltip) {\n var self = this;\n self.icon = icon;\n self.link = link;\n self.tooltip = tooltip;\n}",
"function createLink() {\r\n if (!validateMode()) return;\r\n \r\n var isA = getEl(\"A\",Composition.document.selection.createRange().parentElement());\r\n if(isA==null){\r\n\tvar str=prompt(\"Укажите адрес :\",\"http:\\/\\/\");\r\n\t \r\n\tif ((str!=null) && (str!=\"http://\")) {\r\n\t\tvar sel=Composition.document.selection.createRange();\r\n\t\tif (Composition.document.selection.type==\"None\") {\r\n\t\t\tsel.pasteHTML('<A HREF=\"'+str+'\">'+str+'</A>');\r\n\t\t}else {\r\n\t\t\tsel.execCommand('CreateLink',\"\",str);\r\n\t }\r\n\t\tsel.select();\r\n\t}\r\n } else {\r\n\tvar str=prompt(\"Укажите адрес :\",isA.href);\r\n\r\n\tif ((str!=null) && (str!=\"http://\")) isA.href=str;\r\n\r\n }\r\n\r\nComposition.focus();\r\n}",
"function externalLinks() \n{\n\t$('a[rel*=external]').live(\"click\", function() {\n\t\twindow.open(this.href);\n\t\treturn false;\n\t});\n}",
"function generateURL(id) {\n return `https://picsum.photos/id/${id}/400`;\n }",
"function buildAllExternalLinksRes(res) {\n res.writeHead(200, {'Content-Type': 'text/plain'});\n res.write('External Links:\\n');\n for (var i = 0; i < json.length; i++) {\n var tweet = json[i].text;\n var urls = tweet.match(new RegExp('(https?|ftp)://(www\\d?|[a-zA-Z0-9]+)?\\.[a-zA-Z0-9-]+(\\:|\\.)([a-zA-Z0-9.]+|(\\d+)?)([/?:].*)?', 'gi'));\n if (urls != null) {\n for (var j = 0; j < urls.length; j++) {\n var link = urls[j].split('\\\"').join('');\n res.write('<a href=\"' + link + '\">' + link + '</a>\\n');\n }\n }\n }\n res.end();\n}",
"function GetLinkStr(link, key, type)\n{\n var o = '';\n if (IsViewer())\n {\n o += GL(key);\n }\n else\n {\n o += GetContentLink(key, link, type);\n }\n return o;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Look up a translation for the given phrase (via the / [`phrases`](state.EditorState^phrases) facet), or return the / original string if no translation is found. | phrase(phrase) {
for (let map of this.facet(EditorState.phrases))
if (Object.prototype.hasOwnProperty.call(map, phrase))
return map[phrase];
return phrase;
} | [
"phrase(phrase) {\n for (let map of this.facet(dist_EditorState.phrases))\n if (Object.prototype.hasOwnProperty.call(map, phrase))\n return map[phrase];\n return phrase;\n }",
"function displayPhrase(id) {\n if (id != null) {\n var phrase = phrases[id];\n\n if (phrase != null)\n document.getElementById(\"translation-box\").innerHTML =\n \"<b>\" + phrase[0] + \"</b> \" + phrase[1];\n }\n}",
"phrase(phrase, ...insert) {\n for (let map of this.facet(EditorState.phrases))\n if (Object.prototype.hasOwnProperty.call(map, phrase)) {\n phrase = map[phrase]\n break\n }\n if (insert.length)\n phrase = phrase.replace(/\\$(\\$|\\d*)/g, (m, i) => {\n if (i == '$') return '$'\n let n = +(i || 1)\n return !n || n > insert.length ? m : insert[n - 1]\n })\n return phrase\n }",
"function translate(key) {\n var lang = getLang(),\n text = translations[key];\n\n if (typeof text === 'undefined') {\n if (SC_DEV) { console.log('Unable to get translation for text code: \"'+ key + '\" and language: \"' + lang + '\".'); }\n return '-';\n }\n\n return text;\n }",
"function translate(text, dictionary){\n\t// TODO: implementați funcția\n\t// TODO: implement the function\n}",
"function translate (phrase) {\n var newPhrase = \" \";\n for (var count = 0; count < phrase.length; count++) {\n var letter = phrase[count];\n if (cleanerIsVowel(letter) || letter === \" \") {\n newPhrase += letter;\n } else {\n newPhrase += letter + \"o\" + letter;\n }\n return newPhrase;\n}\n\n translate(\"these are some words\");\n}",
"function gettext(msgid) {\n if (bundle) {\n if (typeof bundle[msgid] === \"string\") {\n return bundle[msgid];\n }\n console.warn(\"[i18n]\", bundle_path, msgid, undefined);\n }\n return msgid;\n}",
"function translate(text, dictionary){\n\t// TODO: implementați funcția\n\t// TODO: implement the function\n\t\n\t\n\t\tif (typeof text !== 'string'){\n\t\t\tthrow new Error(\"InvalidType\")\n\t\t}\n\t\tif (typeof dictionary !== 'object' || !dictionary){\n\t\t\tthrow new Error(\"InvalidType\")\n\t\t}\n\t\t// for (let prop in dictionary){\n\t\t// if (typeof dictionary[prop] !== 'string'){\n\t\t// \tthrow new Error('InvalidType')\n\t\t// }\n\t\t// }\n\t\tfor(let i =0;i<dictionary.length;i++){\n\t\t\tif(typeof dictionary[i] !== 'string'){\n\t\t\t\tthrow new Error(\"InvalidType\")\n\t\t\t}\n\t\t}\n\t\t\n\t\n\tlet value = text.split(' ')\n\n\tfor (let index in dictionary){\n\t\tlet position = value.indexOf(index)\n\t\tif (position !== -1){\n\t\t\tvalue[position] = dictionary[index]\n\t\t}\t\n\t}\n\treturn value.join(' ')\n}",
"async function getTranslatedString(string, targetLang){\n AWS.config.region = \"us-east-1\";\n var ep = new AWS.Endpoint(\"https://translate.us-east-1.amazonaws.com\");\n AWS.config.credentials = new AWS.Credentials(\"AKIAJQLVBELRL5AAMZOA\", \"Kl0ArGHFySw+iBEdGXZDrTch2V5VAaDbSs+EKKEZ\");\n var translate = new AWS.Translate();\n translate.endpoint = ep;\n var params = {\n Text: string,\n SourceLanguageCode: \"en\",\n TargetLanguageCode: targetLang\n };\n var promise = new Promise((resolve, reject)=>{\n translate.translateText(params, (err, data)=>{\n if (err) return reject(err);\n else {\n return resolve(data);\n }\n });\n });\n var result = await promise;\n return result.TranslatedText;\n}",
"function getStringBasedOnLocale(langDictKey, stringKey, obj) {\n return substitute(langDictionary['en'][langDictKey][stringKey], obj || {}) || '[UNKNOWN]';\n }",
"function load(word) {\n if (word == null) {\n word = wordsJSON.words[Math.floor(Math.random() * wordsJSON.words.length)].toki_pona;\n }\n\n var translations = getWord(word);\n\n document.getElementById('out1').innerHTML = translations[0] + ' = ' + translations[1];\n document.getElementById('out2').innerHTML = '';\n\n if (translations[2] != '') {\n document.getElementById('out2').innerHTML = 'also: ' + translations[2];\n }\n}",
"getTranslationString(type) {\n let userString;\n let tts = this.get('typeToString');\n userString = tts[type];\n\n if (userString === undefined) {\n for (let ts in tts) {\n if (type.toLowerCase().indexOf(ts) !== -1) {\n userString = tts[ts];\n break;\n }\n }\n }\n\n if (userString === undefined) {\n userString = type;\n }\n\n return userString;\n }",
"function getPhraseIndex(arr){\n const phraseIndex = arr.indexOf(chosenPhrase);\n return phraseIndex;\n}",
"function getTranslation(term){\n\tvar query = \"http://api.wordreference.com/0.8/22816/json/fren/\"+ term; \n\n\tvar result = $.ajax({\n\t url: query,\n\t type:'GET',\n\t dataType:'JSONP',\n\t success: function(data){\n\t var translation = data[\"term0\"][\"PrincipalTranslations\"][\"0\"][\"FirstTranslation\"][\"term\"]\n //Add the term to the terms div\n $('#addingterms').append('<div class=\"selection\"><span class=\"label\">Term:</span> <span class=\"justadded\">' + term + ' </span></div>');\n //Add the definition to definitions div\n\t $('#addingdefinitions').append('<div class=\"selection\"><span class=\"label\">Definition:</span> '+ translation + \"</div>\");\n termsArray.push(term);\n definitionsArray.push(translation);\n\n\t }\n\t});\n}",
"function randomPhrase (phrases){\r\n\treturn phrases[Math.floor(Math.random()*phrases.length)];\r\n\t}",
"function translate(messageParts, substitutions) {\n const message = parseMessage(messageParts, substitutions);\n const translation = $localize.TRANSLATIONS[message.translationKey];\n const result = (translation === undefined ? [messageParts, substitutions] : [\n translation.messageParts,\n translation.placeholderNames.map(placeholder => message.substitutions[placeholder])\n ]);\n return result;\n}",
"function selectPhrase(editArea)\r\n{\r\n var startPos = editArea.selectionStart;\r\n var endPos = editArea.selectionEnd;\r\n var selPhrase = editArea.value.substring(startPos, endPos);\r\n var _phrase = document.getElementById('phrase');\r\n if (_phrase)\r\n {\r\n _phrase.value = selPhrase;\r\n } \r\n}",
"function leetspeak(text) {\n\tlet translatableChars = ['A', 'E', 'G', 'L', 'O', 'S', 'T'];\n\tlet translatedChars = [4, 3, 6, 1, 0, 5, 7];\n\tlet translatedText = '';\n\tlet translated = false;\n\tfor (let i = 0; i < text.length; i++) {\n\t\tfor (let j = 0; j < translatableChars.length; j++) {\n\t\t\tif (text[i].toLowerCase() == translatableChars[j].toLowerCase()) {\n\t\t\t\ttranslatedText += translatedChars[j];\n\t\t\t\ttranslated = true;\t\n\t\t\t}\n\t\t}\n\t\tif (!translated) {\n\t\t\ttranslatedText += text[i];\n\t\t\ttranslated = false;\t\n\t\t}\t\t\n\t}\n\treturn translatedText;\n}",
"function translation() {\n return gulp\n .src(theme.php.src)\n .pipe(wpPot({\n domain: 'wpg_theme',\n package: 'Powiat Bartoszycki',\n bugReport: 'http:/powiatbartoszyce.pl'\n }))\n .pipe(gulp.dest(theme.lang.dist + 'powiat-bartoszycki.pot'))\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper returns a function that can only be called 10 times before it throws an error | function protectAgainstInfiniteLoops(func) {
var counter = 0;
return function() {
counter += 1;
if (counter > 10) {
throw new Error("Infinite loop");
}
return func.apply(null, arguments);
};
} | [
"retry (fn, max, errorFunc) {\n const f = async () => {\n let error;\n for (let i = 0; i < max; i++) {\n try {\n return await fn();\n } catch (e) {\n if (this.debugging) {\n // eslint-disable-next-line\n debugger;\n }\n console.log(`caught ${i}`)\n if (errorFunc && !errorFunc(e)) {\n throw e;\n }\n error = e;\n }\n }\n console.log('out of retries');\n throw error;\n }\n return f()\n }",
"function retryUntil_(self, f, __trace) {\n return retryUntilM_(self, a => core.succeed(f(a)), __trace);\n}",
"function repeat(fn, n) {\nfor(let i=0; i<n; i++) {\n\tfn();\n}\n\n}",
"function trials (test, minSuccess = 10) {\n let success = 0\n for (let t = 0; t < 10; t++) {\n success += test() ? 1 : 0\n }\n assert(success >= minSuccess)\n }",
"static failRetry(){\r\n let fatus = Fatusjs.instance;\r\n fatus.getFailSize(function onGet(err,count){\r\n if(count && count >0){\r\n console.log(MODULE_NAME + ': adding fail worker');\r\n fatus.addFailWorker();\r\n }\r\n });\r\n fatus.getQueueSize(function onGet(err,count){\r\n if(count && count >0){\r\n console.log(MODULE_NAME + ': adding collector' )\r\n fatus.addCollector();\r\n }\r\n })\r\n }",
"function fireEvery() {\n var currentCount = 0;\n return function(steps) {\n if (currentCount >= steps) {\n currentCount = 0;\n return true;\n } else {\n currentCount++;\n return false;\n }\n };\n}",
"repeat (n, f, o) { for (let i = 0; i < n; i++) f(i, o); return o }",
"function OneShotLimitReached()\n{\n\treturn (crashesStarted + gearShiftsStarted) > oneShotLimit;\n}",
"function retry(func, options) {\n options = options || {};\n\n var interval = typeof options.interval === 'number' ? options.interval : 1000;\n\n var max_tries, giveup_time;\n if (typeof(options.max_tries) !== 'undefined') {\n max_tries = options.max_tries;\n }\n\n if (options.timeout) {\n giveup_time = new Date().getTime() + options.timeout;\n }\n\n if (!max_tries && !giveup_time) {\n max_tries = 5;\n }\n\n var tries = 0;\n var start = new Date().getTime();\n\n function try_once() {\n var tryStart = new Date().getTime();\n return Promise.try(function () {\n return func();\n })\n .catch(function (err) {\n if (err instanceof StopError) {\n if (err.err instanceof Error) {\n return Promise.reject(err.err);\n } else {\n return Promise.reject(err);\n }\n }\n ++tries;\n if (tries > 1) {\n interval = backoff(interval, options);\n }\n var now = new Date().getTime();\n\n if ((max_tries && (tries === max_tries) ||\n (giveup_time && (now + interval >= giveup_time)))) {\n var timeout = new Error('operation timed out after ' + (now - start) + ' ms, ' + tries + ' tries' + ' failure: ' + err.message);\n timeout.failure = err;\n timeout.code = 'ETIMEDOUT';\n timeout.stack = err.stack;\n return Promise.reject(timeout);\n } else {\n var delay = interval - (now - tryStart);\n if (delay <= 0) {\n return try_once();\n } else {\n return Promise.delay(delay).then(try_once);\n }\n }\n });\n }\n\n return try_once();\n}",
"function repeat(action, times, argument) {\n let count = 0;\n\n const repeater = (arg) => {\n if (count >= times) {\n return arg;\n }\n\n count++;\n\n return action(arg).then(repeater);\n };\n\n return repeater(argument);\n}",
"function rand10() {\n return rand5() + rand5() - 3;\n}",
"function RetrySendRequest(serviceObj, callbackFunc) {\n if (serviceObj.retryCounter >= MAX_FAILED_SERVICE_RETRIES) {\n return false;\n }\n\n setTimeout(function () { handleLiveService(serviceObj, callbackFunc); }, 500);\n return true;\n}",
"function simulate() {\n for (let i = 1; i <= 5; i++) {\n test(i)\n }\n}",
"function rollCall(names) {\n let counter = 0;\n return () => {\n if (counter < names.length) {\n console.log(names[counter]);\n counter++;\n } else {\n console.log(\"Everyone accounted for\");\n }\n };\n}",
"function addrof(val) {\n for (var i = 0; i < 100; i++) {\n var result = addrofInternal(val);\n if (typeof result != \"object\" && result !== 13.37){\n return result;\n }\n }\n \n print(\"[-] Addrof didn't work. Prepare for WebContent to crash or other strange stuff to happen...\");\n throw \"See above\";\n}",
"function resetLARRY(){\n let times = 10; //number of quack\n \n for(var i = 0; i < 10; i++){\n LARRY.quack();\n }\n}",
"throttle (n) {\n return throttle(n, this)\n }",
"function incrementoError()\n\t{\n\t\tif(presente === false)\n\t\t{\n\t\t\tmasUnError();//Instanciar la función que aumenta los fallos acumulados.\n\t\t}\n\t}",
"function wrongAnswer() {\n interval -= 10;\n}",
"function callCount() {\n let counter = 0;\n return function() {\n counter++;\n return counter;\n };\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructs a new ConfigHash. | constructor() {
ConfigHash.initialize(this);
} | [
"function NewHash() {\n return blakejs_1[\"default\"].blake2bInit(32, null);\n}",
"function Configuration(props) {\n return __assign({ Type: 'AWS::AmazonMQ::Configuration' }, props);\n }",
"function Config(obj) {\n if (!(this instanceof Config)) {\n return new Config(obj)\n }\n\n obj = obj || {}\n\n this.data = null\n this._loadObj(obj)\n}",
"constructAxiosRequestConfig() {\n const input = this._getInput(this.edge);\n const config = {\n url: this._getUrl(this.edge, input),\n params: this._getParams(this.edge, input),\n data: this._getRequestBody(this.edge, input),\n method: this.edge.query_operation.method,\n timeout: 50000\n }\n this.config = config;\n return config;\n }",
"function Config(action) {\n trace(whoAmI,\"Constructor\",true);\n\n var fName = \"cva-create.json\";\n var homeEnv = (utils.isWindows) ? 'USERPROFILE' : 'HOME';\n var homePath = process.env[homeEnv];\n\n // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n // Check that the user's home path can be identified\n // If this fails, then throw toys out of pram, pack up and go home\n // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n if (!homePath || homePath.length == 0) {\n utils.writeToConsole('error',\n [[\"\\nUser home directory cannot be identified!\".error],\n [\"Please set the environment variable \" + homeEnv + \" to a valid location\"]]);\n process.exit(1);\n }\n\n var localConfigFile = path.join(\".\", fName);\n var globalConfigFile = path.join(homePath, fName);\n \n this.configFiles.globalConfig.path = globalConfigFile\n this.configFiles.globalConfig.exists = fs.existsSync(globalConfigFile);\n\n this.configFiles.localConfig.path = localConfigFile;\n this.configFiles.localConfig.exists = fs.existsSync(localConfigFile);\n \n // Does the global config file already exist?\n if (this.configFiles.globalConfig.exists) {\n // Yup, so read that file and merge its contents with values from the prototype.\n // The merge guarantees that all property values exist and have at least a\n // default value\n mergeProperties(\"global\",utils.readJSONFile(this.configFiles.globalConfig.path), this);\n }\n else {\n // Nope, so create a global configuration file\n generateGlobalConfig(this);\n }\n \n // Now read the local configuration file and merge its contents with the global values\n mergeProperties(\"local\",utils.readJSONFile(this.configFiles.localConfig.path), this);\n\n trace(whoAmI,\"Constructor\",false);\n}",
"function createInstance() {\n /**\n * Initialize the configuration.\n *\n * @method module:ConfigurationHandler#init\n * @param {string} region - REGION name where the App Configuration service instance is\n * created.\n * @param {string} guid - GUID of the App Configuration service.\n * @param {string} apikey - APIKEY of the App Configuration service.\n */\n function init(region, guid, apikey) {\n _guid = guid;\n urlBuilder.setRegion(region);\n urlBuilder.setGuid(guid);\n urlBuilder.setApikey(apikey);\n urlBuilder.setAuthenticator();\n }\n\n /**\n * Used to re-initialize this module\n *\n * 1. Clears the interval set for internet check\n * 2. Clears any scheduled retries if they were set\n * 3. Deletes the configurations stored in SDK defined file path\n * @method module:ConfigurationHandler#cleanup\n */\n function cleanup() {\n clearInterval(interval);\n clearTimeout(retryScheduled);\n if (_persistentCacheDirectory) {\n FileManager.deleteFileData(path.join(_persistentCacheDirectory, 'appconfiguration.json'));\n }\n _onSocketRetry = false;\n }\n\n /**\n * Stores the given configurations data into respective maps.\n * (_featureMap, _propertyMap, _segmentMap)\n *\n * @method module:ConfigurationHandler#loadConfigurationsToCache\n * @param {JSON} data - The configurations data\n */\n function loadConfigurationsToCache(data) {\n if (data) {\n if (data.features && Object.keys(data.features).length) {\n const { features } = data;\n _featureMap = {};\n features.forEach((feature) => {\n _featureMap[feature.feature_id] = new Feature(feature);\n });\n }\n if (data.properties && Object.keys(data.properties).length) {\n const { properties } = data;\n _propertyMap = {};\n properties.forEach((property) => {\n _propertyMap[property.property_id] = new Property(property);\n });\n }\n if (data.segments && Object.keys(data.segments).length) {\n const { segments } = data;\n _segmentMap = {};\n segments.forEach((segment) => {\n _segmentMap[segment.segment_id] = new Segment(segment);\n });\n }\n }\n }\n\n /**\n * Writes the given data on to the persistent volume.\n *\n * @async\n * @param {JSON|string} fileData - The data to be written\n * @returns {undefined} If fileData is null\n */\n async function writeToPersistentStorage(fileData) {\n if (fileData == null) {\n logger.log('No data');\n return;\n }\n const json = JSON.stringify(fileData);\n FileManager.storeFiles(json, (path.join(_persistentCacheDirectory, 'appconfiguration.json')), () => { });\n }\n\n /**\n * Creates API request and waits for the response.\n * If response has data, then passes the response data to `writeToPersistentStorage()` method\n * for further actions. Else, logs the error message to console.\n *\n * @async\n * @method module:ConfigurationHandler#fetchFromAPI\n */\n async function fetchFromAPI() {\n retryCount -= 1;\n try {\n const query = {\n environment_id: _environmentId,\n };\n const parameters = {\n options: {\n url: `/apprapp/feature/v1/instances/${_guid}/collections/${_collectionId}/config`,\n method: 'GET',\n qs: query,\n },\n defaultOptions: {\n serviceUrl: urlBuilder.getBaseServiceUrl(),\n headers: urlBuilder.getHeaders(),\n },\n };\n const response = await ApiManager.createRequest(parameters);\n if (response && _liveUpdate) {\n // load the configurations in the response to cache maps\n loadConfigurationsToCache(response.result);\n emitter.emit(Constants.MEMORY_CACHE_ACTION_SUCCESS);\n // asynchronously write the response to persistent volume, if enabled\n if (_persistentCacheDirectory) {\n writeToPersistentStorage(response.result);\n }\n } else if (retryCount > 0) {\n logger.log('Retrying to fetch the configurations');\n fetchFromAPI();\n } else {\n logger.error(`Failed to fetch the configurations. Retrying after ${retryTime} minutes`);\n retryCount = 3;\n retryScheduled = setTimeout(() => fetchFromAPI(), retryTime * 60000);\n }\n } catch (error) {\n logger.error(error.message);\n }\n }\n\n /**\n * Perform websocket connect to appconfiguration server\n *\n * @async\n * @method module:ConfigurationHandler#connectWebSocket\n */\n async function connectWebSocket() {\n try {\n const urlForWebsocket = urlBuilder.getWebSocketUrl(_collectionId, _environmentId);\n const _bearerToken = await urlBuilder.getToken();\n const headers = {\n Authorization: _bearerToken,\n };\n closeWebSocket(); // close existing websocket connection if any\n socketClient.connect(\n urlForWebsocket, [], [], headers,\n );\n } catch (error) {\n logger.warning(error.message);\n logger.warning('Connection to the App Configuration server failed with unexpected error');\n }\n }\n\n function isJSONDataEmpty(jsonData) {\n if (Object.keys(jsonData).length === 0) {\n return true;\n }\n return false;\n }\n\n async function fetchConfigurationsData() {\n if (_liveUpdate) {\n await fetchFromAPI();\n connectWebSocket();\n }\n }\n\n /**\n * Sets the context of the SDK\n *\n * @method module:ConfigurationHandler#setContext\n * @param {string} collectionId - Id of the collection created in App Configuration service\n * instance.\n * @param {string} environmentId - Id of the environment created in App Configuration\n * service instance.\n * @param {object} [options] - Options object\n * @param {string} [options.persistentCacheDirectory] - Absolute path to a directory which has\n * read & write permissions for file operations.\n * @param {string} [options.bootstrapFile] - Absolute path of configuration file. This parameter\n * when passed along with `liveConfigUpdateEnabled` value will drive the SDK to use the\n * configurations of this file to perform feature & property evaluations.\n * @param {boolean} [options.liveConfigUpdateEnabled] - live configurations update from the server.\n * Set this value to `false` if the new configuration values shouldn't be fetched from the server.\n */\n function setContext(collectionId, environmentId, options) {\n // when setContext is called more than one time with any of collectionId, environmentId or options\n // different from its previous time, cleanup method is invoked.\n // don't do the cleanup when setContext is called for the first time.\n if ((_collectionId && (_collectionId !== collectionId))\n || (_environmentId && (_environmentId !== environmentId))\n || (_persistentCacheDirectory && (_persistentCacheDirectory !== options.persistentCacheDirectory))\n || (_bootstrapFile && (_bootstrapFile !== options.bootstrapFile))\n ) {\n cleanup();\n }\n _collectionId = collectionId;\n _environmentId = environmentId;\n _persistentCacheDirectory = options.persistentCacheDirectory;\n _bootstrapFile = options.bootstrapFile;\n _liveUpdate = options.liveConfigUpdateEnabled;\n\n if (_persistentCacheDirectory) {\n persistentData = FileManager.getFileData(path.join(_persistentCacheDirectory, 'appconfiguration.json'));\n // no emitting the event here. Only updating cache is enough\n loadConfigurationsToCache(persistentData);\n try {\n fs.accessSync(_persistentCacheDirectory, fs.constants.W_OK);\n } catch (err) {\n logger.error(Constants.ERROR_NO_WRITE_PERMISSION);\n return;\n }\n }\n\n if (_bootstrapFile) {\n if (_persistentCacheDirectory) {\n if (isJSONDataEmpty(persistentData)) {\n try {\n const bootstrapFileData = FileManager.getFileData(_bootstrapFile);\n loadConfigurationsToCache(bootstrapFileData);\n emitter.emit(Constants.MEMORY_CACHE_ACTION_SUCCESS);\n writeToPersistentStorage(bootstrapFileData)\n } catch (error) {\n logger.error(error);\n }\n } else {\n // only emit the event here. Because, cache is already updated above (line 270)\n emitter.emit(Constants.MEMORY_CACHE_ACTION_SUCCESS);\n }\n } else {\n const bootstrapFileData = FileManager.getFileData(_bootstrapFile);\n loadConfigurationsToCache(bootstrapFileData);\n emitter.emit(Constants.MEMORY_CACHE_ACTION_SUCCESS);\n }\n }\n\n if (_liveUpdate) {\n checkInternet().then((val) => {\n if (!val) {\n logger.warning(Constants.NO_INTERNET_CONNECTION_ERROR);\n _isConnected = false;\n }\n });\n interval = setInterval(() => {\n checkInternet().then((val) => {\n if (!val) {\n logger.warning(Constants.NO_INTERNET_CONNECTION_ERROR);\n _isConnected = false;\n } else {\n if (!_isConnected) {\n _onSocketRetry = false;\n fetchFromAPI();\n connectWebSocket();\n }\n _isConnected = true;\n }\n });\n }, 30000); // 30 second\n }\n\n fetchConfigurationsData();\n }\n\n async function socketActions() {\n fetchFromAPI();\n }\n\n /**\n * Get the Feature object containing all features\n *\n * @method module:ConfigurationHandler#getFeatures\n * @returns {object} Feature object\n */\n function getFeatures() {\n return _featureMap;\n }\n\n /**\n * Get the Feature with give Feature Id\n *\n * @method module:ConfigurationHandler#getFeature\n * @param {string} featureId - The Feature Id\n * @returns {object|null} Feature object\n */\n function getFeature(featureId) {\n if (Object.prototype.hasOwnProperty.call(_featureMap, featureId)) {\n return _featureMap[featureId];\n }\n logger.error(`Invalid feature id - ${featureId}`);\n return null;\n }\n\n /**\n * Get the Property object containing all properties\n *\n * @method module:ConfigurationHandler#getProperties\n * @returns {object} Property object\n */\n function getProperties() {\n return _propertyMap;\n }\n\n /**\n * Get the Property with give Property Id\n *\n * @method module:ConfigurationHandler#getProperty\n * @param {string} propertyId - The Property Id\n * @returns {object|null} Property object\n */\n function getProperty(propertyId) {\n if (Object.prototype.hasOwnProperty.call(_propertyMap, propertyId)) {\n return _propertyMap[propertyId];\n }\n logger.error(`Invalid property id - ${propertyId}`);\n return null;\n }\n\n function getSegment(segmentId) {\n if (Object.prototype.hasOwnProperty.call(_segmentMap, segmentId)) {\n return _segmentMap[segmentId];\n }\n logger.error(`Invalid segment id - ${segmentId}`);\n return null;\n }\n\n function evaluateSegment(segmentKey, entityAttributes) {\n if (Object.prototype.hasOwnProperty.call(_segmentMap, segmentKey)) {\n const segmentObjc = _segmentMap[segmentKey];\n return segmentObjc.evaluateRule(entityAttributes);\n }\n return null;\n }\n\n function _parseRules(segmentRules) {\n const rulesMap = {};\n segmentRules.forEach((rules) => {\n rulesMap[rules.order] = new SegmentRules(rules);\n });\n return rulesMap;\n }\n\n function evaluateRules(_rulesMap, entityAttributes, feature, property) {\n const resultDict = {\n evaluated_segment_id: Constants.DEFAULT_SEGMENT_ID,\n value: null,\n };\n\n try {\n for (let index = 1; index <= Object.keys(_rulesMap).length; index += 1) {\n const segmentRule = _rulesMap[index];\n\n if (segmentRule.rules.length > 0) {\n for (let level = 0; level < segmentRule.rules.length; level += 1) {\n const rule = segmentRule.rules[level];\n\n const { segments } = rule;\n if (segments.length > 0) {\n for (let innerLevel = 0; innerLevel < segments.length; innerLevel += 1) {\n const segmentKey = segments[innerLevel];\n\n if (evaluateSegment(segmentKey, entityAttributes)) {\n resultDict.evaluated_segment_id = segmentKey;\n if (segmentRule.value === '$default') {\n if (feature !== null) {\n resultDict.value = feature.enabled_value;\n } else {\n resultDict.value = property.value;\n }\n } else {\n resultDict.value = segmentRule.value;\n }\n return resultDict;\n }\n }\n }\n }\n }\n }\n } catch (error) {\n logger.error(`RuleEvaluation ${error}`);\n }\n\n if (feature !== null) {\n resultDict.value = feature.enabled_value;\n } else {\n resultDict.value = property.value;\n }\n return resultDict;\n }\n\n /**\n * Records each of feature & property evaluations done by sending it to metering module.\n * See {@link module:Metering}\n *\n * @method module:ConfigurationHandler#recordEvaluation\n * @param {string} featureId - The Feature Id\n * @param {string} propertyId - The Property Id\n * @param {string} entityId - The Entity Id\n * @param {string} segmentId - The Segment Id\n */\n function recordEvaluation(featureId, propertyId, entityId, segmentId) {\n meteObj.addMetering(_guid,\n _environmentId,\n _collectionId,\n entityId,\n segmentId,\n featureId,\n propertyId);\n }\n\n /**\n * Feature evaluation\n *\n * @method module:ConfigurationHandler#featureEvaluation\n * @param {object} feature - Feature object\n * @param {string} entityId - Entity Id\n * @param {object} entityAttributes - Entity attributes object\n * @returns {boolean|string|number} Feature evaluated value\n */\n function featureEvaluation(feature, entityId, entityAttributes) {\n let resultDict = {\n evaluated_segment_id: Constants.DEFAULT_SEGMENT_ID,\n value: null,\n };\n try {\n if (feature.enabled) {\n if (!entityAttributes || Object.keys(entityAttributes).length <= 0) {\n return feature.enabled_value;\n }\n if (feature.segment_rules && feature.segment_rules.length > 0) {\n const _rulesMap = _parseRules(feature.segment_rules);\n resultDict = evaluateRules(_rulesMap, entityAttributes, feature, null);\n return resultDict.value;\n }\n return feature.enabled_value;\n }\n return feature.disabled_value;\n } finally {\n recordEvaluation(feature.feature_id, null, entityId, resultDict.evaluated_segment_id);\n }\n }\n\n /**\n * Property evaluation\n *\n * @method module:ConfigurationHandler#propertyEvaluation\n * @param {object} property - Property object\n * @param {string} entityId - Entity Id\n * @param {object} entityAttributes - Entity attributes object\n * @returns {boolean|string|number} Property evaluated value\n */\n function propertyEvaluation(property, entityId, entityAttributes) {\n let resultDict = {\n evaluated_segment_id: Constants.DEFAULT_SEGMENT_ID,\n value: null,\n };\n try {\n if (!entityAttributes || Object.keys(entityAttributes).length <= 0) {\n return property.value;\n }\n if (property.segment_rules && property.segment_rules.length > 0) {\n const _rulesMap = _parseRules(property.segment_rules);\n resultDict = evaluateRules(_rulesMap, entityAttributes, null, property);\n return resultDict.value;\n }\n return property.value;\n } finally {\n recordEvaluation(null, property.property_id, entityId, resultDict.evaluated_segment_id);\n }\n }\n\n // Other event listeners\n emitter.on(Constants.MEMORY_CACHE_ACTION_SUCCESS, () => {\n emitter.emit(Constants.APPCONFIGURATION_CLIENT_EMITTER);\n });\n\n // Socket Listeners\n emitter.on(Constants.SOCKET_CONNECTION_ERROR, (error) => {\n logger.warning(`Connecting to app configuration server failed. ${error}`);\n logger.warning(Constants.CREATE_NEW_CONNECTION);\n _onSocketRetry = true;\n connectWebSocket();\n });\n\n emitter.on(Constants.SOCKET_LOST_ERROR, (error) => {\n logger.warning(`Connecting to app configuration server lost. ${error}`);\n logger.warning(Constants.CREATE_NEW_CONNECTION);\n _onSocketRetry = true;\n connectWebSocket();\n });\n\n emitter.on(Constants.SOCKET_CONNECTION_CLOSE, () => {\n logger.warning('server connection closed. Creating a new connection to the server.');\n logger.warning(Constants.CREATE_NEW_CONNECTION);\n _onSocketRetry = true;\n connectWebSocket();\n });\n\n emitter.on(Constants.SOCKET_MESSAGE_RECEIVED, (data) => {\n logger.log(`Received message from server. ${data}`);\n });\n\n emitter.on(Constants.SOCKET_CALLBACK, () => {\n socketActions();\n });\n\n emitter.on(Constants.SOCKET_MESSAGE_ERROR, () => {\n logger.warning('Message received from server is invalid.');\n });\n\n emitter.on(Constants.SOCKET_CONNECTION_SUCCESS, () => {\n logger.log('Successfully connected to App Configuration server');\n if (_onSocketRetry === true) {\n socketActions();\n }\n _onSocketRetry = false;\n });\n\n return {\n init,\n setContext,\n getFeature,\n getFeatures,\n getProperty,\n getProperties,\n getSegment,\n featureEvaluation,\n propertyEvaluation,\n cleanup,\n };\n }",
"static defaultConfig() {\r\n if (_defaultConfig == null) {\r\n _defaultConfig = new Config(\"./config/etc/config.json\");\r\n }\r\n\r\n return _defaultConfig;\r\n }",
"function createHb (options = {}) {\n hbase.define('Test', Object.assign({\n tableName: 'hbasetest',\n columns: [{\n name: 'cf1:string',\n type: 'string'\n }, {\n name: 'cf2:date',\n type: 'date'\n }, {\n name: 'cf2:number',\n type: 'number'\n }, {\n name: 'cf2:buffer',\n type: 'buffer'\n }],\n classMethods: {\n testClassMethod () {\n\n }\n },\n instanceMethods: {\n testInstanceMethod () {\n return this\n }\n }\n }, options))\n\n return hbase\n}",
"function Configuration(resource) {\n // defining the encoding as utf-8.\n this.ENCODING = 'utf8';\n this.config = this.loadConfigResource(resource); // this function is defined in the below line.\n }",
"static get(name, id, state, opts) {\n return new EncryptionConfig(name, state, Object.assign(Object.assign({}, opts), { id: id }));\n }",
"toDescriptor() {\n return {\n apiVersion: 'v1',\n kind: 'Secret',\n metadata: this.metadata,\n data: Object.entries(this.data).reduce((hash, entry) => {\n const [ key, value ] = entry;\n if (value !== undefined) hash[key] = toBase64(value);\n return hash;\n }, {})\n };\n }",
"function MapConfig(cfg) {\n // TODO: check configuration ?\n // TODO: inject defaults ?\n this._cfg = cfg;\n}",
"constructor() { \n \n S3StorageConfig.initialize(this);\n }",
"constructor(config_dir){\n if(fs.existsSync(config_dir)){\n if(typeof require(config_dir) == 'json' || typeof require(config_dir) == 'object'){\n this.config = require(config_dir);\n\n // Load the access token key.\n if(this.config.mode == 'sandbox') this.config.token = this.config.keys.sandbox;\n else if(this.config.mode == 'production') this.config.token = this.config.keys.production;\n\n // Log to console.\n if(this.config.mode == 'sandbox'){\n console.log('[Flip Gocardless] => Running in ' + this.config.mode);\n console.log('[Flip GoCardless] => Loaded configuration files.');\n }\n }\n else throw '[Flip GoCardless] => Invalid config file contents.';\n }\n else throw '[Flip GoCardless] => Invalid config file.';\n }",
"function ConfigurationAggregator(props) {\n return __assign({ Type: 'AWS::Config::ConfigurationAggregator' }, props);\n }",
"constructor() { \n \n SshKeyAllOf.initialize(this);\n }",
"function ConfigurationSet(props) {\n return __assign({ Type: 'AWS::SES::ConfigurationSet' }, props);\n }",
"function FunctionConfiguration(props) {\n return __assign({ Type: 'AWS::AppSync::FunctionConfiguration' }, props);\n }",
"constructor(_data, _blockhash, _prevhash){\n this.timestamp = Date.now()\n this.data = _data\n this.prevHash = _prevhash\n this.nonce = nonce ++\n this.blockHash = _blockhash\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
shows weight logs for the month | getWeightsMonth(){
let temp = [];
let today = new Date();
let progress = 0;
for(var i=0; i< this.weightLog.length; i++){
let then= this.weightLog[i].date;
if(then.getFullYear() == today.getFullYear() && then.getMonth() == today.getMonth()){
temp.push(this.weightLog[i]);
}
}
if(temp.length >= 2){
progress = temp[temp.length - 1].weight - temp[0].weight;
}
return {weights: temp, progress: progress};
} | [
"function monthlyReport() {\n\n}",
"getWeightsWeek(){\n let temp = [];\n let today = new Date();\n let progress = 0;\n let lastWeek = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 7);\n for(var i=0; i< this.weightLog.length; i++){\n if(this.weightLog[i].date >= lastWeek && this.weightLog[i].date <=today){\n temp.push(this.weightLog[i]);\n }\n }\n if(temp.length >= 2){\n progress = temp[temp.length - 1].weight - temp[0].weight;\n }\n return {weights: temp, progress: progress}; \n }",
"getWeightsYear(){\n let temp = [];\n let today = new Date();\n let progress = 0;\n for(var i=0; i< this.weightLog.length; i++){\n let then= this.weightLog[i].date;\n if(then.getFullYear() == today.getFullYear()){\n temp.push(this.weightLog[i]);\n }\n }\n if(temp.length >= 2){\n progress = temp[temp.length - 1].weight - temp[0].weight;\n }\n return {weights: temp, progress: progress}; \n }",
"function printMonthTitle(month, year) {\n output = monthsName[month] + ' ' + year + '.';\n document.getElementsByClassName(\"date-info\")[0].innerText = output;\n }",
"function renderMonth() {\r\n // Creo un oggetto moment con anno e mese scelti\r\n var momentObject = {\r\n \"year\": startYear,\r\n \"month\": startMonth\r\n };\r\n\r\n // Creo una data moment.js passando l'oggetto creato\r\n var momentDate = moment(momentObject);\r\n // Ottengo il numero di giorni nel mese selezionato\r\n var daysInMonth = momentDate.daysInMonth();\r\n\r\n // Modifico il titolo in base al mese scelto\r\n $(\"h1\").text(momentDate.format(\"MMMM YYYY\"));\r\n\r\n // Per ognuno dei giorni nel mese, modifico il context e compilo il template\r\n for (var i = 1; i <= daysInMonth; i++) {\r\n var context = {\r\n \"day\": i,\r\n \"month\": momentDate.format(\"MMMM\")\r\n }\r\n\r\n // Compilo il template e lo aggiungo alla lista sulla pagina\r\n var html = template(context);\r\n $(\"ul.month-display\").append(html);\r\n }\r\n }",
"function getMonthList() {\n var today = new Date();\n var aMonth = today.getMonth();\n var i;\n var matrixMnthList = $(\".div-lpc-wrapper #matrixMonthList\");\n for (i = 0; i < 12; i++) {\n var monthRow = '<th class=\"label-month-lpc-wrapper\" id=\\\"' + i + '\\\">' + monthArray[aMonth] + '</th>';\n if ($(matrixMnthList)) {\n $(matrixMnthList).append(monthRow);\n }\n aMonth++;\n if (aMonth > 11) {\n aMonth = 0;\n }\n }\n}",
"function show_activity_distances(ndx) {\n var date_dim = ndx.dimension(dc.pluck('date'));\n var total_distance_km_per_date = date_dim.group().reduceSum(dc.pluck('distance_km'));\n var minDate = date_dim.bottom(1)[0].date;\n var maxDate = date_dim.top(1)[0].date;\n dc.lineChart(\"#distance\")\n .width(570)\n .height(300)\n .margins({ top: 10, right: 50, bottom: 30, left: 50 })\n .dimension(date_dim)\n .group(total_distance_km_per_date)\n .transitionDuration(500)\n .x(d3.time.scale().domain([minDate, maxDate]))\n .yAxisLabel(\"Distance of Activity\")\n .xAxisLabel(\"Month\")\n .brushOn(false)\n .yAxis().ticks(10);\n}",
"function show_average_speed(ndx) {\n var date_dim = ndx.dimension(dc.pluck('date'));\n var total_average_speed_kmph_per_date = date_dim.group().reduceSum(dc.pluck('average_speed_kmph'));\n var minDate = date_dim.bottom(1)[0].date;\n var maxDate = date_dim.top(1)[0].date;\n dc.lineChart(\"#average\")\n .width(570)\n .height(300)\n .margins({ top: 10, right: 50, bottom: 30, left: 50 })\n .dimension(date_dim)\n .group(total_average_speed_kmph_per_date)\n .transitionDuration(500)\n .x(d3.time.scale().domain([minDate, maxDate]))\n .yAxisLabel(\"Average Speed of Activity\")\n .xAxisLabel(\"Month\")\n .brushOn(false)\n .yAxis().ticks(10);\n}",
"getFoodMonth(){\n let temp = [];\n let total = 0;\n let today= new Date();\n for(var i = 0; i< this.foodLog.length; i++){\n let then = this.foodLog[i].date;\n if(then.getFullYear() == today.getFullYear() && then.getMonth() == today.getMonth()){\n temp.push(this.foodLog[i]);\n total += this.foodLog[i].calories;\n }\n }\n return {foods: temp, calories: total};\n }",
"function buildWeek(date, month, viewedMonth){\n var days = [];\n for (var i = 0; i < 7; i++) {\n days.push({\n name: date.format(\"dd\").substring(0, 2),\n number: date.date(),\n isCurrentMonth: date.month() === month.month(),\n isViewedMonth: date.month() === viewedMonth.month(),\n isToday: date.isSame(new Date(), \"day\"),\n date: moment(date, \"MM-DD-YYYY\"),\n transactions: applyTransactions(date),\n endOfDay: Math.round((calculateEndOfDay(date, viewedMonth) + 0.00001) * 100) / 100\n });\n\n if (date._d.toString() == moment().endOf('month').startOf('day')._d.toString() && date.month() == viewedMonth.month()){\n console.log('last day of the current month', days[days.length -1]);\n applyNextTotal(days[days.length -1])\n }\n\n date = date.clone();\n date.add(1, \"d\");\n }\n return days;\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 displayDate(year, month, day) {\n var entries = [];\n\n // Loads launches from current day's launch data\n if(launchData[year] && launchData[year][month] && launchData[year][month][day]) {\n entries = launchData[year][month][day];\n }\n\n // Right now this clears the points completely\n // Later we may change it to not clear, and just allow\n // the animation to continue\n currentLaunches = [];\n\n for(var i=0; i <entries.length; i++) {\n \n // If there are filter tags, applies the filter\n if (currentTags.length > 0)\n {\n for (var tagNo = 0; tagNo < currentTags.length; tagNo++)\n {\n var tag = currentTags[tagNo];\n // Add if we have a tag match\n if (entries[i]['Tag'] === tag)\n {\n currentLaunches.push(\n { birthtime: (new Date()).getTime(),\n info: entries[i] } );\n }\n }\n }\n else\n {\n // Just add, since we're not checking tags\n currentLaunches.push(\n { birthtime: (new Date()).getTime(),\n info: entries[i] } );\n }\n }\n\n updatePlayBar();\n redrawLaunchesOnly();\n}",
"function generateRowForDate(year, month, count){\n\t$( \"#metricsPanel tr:last\" ).after( \"<tr class=''></tr>\" );\n $( \"#metricsPanel tr:last\" ).append( \"<td>\" + month + \"-\" + year + \"</td>\" );\n //$( \"#metricsPanel tr:last\" ).append( \"<td>\" + parsed.sorting_date + \"</td>\" );\n $( \"#metricsPanel tr:last\" ).append( \"<td>\" + count + \"</td>\" );\n}",
"getWeightsRange(date1, date2){\n let temp = [];\n let progress = 0;\n let start = new Date(date1);\n let end = new Date(date2);\n for(var i=0; i< this.weightLog.length; i++){\n if(this.weightLog[i].date >= start && this.weightLog[i].date <=end){\n temp.push(this.weightLog[i]);\n }\n }\n if(temp.length >= 2){\n progress =temp[temp.length - 1].weight -temp[0].weight;\n }\n return {weights: temp, progress: progress}; \n }",
"listMonthly() {\n const today = new Date();\n return this.trafficRepository.getMonthlyData(dateService.getYearStart(today), dateService.getYearEnd(today))\n .then(data => {\n data = this.mapRepositoryData(data);\n const range = numberService.getSequentialRange(1, 12);\n const valuesToAdd = range.filter(x => !data.find(item => item.group === x));\n return data.concat(this.mapEmptyEntries(valuesToAdd));\n });\n }",
"function _drawMetricDate(svg,x,y,context){\n\tvar gDate = svg.append(\"g\").attr(\"id\",\"metric_date_\"+context.data.title);\n\tvar _title = _drawText(gDate,context.data.title,x,y,{\"size\":\"16px\",\"weight\":\"bold\",\"anchor\":\"start\",\"color\":COLOR_BPTY});\n\tvar _m =get_metrics(_title.node());\n\n\n\tif (!context.dimension==\"goal\"){\n\t\t_drawText(gDate,context.data.line1+\" \",x,y+7,{\"size\":\"5px\",\"weight\":\"normal\",\"anchor\":\"start\",\"color\":COLOR_BPTY});\n\t\t_drawText(gDate,\"[from: \"+context.intervalStart.toString('yyyy-MM-dd')+\" to: \"+context.intervalEnd.toString('yyyy-MM-dd')+\" ]\",(x+_m.width),y+7,{\"size\":\"6px\",\"weight\":\"bold\",\"anchor\":\"end\",\"color\":COLOR_BPTY});\n\n\t\t_drawText(gDate,context.data.line2+\" \",x,y+14,{\"size\":\"5px\",\"weight\":\"normal\",\"anchor\":\"start\",\"color\":COLOR_BPTY});\n\t\tif (context.forecastDate)\n\t\t\t_drawText(gDate,\"[ \"+_.last(context.forecastDate).toString('yyyy-MM-dd')+\" ]\",(x+_m.width),y+14,{\"size\":\"6px\",\"weight\":\"bold\",\"anchor\":\"end\",\"color\":COLOR_BPTY});\n\n\t}\n}",
"monthViewTitle({ date, locale }) {\n return new Intl.DateTimeFormat(locale, {\n year: 'numeric',\n month: 'long'\n }).format(date);\n }",
"function monthlyTimeChart (result) {\n // Get chart data\n function getMessagesByDay (data, channelFilter) {\n const channels = {}\n\n // Loops through the data to build the `channels` object\n data.forEach(item => {\n const channel = moment(item.MessageTime).format('YYYY-MM-DD'); const id = item.MessageID\n\n // Makes sure there is no filter, or channel matches filter, before proceeding\n if (!channelFilter || channelFilter === channel) {\n if (!channels[channel]) {\n // Adds a property to the `channels` object. Its value is an array including one item: the MessageID.\n channels[channel] = [id]\n } else if (!channels[channel].includes(id)) {\n // Add a new MessageID to the array for this channel\n channels[channel].push(id)\n }\n }\n })\n\n // Replaces the property's value with a number indicating the number of unique conversations\n for (var channel in channels) {\n // Uses `for...in` to loop through object properties\n channels[channel] = channels[channel].length\n }\n\n return channels\n }\n\n // Push 0s where data is missing\n var timeArray = getMessagesByDay(result)\n\n var month = Object.keys(timeArray)\n var selectedMonth = moment(month[0]).format('YYYY-MM')\n\n const timeLabels = []\n const timeData = []\n\n const date = moment(selectedMonth + '-01')\n const endDate = moment(selectedMonth).endOf('month')\n\n const endOfMonth = moment(selectedMonth).endOf('month').format('YYYY-MM-DD')\n\n do {\n const dateStr = date.format('YYYY-MM-DD')\n timeLabels.push(dateStr)\n\n if (timeArray.hasOwnProperty(dateStr)) { timeData.push(timeArray[dateStr]) } else { timeData.push(0) }\n\n date.add(1, 'day')\n } while (date.isBefore(endDate))\n\n // Set data and labels\n var labels = timeLabels\n var data = timeData\n\n document.getElementById('monthlyTotalTime').innerHTML = ''\n\n // Create chart\n var ctx = document.getElementById('monthlyTimeChart').getContext('2d')\n var chart = new Chart(ctx, {\n type: 'line',\n data: {\n labels: labels,\n datasets: [{\n label: '# of Messages',\n data: data\n }]\n },\n options: {\n title: {\n display: true,\n text: 'Messages Received'\n },\n legend: {\n display: false\n },\n scales: {\n xAxes: [{\n type: 'time',\n time: {\n displayFormats: {\n day: 'DD MMM'\n },\n unit: 'day',\n min: selectedMonth + '-01',\n max: endOfMonth\n }\n }],\n yAxes: [{\n gridLines: {\n display: false\n },\n ticks: {\n beginAtZero: true\n }\n }]\n },\n plugins: {\n colorschemes: {\n scheme: chartColorScheme\n },\n datalabels: {\n display: function (context) {\n return context.dataset.data[context.dataIndex] !== 0 // or >= 1 or ...\n }\n }\n }\n }\n })\n}",
"allWeight(){\n let progress = 0;\n if(this.weightLog.length >= 2){\n progress = this.weightLog[this.weightLog.length-1].weight - this.weightLog[0].weight;\n }\n return {weights: this.weightLog, progress: progress};\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns whether or not the capy has hit one of the pipes or the upper/lower boundaries of the Level | gameOver() {
return (this.level.collidesWith(this.capy.bounds()) || this.capy.outOfBounds());
} | [
"outOfBounds() {\n const aboveTop = this.y < 0;\n const belowBottom = this.y + CONST.CAPY_HEIGHT > this.dimensions.height;\n return aboveTop || belowBottom;\n }",
"passedPipe(capy, callback) {\n this.eachPipe((pipe) => {\n if (pipe.topPipe.right < capy.left) {\n if (!pipe.passed) {\n pipe.passed = true;\n callback();\n }\n }\n });\n }",
"function isInBound(x,y){\n\treturn x>-1&&x<9&&y>-1&&y<9;\n}",
"canHit(unit) {\r\n if (abs(unit.mapX - this.mapX) <= this.info.range &&\r\n abs(unit.mapY - this.mapY) <= this.info.range) {\r\n if (unit.player !== this.player) {\r\n if (!this.attacked) return true;\r\n }\r\n return false\r\n }\r\n return false;\r\n }",
"checkWithinBound(newX) {\n return newX >= enemySmallestX && newX <= 500;\n }",
"function inBounds(p) {\n // check bounds of display\n if((p[0]-2*bcr) <= width * 0.1 || //left\n (p[0]+2*bcr) >= width - (width * 0.1) || //right\n (p[1]-2*bcr) <= height * 0.1 ||\n (p[1]+2*bcr) >= height - (height * 0.1)) {\n return false;\n }\n return true;\n}",
"function checkHit() {\r\n \"use strict\";\r\n // if torp left and top fall within the ufo image, its a hit!\r\n let ymin = ufo.y;\r\n let ymax = ufo.y + 65;\r\n let xmin = ufo.x;\r\n let xmax = ufo.x + 100;\r\n\r\n\r\n console.log(\"torp top and left \" + torpedo.y + \", \" + torpedo.x);\r\n console.log(\"ymin: \" + ymin + \"ymax: \" + ymax);\r\n console.log(\"xmin: \" + xmin + \"xmax: \" + xmax);\r\n console.log(ufo);\r\n\r\n if (!bUfoExplode) {\r\n // not exploded yet. Check for hit...\r\n if ((torpedo.y >= ymin && torpedo.y <= ymax) && (torpedo.x >= xmin && torpedo.x <= xmax)) {\r\n // we have a hit.\r\n console.log(\" hit is true\");\r\n\r\n bUfoExplode = true; // set flag to show we have exploded.\r\n }// end if we hit\r\n\r\n }// end if not exploded yet\r\n\r\n // reset fired torp flag\r\n bTorpFired = false;\r\n\r\n // call render to update.\r\n render();\r\n\r\n}// end check hit",
"canSeePlayer(){\n\t\t//enemy should act like it doesn't know where the player is if they're dead\n\t\tif(lostgame)\n\t\t\treturn false;\n\t\t\n\t\t// casts a ray to see if the line of sight has anything in the way\n\t\tvar rc = ray.fromPoints(this.pos, p1.pos);\n\t\t\n\t\t// creates a bounding box for the ray so that the ray only tests intersection\n\t\t// for the blocks in that bounding box\n\t\tvar rcbb = box.fromPoints(this.pos, p1.pos);\n\t\tvar poscols = []; // the blocks in the bounding box\n\t\tfor(var i = 0; i < blocks.length; i++){\n\t\t\tif(box.testOverlap(blocks[i].col, rcbb))\n\t\t\t\tposcols.push(blocks[i]);\n\t\t}\n\t\t\n\t\t// tests ray intersection for all the blocks in th ebounding box\n\t\tfor(var i = 0; i < poscols.length; i++){\n\t\t\tif(poscols[i].col.testIntersect(rc))\n\t\t\t\treturn false; // there is a ray intersection, the enemy's view is obstructed\n\t\t}\n\t\treturn true;\n\t}",
"isOnTheWater() {\n return this.y <= 0;\n }",
"function checkInsideBoundingBox(bound, pt)\n{\n\tif (pt.x < bound.lower_bound.x || pt.x > bound.higher_bound.x) {\n\t\treturn false;\n\t}\n\tif (pt.y < bound.lower_bound.y || pt.y > bound.higher_bound.y) {\n\t\treturn false;\n\t}\n\tif (pt.z < bound.lower_bound.z || pt.z > bound.higher_bound.z) {\n\t\treturn false;\n\t} \n\treturn true;\n}",
"isInBounds(x, y) {\n if(x <= 0 || x >= this.mapWidth || y <= 0 || y >= this.mapHeight) {\n return false;\n }\n return true;\n }",
"__moveThresholdReached(clientX, clientY) {\n return Math.abs(clientX - this.data.startMouseX) >= this.moveThreshold || Math.abs(clientY - this.data.startMouseY) >= this.moveThreshold;\n }",
"canLevelUp(message, cache) {\n\t\tconst element = cache.get(message.member.id);\n\t\tconst exp = element.occupations.get('Painter').experience;\n\t\tconst level = element.occupations.get('Painter').level;\n\n\t\tconst requirements = [];\n\n\t\tif ((level < 9) && (exp >= this.exp_levels[level].exp)) {\n\t\t\treturn true;\n\t\t}\n\n\t\tmessage.channel.send(new RichEmbed({\n\t\t\tcolor: colors.darkblue,\n\t\t\ttitle: 'Bottleneck Ahoy!',\n\t\t\tdescription: `${message.member.displayName}, you've reached a bottleneck in your progression along the path of the Painter. The requirements to pass the bottleneck are:`,\n\t\t}).addField('Requirements', requirements.join('\\n'), true));\n\t\treturn false;\n\t}",
"function hasHitEnemy(abuser, victim) {\n let result = false;\n if(abuser.hurtbox && abuser.hurtbox.isActive && victim.hitbox && victim.hitbox.isActive) {\n result = abuser.hurtbox.x < victim.hitbox.x + victim.hitbox.width\n && abuser.hurtbox.x + abuser.hurtbox.width > victim.hitbox.x\n && abuser.hurtbox.y < victim.hitbox.y + victim.hitbox.height\n && abuser.hurtbox.y + abuser.hurtbox.height > victim.hitbox.y;\n }\n // if(result) console.log(result);\n return result;\n}",
"function hitTest() {\n let topConditional; // hit past certain y position (min y value)\n let bottomConditional; // hit before certain y position (max y value)\n\n // best for loop; has the best content\n for (let i = 0; i < layersFalling; i ++) {\n if (layersStacked === 0) { // if tray empty\n bottomConditional = height - 20;\n topConditional = trayY;\n } else {\n bottomConditional = trayHit + 10;\n topConditional = trayHit;\n }\n if (cakeY[i] + 45 >= topConditional && cakeY[i] + 45 <= bottomConditional && cakeX[i] - 50 >= trayX - 65 && cakeX[i] + 50 <= trayX + 65) {\n restartPosition(i);\n layersStacked += 1;\n cakeStack.play();\n }\n }\n}",
"hitBorder() {\n let head = this.state.rat[0]\n if (head[0] >= 100 || head[1] >= 100 || head[0] < 0 || head[1] < 0) {\n this.gameOver()\n }\n }",
"function isInBounds(point) {\n\t\tif (point >= bounds.sw && point <= bounds.nw) {\n\t\t\tconsole.log(\"point in bounds\");\n\t\t}\n\t}",
"isColliding() {\n this.getCorners();\n return Line.isColliding(this.hitboxLines, sceneHitboxLines.filter(line => this.hitboxLines.indexOf(line) === -1));\n }",
"function checkColision(){\n return obstacles.obstacles.some(obstacle => {\n if(obstacle.y + obstacle.height >= car.y && obstacle.y <= car.y + car.height){\n if(obstacle.x + obstacle.width >= car.x && obstacle.x <= car.x + car.width){\n console.log(\"colision\")\n return true;\n }\n }\n return false;\n });\n}",
"checkGameStatus() {\n if(this.props.player.health <= 0 || this.props.game.level >= 6) {\n this.props.actions.gameOver()\n }\n\n if(this.props.player.xp >= (this.props.game.level * 50)) {\n this.levelUp();\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
stop loop of strip moving | function stopStripMovingLoop(){
if(g_temp.isStripMoving == false)
return(false);
g_temp.isStripMoving = false;
g_temp.handle_timeout = clearInterval(g_temp.handle_timeout);
} | [
"toStopPosition() {\n console.log('[johnny-five] Proceeding with Stop Sequence.');\n\n this.red.stop().off();\n this.yellow.stop().off();\n this.green.on();\n\n setTimeout(() => {\n this.green.off();\n this.yellow.pulse(300);\n }, 2000);\n\n setTimeout(() => {\n this.red.on();\n this.yellow.stop().off();\n }, 3500);\n }",
"function completeStripPhase () {\n /* strip the player with the lowest hand */\n stripPlayer(recentLoser);\n updateAllGameVisuals();\n}",
"function checkAndRepositionInnerStrip(){\n\t\t\n\t\tif(isStripMovingEnabled() == false)\n\t\t\treturn(false);\n\t\t\n\t\tvar pos = t.getInnerStripPos();\n\t\t\n\t\tvar posFixed = t.fixInnerStripLimits(pos);\n\t\t\t\t\n\t\tif(pos != posFixed)\n\t\t\tt.positionInnerStrip(posFixed, true);\n\t}",
"function continueTouchMotion(){\n\t\t\t\t\n\t\tvar slowFactor = g_serviceParams.thumb_touch_slowFactor;\n\t\t\n\t\t//don't alow portion less then the minTime\n\t\tvar minDeltaTime = g_serviceParams.minDeltaTime;\n\t\t\n\t\t//if less then this path, dont' continue motion\n\t\tvar minPath = g_serviceParams.minPath;\t\n\t\t\n\t\tvar currentInnerPos = g_parent.getInnerStripPos();\n\t\t\n\t\tvar currentTime = jQuery.now();\n\t\tvar deltaTime = currentTime - g_temp.lastTime;\n\t\tvar deltaPos = currentInnerPos - g_temp.lastPortionPos;\n\t\t\n\t\t//if time too fast, take last portion values\n\t\tif(deltaTime < minDeltaTime && g_temp.lastDeltaTime > 0){\n\t\t\tdeltaTime = g_temp.lastDeltaTime;\n\t\t\tdeltaPos = g_temp.lastDeltaPos + deltaPos;\n\t\t}\n\t\t\n\t\t//fix delta time\n\t\tif(deltaTime < minDeltaTime)\n\t\t\tdeltaTime = minDeltaTime;\n\t\t\t\t\t\n\t\tvar dir = (deltaPos > 0)?1:-1;\n\t\t\n\t\tvar speed = 0;\n\t\tif(deltaTime > 0)\n\t\t\tspeed = deltaPos / deltaTime;\t\n\t\t\n\t\tvar path = (speed * speed) / (slowFactor * 2) * dir;\n\t\t\n\t\t//disable path for very slow motions\n\t\tif(Math.abs(path) <= minPath)\n\t\t\tpath = 0;\n\t\t\n\t\t\n\t\tvar innerStripPos = g_parent.getInnerStripPos();\n\t\tvar newPos = innerStripPos + path;\t\t\n\t\tvar correctPos = g_parent.fixInnerStripLimits(newPos);\n\t\tvar objLimits = g_parent.getInnerStripLimits();\n\t\t\n\t\t//check the off the limits and return (second animation)\n\t\tvar limitsBreakAddition = g_serviceParams.limitsBreakAddition;\n\t\tvar doQueue = false;\n\t\tvar returnPos = correctPos;\n\t\t\n\t\t\n\t\t//fix the first animation position (off the limits)\n\t\tif(newPos > objLimits.maxPos){\n\t\t\tdoQueue = true;\n\t\t\tcorrectPos = limitsBreakAddition;\n\t\t\tif(newPos < limitsBreakAddition)\n\t\t\t\tcorrectPos = newPos;\t\t\t\n\t\t}\n\t\t\t\t\n\t\tif(newPos < objLimits.minPos){\n\t\t\tdoQueue = true;\n\t\t\tvar maxStopPos = objLimits.minPos - limitsBreakAddition;\n\t\t\tcorrectPos = maxStopPos;\n\t\t\tif(newPos > maxStopPos)\n\t\t\t\tcorrectPos = newPos;\n\t\t}\n\t\t\t\t\n\t\tvar correctPath = correctPos - innerStripPos;\n\t\t\n\t\t//set animation speed\t\t\n\t\tvar animateSpeed = Math.abs(Math.round(speed / slowFactor));\n\t\t\n\t\t//fix animation speed according the paths difference\n\t\tif(path != 0)\n\t\t\tanimateSpeed = animateSpeed * correctPath / path;\t\t\n\t\t\n\t\t\n\t\t//Do first animation\n\t\tif(innerStripPos != correctPos){\n\t\t\t\n\t\t\tvar animateProps = {\"left\":correctPos+\"px\"};\n\t\t\tif(g_isVertical == true)\n\t\t\t\tanimateProps = {\"top\":correctPos+\"px\"};\t\t\n\t\t\t\n\t\t\tg_objStripInner.animate(animateProps ,{\n\t\t\t\t\tduration: animateSpeed,\n\t\t\t\t\teasing: g_serviceParams.animationEasing,\n\t\t\t\t\tqueue: true,\n\t\t\t\t\tprogress:onAnimateProgress \n\t\t\t});\n\t\t\t\t\t\t\n\t\t}\n\t\t\n\t\t\t\t\n\t\t//do second animation if off limits\n\t\tif(doQueue == true){\n\t\t\tvar returnAnimateSpeed = g_serviceParams.returnAnimateSpeed;\n\t\t\t\n\t\t\tvar returnAnimateProps = {\"left\":returnPos+\"px\"};\n\t\t\tif(g_isVertical == true)\n\t\t\t\treturnAnimateProps = {\"top\":returnPos+\"px\"};\t\t\n\t\t\t\n\t\t\t\n\t\t\tg_objStripInner.animate(returnAnimateProps,{\t\t\t\t\n\t\t\t\tduration: returnAnimateSpeed,\n\t\t\t\teasing: g_serviceParams.returnAnimationEasing,\n\t\t\t\tqueue: true,\n\t\t\t\tprogress:onAnimateProgress \n\t\t\t});\n\t\t}\n\t\t\n\t}",
"buildLoop() {\n this.toGoPosition();\n\n setTimeout(() => {\n this.toStopPosition();\n }, 4000);\n }",
"function endPosition(){\r\n painting = false; \r\n c.beginPath();\r\n}",
"function noWrap()\r\n\t {\r\n\t\timageContext.lineTo(newX, newY);\r\n\t\tturtle.pos.x = newX;\r\n\t\tturtle.pos.y = newY;\r\n\t\tdistance = 0;\r\n\t }",
"function stopLoop() {\n clearInterval (Defaults.game.handle);\n }",
"function swipeCancelHandler () {\n\n startCoords = null;\n }",
"function stopDrag(){\n\t detector_container.removeEventListener(\"pressmove\", moveDrag); \n}",
"toggleLoop() {\r\n this.setLoop(!this._loop);\r\n }",
"skipNext() {\n const { selectedSongIdx } = this.state\n const isAtLoopPoint = selectedSongIdx >= this.countTracks() - 1 ||\n selectedSongIdx < 0\n\n const songIdx = isAtLoopPoint ? 0 : (selectedSongIdx + 1)\n\n this.selectSong(songIdx)\n this.play(songIdx)\n }",
"toGoPosition() {\n console.log('[johnny-five] Proceeding with Go Sequence.');\n\n this.red.on();\n this.yellow.stop().off();\n this.green.stop().off();\n\n setTimeout(() => {\n this.yellow.on();\n }, 2000);\n\n setTimeout(() => {\n this.red.off();\n this.yellow.off();\n this.green.on();\n }, 3500);\n }",
"function goFaster() {\n if (SPACE_BAR_DEPRESSED) {\n clearInterval(interval);\n interval = setInterval(moveSnake, 40);\n }\n SPACE_BAR_SWITCH = false;\n}",
"function mouseGrab(e) {\n console.log(\"mouseGrab\");\n var evt = e|| window.event;\n mousePiece = evt.target || evt.srcElement;\n maxZ ++;\n\n //Remove piece from array and stop animation\n $(mousePiece).stop(true);\n var index = movingPieces.indexOf(mousePiece);\n movingPieces.splice(index, 1);\n console.log(movingPieces);\n\n //Loop through an array with all removed pieces and assign a stop() to them\n // I think the updating of the animate array is a bit slow so it doesn't always apply when you click the piece\n stoppedPieces.push(mousePiece);\n\n mousePiece.style.zIndex = maxZ; // Place the piece above other objects\n\n mousePiece.style.cursor = \"move\";\n\n var mouseX = evt.clientX; // x-coordinate of pointer\n var mouseY = evt.clientY; // y-coordinate of pointer\n\n /* Calculate the distance from the pointer to the piece */\n diffX = parseInt(mousePiece.style.left) - mouseX;\n diffY = parseInt(mousePiece.style.top) - mouseY;\n\n /* Add event handlers for mousemove and mouseup events */\n addEvent(document, \"mousemove\", mouseMove, false);\n addEvent(document, \"mouseup\", mouseDrop, false);\n }",
"stop() {\n this.song_.stop();\n this.bitDepthSlider_.disable();\n this.reductionSlider_.disable();\n }",
"function stopAnimation() {\n $(\"start\").disabled = false;\n $(\"stop\").disabled = true;\n document.querySelector(\"textarea\").disabled = false;\n clearInterval(timer);\n timer=null;\n $(\"readarea\").innerHTML = \"\";\n index = 0;\n }",
"startMoving () {\r\n this._isMoving = true;\r\n }",
"sense () {\n const step = 50\n var x = ships[this.botId].translation.x\n var y = ships[this.botId].translation.y\n var rotation = ships[this.botId].rotation\n var cX = (Math.cos(rotation + (Math.PI / 2) - this.theta))\n var cY = (Math.sin(rotation + (Math.PI / 2) - this.theta))\n\n for (var i = 0; i < this.length; i += step) {\n var pX = x + i * cX\n var pY = y + i * cY\n if (isBelowGround(pX, pY)) {\n this.line.stroke = 'red'\n this.value = 1\n return i\n }\n }\n this.line.stroke = 'green'\n this.value = -1\n return -1\n }",
"stopGC() {\n if (this.currentParams.pointList.length > 1) {\n this.drawTurtle.CreateExtrudeShape(\"tube\" + (this.drawTurtle.graphicElems.length + 1).toString(), { shape: this.currentParams.shapeSection, path: this.currentParams.pointList, sideOrientation: BABYLON.Mesh.DOUBLESIDE, radius: 0.075 }, this.drawTurtle.materialTextures[0]);\n this.currentParams.pointList = [];\n }\n this.currentParams.generalizedCylinder = false;\n this.currentParams.customId = SHAPE_NOID;\n this.currentParams.customParentId = SHAPE_NOID;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Lifts the app state reducer into a DevTools state reducer. | function liftReducer(reducer, initialState) {
var initialLiftedState = {
committedState: initialState,
stagedActions: [INIT_ACTION],
skippedActions: {},
currentStateIndex: 0,
monitorState: {
isVisible: true
},
timestamps: [Date.now()]
};
/**
* Manages how the DevTools actions modify the DevTools state.
*/
return function liftedReducer(liftedState, liftedAction) {
if (liftedState === undefined) liftedState = initialLiftedState;
var shouldRecomputeStates = true;
var committedState = liftedState.committedState;
var stagedActions = liftedState.stagedActions;
var skippedActions = liftedState.skippedActions;
var computedStates = liftedState.computedStates;
var currentStateIndex = liftedState.currentStateIndex;
var monitorState = liftedState.monitorState;
var timestamps = liftedState.timestamps;
switch (liftedAction.type) {
case ActionTypes.RESET:
committedState = initialState;
stagedActions = [INIT_ACTION];
skippedActions = {};
currentStateIndex = 0;
timestamps = [liftedAction.timestamp];
break;
case ActionTypes.COMMIT:
committedState = computedStates[currentStateIndex].state;
stagedActions = [INIT_ACTION];
skippedActions = {};
currentStateIndex = 0;
timestamps = [liftedAction.timestamp];
break;
case ActionTypes.ROLLBACK:
stagedActions = [INIT_ACTION];
skippedActions = {};
currentStateIndex = 0;
timestamps = [liftedAction.timestamp];
break;
case ActionTypes.TOGGLE_ACTION:
skippedActions = toggle(skippedActions, liftedAction.index);
break;
case ActionTypes.JUMP_TO_STATE:
currentStateIndex = liftedAction.index;
// Optimization: we know the history has not changed.
shouldRecomputeStates = false;
break;
case ActionTypes.SWEEP:
stagedActions = stagedActions.filter(function (_, i) {
return !skippedActions[i];
});
timestamps = timestamps.filter(function (_, i) {
return !skippedActions[i];
});
skippedActions = {};
currentStateIndex = Math.min(currentStateIndex, stagedActions.length - 1);
break;
case ActionTypes.PERFORM_ACTION:
if (currentStateIndex === stagedActions.length - 1) {
currentStateIndex++;
}
stagedActions = [].concat(stagedActions, [liftedAction.action]);
timestamps = [].concat(timestamps, [liftedAction.timestamp]);
// Optimization: we know that the past has not changed.
shouldRecomputeStates = false;
// Instead of recomputing the states, append the next one.
var previousEntry = computedStates[computedStates.length - 1];
var nextEntry = computeNextEntry(reducer, liftedAction.action, previousEntry.state, previousEntry.error);
computedStates = [].concat(computedStates, [nextEntry]);
break;
case ActionTypes.SET_MONITOR_STATE:
monitorState = liftedAction.monitorState;
break;
case ActionTypes.RECOMPUTE_STATES:
stagedActions = liftedAction.stagedActions;
timestamps = liftedAction.timestamps;
committedState = liftedAction.committedState;
currentStateIndex = stagedActions.length - 1;
skippedActions = {};
break;
default:
break;
}
if (shouldRecomputeStates) {
computedStates = recomputeStates(reducer, committedState, stagedActions, skippedActions);
}
return {
committedState: committedState,
stagedActions: stagedActions,
skippedActions: skippedActions,
computedStates: computedStates,
currentStateIndex: currentStateIndex,
monitorState: monitorState,
timestamps: timestamps
};
};
} | [
"function stateSave() {\n return function (dispatch, getState) {\n var _a = getState().explore, left = _a.left, right = _a.right, split = _a.split;\n var urlStates = {};\n var leftUrlState = {\n datasource: left.datasourceInstance.name,\n queries: left.queries.map(app_core_utils_explore__WEBPACK_IMPORTED_MODULE_4__[\"clearQueryKeys\"]),\n range: left.range,\n ui: {\n showingGraph: left.showingGraph,\n showingLogs: left.showingLogs,\n showingTable: left.showingTable,\n dedupStrategy: left.dedupStrategy,\n },\n };\n urlStates.left = Object(app_core_utils_explore__WEBPACK_IMPORTED_MODULE_4__[\"serializeStateToUrlParam\"])(leftUrlState, true);\n if (split) {\n var rightUrlState = {\n datasource: right.datasourceInstance.name,\n queries: right.queries.map(app_core_utils_explore__WEBPACK_IMPORTED_MODULE_4__[\"clearQueryKeys\"]),\n range: right.range,\n ui: {\n showingGraph: right.showingGraph,\n showingLogs: right.showingLogs,\n showingTable: right.showingTable,\n dedupStrategy: right.dedupStrategy,\n },\n };\n urlStates.right = Object(app_core_utils_explore__WEBPACK_IMPORTED_MODULE_4__[\"serializeStateToUrlParam\"])(rightUrlState, true);\n }\n dispatch(Object(app_core_actions__WEBPACK_IMPORTED_MODULE_5__[\"updateLocation\"])({ query: urlStates }));\n };\n}",
"fullState() {\n return Object.assign({}, this.state, this.internals);\n }",
"_transferState(oldLayer) {\n Object(_debug__WEBPACK_IMPORTED_MODULE_7__[\"default\"])(TRACE_MATCHED, this, this === oldLayer);\n const {\n state,\n internalState\n } = oldLayer;\n\n if (this === oldLayer) {\n return;\n } // Move internalState\n\n\n this.internalState = internalState;\n this.internalState.layer = this; // Move state\n\n this.state = state; // We keep the state ref on old layers to support async actions\n // oldLayer.state = null;\n // Ensure any async props are updated\n\n this.internalState.setAsyncProps(this.props);\n\n this._diffProps(this.props, this.internalState.getOldProps());\n }",
"extraReducers(builder) {\n builder.addCase(fetchNotifications.fulfilled, (state, action) => {\n // push the return array of action.payload into the current state array first\n // state.push(...action.payload);\n // state.forEach(notification => {\n // // all read notifications are no longer new\n // notification.isNew = !notification.read\n // })\n\n // notifications entity is no longer an array....KNOW YOUR ENTITY STRUCTURE BEFORE APPLY REDUCER FUNCS!\n // change the isNew in the new notification first\n Object.values(state.entities).forEach(notification => {\n notification.isNew = !notification.read;\n })\n\n // upsert: accept an array of entities or an object, shallowly insert it\n // upsertting the new notifications into the entity\n notificationsAdaptor.upsertMany(state, action.payload)\n\n // sort every date in the state \n // they are pre-sorted any time\n // state.sort((a, b) => b.date.localeCompare(a.date))\n })\n }",
"function modifyState (patch) {\n autoUpdate(patch); //apply changes to UIs\n appState = _.merge(appState, patch); //destructively update appState\n Object.freeze(appState); //freeze!\n }",
"function buildReducer(reducer, store, useTag) {\n /**\n * Expects an object or a function as the reducer argument. If an\n * object then it should be tagged as $$combine, $$extend, etc. This\n * is checked below.\n **/\n if (!(0, _lodash.isPlainObject)(reducer) && !(0, _lodash.isFunction)(reducer)) throw new Error('reslice.buildReducer: expected object or function, got: ' + (typeof reducer === 'undefined' ? 'undefined' : _typeof(reducer)));\n /**\n * Combining reducers. Recursively build nested reducers and use the\n * redux combineReducers fuction to combine them in the normal way.\n * The result is used to create a new tree object for the combined\n * function. This is then processed below.\n **/\n if (reducer.$$combine) {\n /**\n * If a combined reducer is a simple function then wrap the reducer\n * with a filter function that checks on the action tag. If it\n * is not, then it is not wrapped, so that actions continue to\n * propogate down the state tree.\n **/\n var filterReducer = function filterReducer(reducer) {\n var _reducer = buildReducer(reducer, store, myTag);\n if ((0, _lodash.isFunction)(reducer)) return function (state, action) {\n for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {\n args[_key2 - 2] = arguments[_key2];\n }\n\n if (!action.$$tag || action.$$tag === state.$$tag) return _reducer.apply(undefined, [state, action].concat(args));\n return state;\n };\n return _reducer;\n };\n\n var myTag = $$tag++;\n reducer = {\n $$reducer: (0, _redux.combineReducers)((0, _lodash.mapValues)(reducer.$$reducers, function (r) {\n return filterReducer(r);\n })),\n $$selectors: reducer.$$selectors,\n $$actions: reducer.$$actions,\n $$tag: myTag\n };\n }\n /**\n * Extending a reducer. Recursively build the reducer that is being\n * extended, then generate a new tree object where the reducer function\n * invokes the extension or the underlying reducer. This is then processed\n * below.\n **/\n else if (reducer.$$extend) {\n var _reducer = buildReducer(reducer.$$reducer, store);\n var _extension = reducer.$$extension;\n reducer = {\n $$reducer: function $$reducer(state, action) {\n for (var _len3 = arguments.length, args = Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) {\n args[_key3 - 2] = arguments[_key3];\n }\n\n /**\n * Redux initialise actions do not go through the\n * extending function.\n **/\n if (action.type.startsWith('@@')) return _reducer.apply(undefined, [state, action].concat(args));\n /**\n * If the action has the global tag or the matching\n * tag, then run the action through the extending\n * function. If this yields a result then make sure\n * the prototype is set and return that result; also\n * propogate the new state into the reducer so that\n * getSlice() behaves correctly.\n **/\n if (!action.$$tag || action.$$tag === state.$$tag) {\n var newState = _extension.apply(undefined, [state, action].concat(args));\n if (newState) {\n setPrototypeOf(newState, Object.getPrototypeOf(state));\n _reducer.setLastState(newState);\n return newState;\n }\n }\n /**\n * Otherwise, process through the underlying reducer.\n **/\n return _reducer.apply(undefined, [state, action].concat(args));\n },\n $$selectors: reducer.$$reducer.$$selectors,\n $$actions: reducer.$$reducer.$$actions,\n $$tag: _reducer.$$tag\n };\n }\n /**\n * Binding to a reducer function. This is left as-is to be processed\n * below.\n **/\n else if (reducer.$$bind) {\n var _reducer2 = reducer.$$reducer;\n reducer = {\n $$reducer: function $$reducer(state, action) {\n for (var _len4 = arguments.length, args = Array(_len4 > 2 ? _len4 - 2 : 0), _key4 = 2; _key4 < _len4; _key4++) {\n args[_key4 - 2] = arguments[_key4];\n }\n\n if (!action.$$tag || action.$$tag === state.$$tag) return _reducer2.apply(undefined, [state, action].concat(args));\n return state;\n },\n $$selectors: reducer.$$selectors,\n $$actions: reducer.$$actions,\n $$tag: $$tag++\n };\n }\n /**\n * Binding to a mapped reducer. The trick here is to create a factory\n * that creates per-key instances of the underlying reducer, and then\n * wrap that reducer with a function that invokes said reducer with\n * the factory as the third argument.\n **/\n else if (reducer.$$mapped) {\n var reducerForKey = function reducerForKey(key, initialiser) {\n var keyReducer = mapped[key];\n if (!keyReducer) mapped[key] = keyReducer = buildReducer(child, store);\n if (initialiser) {\n /**\n * Check for initialiser case in which case create a\n * new slice and optionally initialise it.\n **/\n var slice = keyReducer(undefined, { type: '@@redux/INIT' });\n var init = initialiser(slice);\n return init ? keyReducer(slice, init) : slice;\n }\n return keyReducer;\n };\n\n var wrapper = function wrapper(state, action) {\n var res = inner(state, action, reducerForKey);\n return shallowEqual(res, state) ? state : res;\n };\n\n var mapped = {};\n var inner = reducer.$$reducer;\n var child = reducer.$$child;\n\n reducer = {\n $$reducer: wrapper,\n $$selectors: reducer.$$selectors,\n $$actions: reducer.$$actions,\n $$tag: $$tag++\n };\n }\n /**\n * If the reducer is simply a function then treat it as bound to empty\n * collections of selectors and reducers.\n **/\n else if ((0, _lodash.isFunction)(reducer)) {\n reducer = {\n $$reducer: reducer,\n $$selectors: {},\n $$actions: {},\n $$tag: useTag || $$tag++\n };\n } else\n /**\n * Any other case is an error.\n **/\n throw new Error(\"reslice.buildReducer: unexpected tree object\");\n\n /**\n * Here lies the point whence ReSlice has to have a logically\n * distinct copy of a reducer function for each position in the\n * state tree at which the reducer is used (which may be more\n * than once).\n *\n * We need to be able to keep track of the last state returned\n * by this instance of a reducer in the tree. To this end, use\n * a generator function that returns a closure on a variable\n * used to save this state.\n **/\n function wrapReducer() {\n var lastState = null;\n var prototype = {\n getRoot: function getRoot() {\n return store.getState();\n },\n globalAction: globalAction,\n $$tag: reducer.$$tag\n };\n /**\n * Generate a prototype that contains the selectors and\n * actions (assumes distinct names). Selector functions are\n * wrapped so the slice becomes the first argument to the\n * selector. Action creators are wrapped so that \"this\" is\n * the slice, and if the action returns a thunk, then the\n * thunk is wrapped so that it will be called with a\n * \"getSlice\" function that returns the last state (and\n * such that \"this\" is explicitely null).\n **/\n (0, _lodash.each)(reducer.$$selectors, function (selector, name) {\n if ((0, _lodash.isFunction)(selector)) {\n /**\n * If the selector has a $$factory property then call\n * that to create the selector. This allows selector\n * memoization on a per-slice basis, rather than\n * globally. Also, since we have a .getRoot() \n * methods on slices, which may return different results\n * even if the particular slice changes, we need to\n * default the outer level of memoization in reslice.\n **/\n if (selector.$$factory) selector = selector.$$factory();\n prototype[name] = function () {\n for (var _len5 = arguments.length, args = Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {\n args[_key5] = arguments[_key5];\n }\n\n args.push(seseq++);\n return selector.apply(undefined, [this].concat(args));\n };\n }\n });\n (0, _lodash.each)(reducer.$$actions, function (creator, name) {\n if ((0, _lodash.isFunction)(creator)) prototype[name] = function () {\n for (var _len6 = arguments.length, args = Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {\n args[_key6] = arguments[_key6];\n }\n\n var action = creator.apply(this, args);\n if ((0, _lodash.isFunction)(action)) return function (dispatch, getState) {\n return action.call(null, dispatch, function () {\n return lastState;\n });\n };\n if (action.$$tag === undefined) return Object.assign({}, action, { $$tag: prototype.$$tag });\n return action;\n };\n });\n prototype.action = function (action) {\n if (action.$$tag !== undefined) throw new Error(\"reslice.action: action already has a tag: \" + action.$$tag);\n return Object.assign({}, action, { $$tag: prototype.$$tag });\n };\n /**\n * This is the actual reducer function that will be returned. Before\n * doing so, add a property which is a function that can be called\n * from outside to change the lastState; this is needed by the code\n * in extendReducer.\n **/\n var $$reducer = function $$reducer(state, action) {\n if (action.$$tag === undefined) if (!action.type.startsWith('@@')) throw new Error(\"reslice.reduce: $$tag is undefined: \" + JSON.stringify(action));\n var newState = reducer.$$reducer(state, action);\n /**\n * If the new state does not have a tag then it lacks the prototype,\n * so extend the prototype chain of the new object with the prototypes\n * derived above from the actions and selectors.\n **/\n if (newState.$$tag === undefined) {\n var newproto = Object.assign(Object.create(Object.getPrototypeOf(newState)), prototype);\n setPrototypeOf(newState, newproto);\n lastState = newState;\n }\n return newState;\n };\n prototype.reducer = function (action) {\n return $$reducer(this, action);\n };\n $$reducer.setLastState = function (state) {\n lastState = state;\n };\n return $$reducer;\n }\n wrapReducer.$$tag = reducer.$$tag;\n return wrapReducer();\n}",
"function debugAction(action) {\n debugger\n action.debug = true\n return action\n}",
"function newStackSpecificToolStateManager (toolTypes, oldStateManager) {\n let toolState = {};\n\n function saveToolState () {\n return toolState;\n }\n\n function restoreToolState (stackToolState) {\n toolState = stackToolState;\n }\n\n // Here we add tool state, this is done by tools as well\n // As modules that restore saved state\n function addStackSpecificToolState (element, toolType, data) {\n // If this is a tool type to apply to the stack, do so\n if (toolTypes.indexOf(toolType) >= 0) {\n\n // If we don't have tool state for this type of tool, add an empty object\n if (toolState.hasOwnProperty(toolType) === false) {\n toolState[toolType] = {\n data: []\n };\n }\n\n const toolData = toolState[toolType];\n\n // Finally, add this new tool to the state\n toolData.data.push(data);\n } else {\n // Call the imageId specific tool state manager\n return oldStateManager.add(element, toolType, data);\n }\n }\n\n // Here you can get state - used by tools as well as modules\n // That save state persistently\n function getStackSpecificToolState (element, toolType) {\n // If this is a tool type to apply to the stack, do so\n if (toolTypes.indexOf(toolType) >= 0) {\n // If we don't have tool state for this type of tool, add an empty object\n if (toolState.hasOwnProperty(toolType) === false) {\n toolState[toolType] = {\n data: []\n };\n }\n\n return toolState[toolType];\n }\n\n // Call the imageId specific tool state manager\n return oldStateManager.get(element, toolType);\n\n }\n\n const stackSpecificToolStateManager = {\n get: getStackSpecificToolState,\n add: addStackSpecificToolState,\n saveToolState,\n restoreToolState,\n toolState\n };\n\n\n return stackSpecificToolStateManager;\n}",
"function rootReducer(state = {}, action) {\n return {\n todos: todos(state.todos, action),\n goals: goals(state.goals, action),\n };\n}",
"function createReducer(initialState, actionsMap) {\n return function () {\n var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState;\n var action = arguments.length > 1 ? arguments[1] : undefined;\n // @ts-ignore createNextState() produces an Immutable<Draft<S>> rather\n // than an Immutable<S>, and TypeScript cannot find out how to reconcile\n // these two types.\n return Object(immer__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(state, function (draft) {\n var caseReducer = actionsMap[action.type];\n return caseReducer ? caseReducer(draft, action) : undefined;\n });\n };\n}",
"function extendReducer(reducer, extension) {\n return { $$extend: true, $$reducer: reducer, $$extension: extension };\n}",
"stateActionDispatch (action) {\n this.send('state.action.dispatch', { action })\n }",
"applyDesignatedState () {\n const dstate = this.designatedState;\n const cstate = this.currentState;\n this.designatedState = {};\n const command = {};\n if (typeof dstate.state !== 'undefined') { // check if HomeKit actually set an on/off state\n if (dstate.state === true && dstate.level !== 0) {\n command.state = 'On';\n if (this.platform.darkMode) { // set cached level in dark mode\n if (typeof dstate.level === 'undefined' && typeof cstate.cachedLevel !== 'undefined' && (dstate.state === true || cstate.state !== false)) {\n dstate.level = cstate.cachedLevel;\n } else if (typeof dstate.level === 'number') {\n if (cstate.powerOffByBrightness && dstate.level === 100) {\n cstate.powerOffByBrightness = false;\n dstate.level = cstate.cachedLevel;\n // TODO: why exactly is this here? can this be avoided with updateHomekitState()?\n this.accessory.getService(Service.Lightbulb).getCharacteristic(Characteristic.Brightness).updateValue(dstate.level);\n } else if (cstate.powerOffByBrightness === false) {\n cstate.cachedLevel = cstate.level;\n }\n }\n }\n if (dstate.level > 1) {\n command.level = dstate.level;\n } else if (dstate.level === 1) { // set night mode if level is 1, remove \"on\" from command\n delete command.state;\n command.commands = ['night_mode'];\n }\n cstate.level = dstate.level;\n } else {\n command.state = 'Off';\n if (this.platform.darkMode) {\n if (cstate.level !== 1) {\n cstate.cachedLevel = cstate.level;\n }\n if (dstate.level === 0) {\n cstate.powerOffByBrightness = true;\n } else {\n cstate.powerOffByBrightness = false;\n }\n command.level = 1;\n cstate.level = command.level;\n }\n }\n cstate.state = command.state;\n }\n if (dstate.saturation !== undefined) {\n if (dstate.saturation === 0) {\n if (command.commands) {\n command.commands = command.commands.concat(['set_white']);\n } else {\n command.commands = ['set_white'];\n }\n } else {\n command.saturation = dstate.saturation;\n }\n cstate.saturation = dstate.saturation;\n }\n if (dstate.hue !== undefined) {\n if (!(dstate.saturation === 0)) {\n command.hue = dstate.hue;\n }\n cstate.hue = dstate.hue;\n }\n if (!this.platform.rgbcctMode) {\n const useWhiteMode = TestWhiteMode(dstate.hue, dstate.saturation);\n if (useWhiteMode) {\n delete command.saturation;\n delete command.hue;\n let kelvin = 100;\n if (dstate.hue > 150) {\n kelvin = 0.5 - dstate.saturation / 40;\n } else {\n kelvin = Math.sqrt(dstate.saturation * 0.0033) + 0.5;\n kelvin = Math.min(1, Math.max(0, kelvin));\n }\n kelvin *= 100;\n kelvin = Math.round(kelvin);\n\n command.kelvin = kelvin;\n cstate.kelvin = kelvin;\n }\n } else if (dstate.color_temp !== undefined) {\n command.color_temp = dstate.color_temp;\n cstate.color_temp = dstate.color_temp;\n }\n this.platform.sendCommand(this.name, this.device_id, this.remote_type, this.group_id, command);\n }",
"function initStore (){\n if(ReactLogger){\n return createStore(\n reducer,\n applyMiddleware(logger)\n );\n }\n else{\n return createStore(reducer);\n }\n}",
"caseFuncsToReducer({$initState:initState,...caseMap}){\n return (state = initState, action) => {\n const reducer = caseMap[action.type];\n \n return reducer ? reducer(state, action) : state;\n };\n }",
"function createSerializableStateInvariantMiddleware() {\n var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n var _options$isSerializab = options.isSerializable,\n isSerializable = _options$isSerializab === void 0 ? isPlain : _options$isSerializab;\n return function (storeAPI) {\n return function (next) {\n return function (action) {\n var foundActionNonSerializableValue = findNonSerializableValue(action, [], isSerializable);\n\n if (foundActionNonSerializableValue) {\n var keyPath = foundActionNonSerializableValue.keyPath,\n _value = foundActionNonSerializableValue.value;\n console.error(NON_SERIALIZABLE_ACTION_MESSAGE, keyPath, _value, action);\n }\n\n var result = next(action);\n var state = storeAPI.getState();\n var foundStateNonSerializableValue = findNonSerializableValue(state);\n\n if (foundStateNonSerializableValue) {\n var _keyPath = foundStateNonSerializableValue.keyPath,\n _value2 = foundStateNonSerializableValue.value;\n console.error(NON_SERIALIZABLE_STATE_MESSAGE, _keyPath, _value2, action.type);\n }\n\n return result;\n };\n };\n };\n}",
"_copyReactRedux() {\n var reactReduxContext = this._getReactReduxContext();\n\n this.fs.copyTpl(\n this.templatePath(appConfig.config.path.reactRedux.templatePath + '/' + reactReduxContext.indexHTML),\n this.destinationPath(appConfig.config.path.reactRedux.destinationPath + '/' + reactReduxContext.indexHTML),\n {\n appName: _.startCase(this.appname)\n }\n );\n\n this.fs.copyTpl(\n this.templatePath(appConfig.config.path.reactRedux.templatePath + '/' + reactReduxContext.indexJS),\n this.destinationPath(appConfig.config.path.reactRedux.destinationPath + '/' + reactReduxContext.indexJS),\n {\n appName: this._formatAppName(this.appname),\n styleFramework: this.styleframework\n }\n );\n\n this.fs.copyTpl(\n this.templatePath(appConfig.config.path.reactRedux.templatePath + '/' + reactReduxContext.components + '/' + 'RootComponent.js'),\n this.destinationPath(appConfig.config.path.reactRedux.destinationPath + '/' + reactReduxContext.components + '/' + this.appname + '.js'),\n {\n appName: this.appname,\n styleFramework:this.styleframework\n }\n );\n\n this.fs.copy(\n this.templatePath(appConfig.config.path.reactRedux.templatePath + '/' + reactReduxContext.constant),\n this.destinationPath(appConfig.config.path.reactRedux.destinationPath + '/' + reactReduxContext.constant)\n );\n\n\n this.fs.copy(\n this.templatePath(appConfig.config.path.reactRedux.templatePath + '/' + reactReduxContext.actions),\n this.destinationPath(appConfig.config.path.reactRedux.destinationPath + '/' + reactReduxContext.actions)\n );\n\n this.fs.copy(\n this.templatePath(appConfig.config.path.reactRedux.templatePath + '/' + reactReduxContext.store),\n this.destinationPath(appConfig.config.path.reactRedux.destinationPath + '/' + reactReduxContext.store)\n );\n\n this.fs.copy(\n this.templatePath(appConfig.config.path.reactRedux.templatePath + '/' + reactReduxContext.reducer),\n this.destinationPath(appConfig.config.path.reactRedux.destinationPath + '/' + reactReduxContext.reducer)\n );\n\n this.fs.copy(\n this.templatePath(appConfig.config.path.reactRedux.templatePath + '/' + reactReduxContext.images),\n this.destinationPath(appConfig.config.path.reactRedux.destinationPath + '/' + reactReduxContext.images)\n );\n\n this.fs.copy(\n this.templatePath(appConfig.config.path.pureReact.templatePath + '/' + reactReduxContext.styles+'/'+'scss'),\n this.destinationPath(appConfig.config.path.pureReact.destinationPath + '/' + reactReduxContext.styles+'/'+'scss')\n );\n\n if(this.styleframework === 'uxframework'){\n this.fs.copy(\n this.templatePath(appConfig.config.path.pureReact.templatePath + '/' + reactReduxContext.styles+'/'+'main-ux-frmwrk.scss'),\n this.destinationPath(appConfig.config.path.pureReact.destinationPath + '/' + reactReduxContext.styles+'/'+'main.scss')\n );\n }else{\n this.fs.copy(\n this.templatePath(appConfig.config.path.pureReact.templatePath + '/' + reactReduxContext.styles+'/'+'main.scss'),\n this.destinationPath(appConfig.config.path.pureReact.destinationPath + '/' + reactReduxContext.styles+'/'+'main.scss')\n );\n }\n }",
"function configureStore(){\n return createStore(calculatorReducer);\n}",
"function createSerializableStateInvariantMiddleware(options) {\n if (options === void 0) {\n options = {};\n }\n\n var _options = options,\n _options$isSerializab = _options.isSerializable,\n isSerializable = _options$isSerializab === void 0 ? isPlain : _options$isSerializab,\n getEntries = _options.getEntries,\n _options$ignoredActio = _options.ignoredActions,\n ignoredActions = _options$ignoredActio === void 0 ? [] : _options$ignoredActio,\n _options$ignoredActio2 = _options.ignoredActionPaths,\n ignoredActionPaths = _options$ignoredActio2 === void 0 ? ['meta.arg'] : _options$ignoredActio2,\n _options$ignoredPaths = _options.ignoredPaths,\n ignoredPaths = _options$ignoredPaths === void 0 ? [] : _options$ignoredPaths,\n _options$warnAfter = _options.warnAfter,\n warnAfter = _options$warnAfter === void 0 ? 32 : _options$warnAfter;\n return function (storeAPI) {\n return function (next) {\n return function (action) {\n if (ignoredActions.length && ignoredActions.indexOf(action.type) !== -1) {\n return next(action);\n }\n\n var measureUtils = getTimeMeasureUtils(warnAfter, 'SerializableStateInvariantMiddleware');\n measureUtils.measureTime(function () {\n var foundActionNonSerializableValue = findNonSerializableValue(action, [], isSerializable, getEntries, ignoredActionPaths);\n\n if (foundActionNonSerializableValue) {\n var keyPath = foundActionNonSerializableValue.keyPath,\n value = foundActionNonSerializableValue.value;\n console.error(\"A non-serializable value was detected in an action, in the path: `\" + keyPath + \"`. Value:\", value, '\\nTake a look at the logic that dispatched this action: ', action, '\\n(See https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants)', '\\n(To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)');\n }\n });\n var result = next(action);\n measureUtils.measureTime(function () {\n var state = storeAPI.getState();\n var foundStateNonSerializableValue = findNonSerializableValue(state, [], isSerializable, getEntries, ignoredPaths);\n\n if (foundStateNonSerializableValue) {\n var keyPath = foundStateNonSerializableValue.keyPath,\n value = foundStateNonSerializableValue.value;\n console.error(\"A non-serializable value was detected in the state, in the path: `\" + keyPath + \"`. Value:\", value, \"\\nTake a look at the reducer(s) handling this action type: \" + action.type + \".\\n(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)\");\n }\n });\n measureUtils.warnIfExceeded();\n return result;\n };\n };\n };\n}",
"_transferLayerState(oldLayer, newLayer) {\n newLayer._transferState(oldLayer);\n\n newLayer.lifecycle = _lifecycle_constants__WEBPACK_IMPORTED_MODULE_1__[\"LIFECYCLE\"].MATCHED;\n\n if (newLayer !== oldLayer) {\n oldLayer.lifecycle = _lifecycle_constants__WEBPACK_IMPORTED_MODULE_1__[\"LIFECYCLE\"].AWAITING_GC;\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ensures that given transaction object has the "errors" key where custom test run errors (not validation errors) are stored. | ensureTransactionErrors(transaction) {
if (!transaction.results) {
transaction.results = {};
}
if (!transaction.errors) {
transaction.errors = [];
}
return transaction.errors;
} | [
"ensureTestStructure(transaction) {\n transaction.test.request = transaction.request;\n transaction.test.expected = transaction.expected;\n transaction.test.actual = transaction.real;\n transaction.test.errors = transaction.errors;\n transaction.test.results = transaction.results;\n }",
"function addErrors(errors) {\n const existing = store.getters.errors.concat();\n const existingCodes = existing.map((e) => e.code).concat(IGNORED_ERROR_CODES);\n const newErrors = (errors || []).filter((e) => existingCodes.indexOf(e.code) === -1);\n\n if (newErrors) {\n store.commit('errors', existing.concat(newErrors));\n }\n}",
"failTransaction(transaction, reason) {\n transaction.fail = true;\n\n this.ensureTransactionErrors(transaction);\n if (reason) {\n transaction.errors.push({ severity: 'error', message: reason });\n }\n\n if (!transaction.test) {\n transaction.test = this.createTest(transaction);\n }\n transaction.test.status = 'fail';\n if (reason) {\n transaction.test.message = reason;\n }\n\n this.ensureTestStructure(transaction);\n }",
"function widgetChangeErrors(errors) {\n\t\t\treturn shiftArrayErrorsKeys(errors, {\n\t\t\t\tarrayKey: schema.key,\n\t\t\t\tminIndex: indexToRemove,\n\t\t\t\tshouldRemoveIndex: index => index === indexToRemove,\n\t\t\t\tgetNextIndex: index => index - 1,\n\t\t\t});\n\t\t}",
"setErrorTopic({ commit }, payload) {\n if (payload.hasOwnProperty('topic')) commit('setErrorTopic', payload)\n else console.warn('Payload does not have \"topic\" property in \"connection/setErrorTopic\"')\n }",
"function wrapError(error, name) {\n if (!TRANSACTION_ERROR_CODES.includes(name)) return Error(`Passed error name ${name} is not valid.`)\n error.code = name\n return error\n}",
"static isFailedTx(result) {\n if (!result) {\n return true;\n }\n if (CommonUtil.isDict(result.result_list)) {\n for (const subResult of Object.values(result.result_list)) {\n if (CommonUtil.isFailedTxResultCode(subResult.code)) {\n return true;\n }\n if (subResult.func_results) {\n if (CommonUtil.isFailedFuncTrigger(subResult.func_results)) {\n return true;\n }\n }\n }\n return false;\n }\n if (CommonUtil.isFailedTxResultCode(result.code)) {\n return true;\n }\n if (result.func_results) {\n if (CommonUtil.isFailedFuncTrigger(result.func_results)) {\n return true;\n }\n }\n return false;\n }",
"hasValidTransactions() {\n for (const tx of this.transactions) {\n if (!tx.isValid()) {\n return false;\n }\n }\n return true;\n }",
"verify() {\n var i; // Basic checks that don't depend on any context\n\n if (this.inputs.length === 0) {\n return 'transaction txins empty';\n }\n\n if (this.outputs.length === 0) {\n return 'transaction txouts empty';\n } // Check for negative or overflow output values\n\n\n var valueoutbn = new _bn.default(0);\n\n for (i = 0; i < this.outputs.length; i += 1) {\n if (this.outputs[i].invalidSatoshis()) {\n return 'Transaction output contains invalid amount';\n }\n\n if (this.outputs[i]._satoshisBN.gt(new _bn.default(Transaction.MAX_MONEY, 10))) {\n return 'Transaction output contains too high satoshi amount';\n }\n\n valueoutbn = valueoutbn.add(this.outputs[i]._satoshisBN);\n\n if (valueoutbn.gt(new _bn.default(Transaction.MAX_MONEY))) {\n return 'Transaction output contains too high satoshi amount';\n }\n } // Size limits\n\n\n if (this.toBuffer().length > MAX_BLOCK_SIZE) {\n return 'Transaction over the maximum block size';\n } // Check for duplicate inputs\n\n\n var txinmap = {};\n\n for (i = 0; i < this.inputs.length; i += 1) {\n var inputid = \"\".concat(this.inputs[i].prevTxId, \":\").concat(this.inputs[i].outputIndex);\n\n if (txinmap[inputid] !== undefined) {\n return 'Transaction contains duplicate input';\n }\n\n txinmap[inputid] = true;\n }\n\n var isCoinbase = this.isCoinbase();\n\n if (isCoinbase) {\n var buf = this.inputs[0]._scriptBuffer;\n\n if (buf.length < 2 || buf.length > 100) {\n return 'Coinbase transaction script size invalid';\n }\n } else if (this.inputs.filter(input => input.isNull()).length > 0) {\n return 'Transaction has null input';\n }\n\n return true;\n }",
"function validateCommitAndCollectErrors() {\n ////////////////////////////////////\n // Checking revert, squash, fixup //\n ////////////////////////////////////\n var _a;\n // All revert commits are considered valid.\n if (commit.isRevert) {\n return true;\n }\n // All squashes are considered valid, as the commit will be squashed into another in\n // the git history anyway, unless the options provided to not allow squash commits.\n if (commit.isSquash) {\n if (options.disallowSquash) {\n errors.push('The commit must be manually squashed into the target commit');\n return false;\n }\n return true;\n }\n // Fixups commits are considered valid, unless nonFixupCommitHeaders are provided to check\n // against. If `nonFixupCommitHeaders` is not empty, we check whether there is a corresponding\n // non-fixup commit (i.e. a commit whose header is identical to this commit's header after\n // stripping the `fixup! ` prefix), otherwise we assume this verification will happen in another\n // check.\n if (commit.isFixup) {\n if (options.nonFixupCommitHeaders && !options.nonFixupCommitHeaders.includes(commit.header)) {\n errors.push('Unable to find match for fixup commit among prior commits: ' +\n (options.nonFixupCommitHeaders.map(function (x) { return \"\\n \" + x; }).join('') || '-'));\n return false;\n }\n return true;\n }\n ////////////////////////////\n // Checking commit header //\n ////////////////////////////\n if (commit.header.length > config.maxLineLength) {\n errors.push(\"The commit message header is longer than \" + config.maxLineLength + \" characters\");\n return false;\n }\n if (!commit.type) {\n errors.push(\"The commit message header does not match the expected format.\");\n return false;\n }\n if (config_1.COMMIT_TYPES[commit.type] === undefined) {\n errors.push(\"'\" + commit.type + \"' is not an allowed type.\\n => TYPES: \" + Object.keys(config_1.COMMIT_TYPES).join(', '));\n return false;\n }\n /** The scope requirement level for the provided type of the commit message. */\n var scopeRequirementForType = config_1.COMMIT_TYPES[commit.type].scope;\n if (scopeRequirementForType === config_1.ScopeRequirement.Forbidden && commit.scope) {\n errors.push(\"Scopes are forbidden for commits with type '\" + commit.type + \"', but a scope of '\" + commit.scope + \"' was provided.\");\n return false;\n }\n if (scopeRequirementForType === config_1.ScopeRequirement.Required && !commit.scope) {\n errors.push(\"Scopes are required for commits with type '\" + commit.type + \"', but no scope was provided.\");\n return false;\n }\n var fullScope = commit.npmScope ? commit.npmScope + \"/\" + commit.scope : commit.scope;\n if (fullScope && !config.scopes.includes(fullScope)) {\n errors.push(\"'\" + fullScope + \"' is not an allowed scope.\\n => SCOPES: \" + config.scopes.join(', '));\n return false;\n }\n // Commits with the type of `release` do not require a commit body.\n if (commit.type === 'release') {\n return true;\n }\n //////////////////////////\n // Checking commit body //\n //////////////////////////\n // Due to an issue in which conventional-commits-parser considers all parts of a commit after\n // a `#` reference to be the footer, we check the length of all of the commit content after the\n // header. In the future, we expect to be able to check only the body once the parser properly\n // handles this case.\n var allNonHeaderContent = commit.body.trim() + \"\\n\" + commit.footer.trim();\n if (!((_a = config.minBodyLengthTypeExcludes) === null || _a === void 0 ? void 0 : _a.includes(commit.type)) &&\n allNonHeaderContent.length < config.minBodyLength) {\n errors.push(\"The commit message body does not meet the minimum length of \" + config.minBodyLength + \" characters\");\n return false;\n }\n var bodyByLine = commit.body.split('\\n');\n var lineExceedsMaxLength = bodyByLine.some(function (line) {\n // Check if any line exceeds the max line length limit. The limit is ignored for\n // lines that just contain an URL (as these usually cannot be wrapped or shortened).\n return line.length > config.maxLineLength && !COMMIT_BODY_URL_LINE_RE.test(line);\n });\n if (lineExceedsMaxLength) {\n errors.push(\"The commit message body contains lines greater than \" + config.maxLineLength + \" characters.\");\n return false;\n }\n // Breaking change\n // Check if the commit message contains a valid break change description.\n // https://github.com/angular/angular/blob/88fbc066775ab1a2f6a8c75f933375b46d8fa9a4/CONTRIBUTING.md#commit-message-footer\n if (INCORRECT_BREAKING_CHANGE_BODY_RE.test(commit.fullText)) {\n errors.push(\"The commit message body contains an invalid breaking change note.\");\n return false;\n }\n if (INCORRECT_DEPRECATION_BODY_RE.test(commit.fullText)) {\n errors.push(\"The commit message body contains an invalid deprecation note.\");\n return false;\n }\n return true;\n }",
"emitError(error, test) {\n logger.debug('Emitting to reporters: test error');\n this.configuration.emitter.emit('test error', error, test, eventCallback);\n\n // Record the error to halt the transaction runner. Do not overwrite\n // the first recorded error if more of them occured.\n this.error = this.error || error;\n }",
"static txPrecheckFailed(result) {\n const precheckFailureCode = [21, 22, 3, 15, 33, 16, 17, 34, 35];\n return precheckFailureCode.includes(result.code);\n }",
"validTransactions() {\n\t\t// must meet following conditions:\n\t\t// verify signature of every transaction\n\t\t// but we can return a filtered down version, doesn't need\n\t\t// to be the whole thing\n\t\treturn this.transactions.filter(transaction => {\n\t\t\t// total amount of outputs in transaction matches whats in output\n\t\t\tconst outputTotal = transaction.outputs.reduce((total, output) => {\n\t\t\t\treturn total + output.amount;\n\t\t\t}, 0);\n\n\t\t\t// verify output totals\n\t\t\tif (transaction.input.amount !== outputTotal) { \n\t\t\t\tconsole.log(`Invalid transaction from ${transaction.input.address}.`);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// verify signature\n\t\t\tif (!Transaction.verifyTransaction(transaction)) {\n\t\t\t\tconsole.log(`Invalid Signature from ${transaction.input.address}`);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\treturn transaction;\n\t\t});\n\t}",
"function checkErrors(data) {\n\tif (data['error'] !== false) {\n\t\tconsole.log(data['error']);\n\t\treturn true;\n\t} else {\n\t\treturn false;\n\t}\n}",
"validate() {\n const seenTables = new Map();\n for (const meta of this.values()) {\n if (seenTables.get(meta.tableName)) {\n throw new Error(\n `DB table \"${meta.tableName}\" already exists. Change the collectionName of the related content type.`\n );\n }\n seenTables.set(meta.tableName, true);\n }\n }",
"hasTrump() {\n if(this.trump === undefined) {\n throw new Error('Trump is not defined.');\n }\n }",
"function printValidationErrors(errors, print) {\n if (print === void 0) { print = console_1.error; }\n print.group(\"Error\" + (errors.length === 1 ? '' : 's') + \":\");\n errors.forEach(function (line) { return print(line); });\n print.groupEnd();\n print();\n print('The expected format for a commit is: ');\n print('<type>(<scope>): <summary>');\n print();\n print('<body>');\n print();\n print(\"BREAKING CHANGE: <breaking change summary>\");\n print();\n print(\"<breaking change description>\");\n print();\n print();\n }",
"_setErrorList (errorList) {\n this.errorList = []\n\n _.toArray(errorList)\n .forEach(fieldSet => this._addErrorList(fieldSet))\n }",
"getAccumulatedTransactionErrors$({ args }, authToken) {\n return RoleValidator.checkPermissions$(\n authToken.realm_access.roles,\n \"ACSS\",\n \"getAccumulatedTransactionError$()\",\n PERMISSION_DENIED_ERROR_CODE.code,\n PERMISSION_DENIED_ERROR_CODE.description,\n [\"PLATFORM-ADMIN\"]\n )\n .mergeMap(roles => {\n return LogErrorDA.getAccumulatedTransactionErrors$(args.page, args.count)\n })\n .mergeMap(rawResponse => this.buildSuccessResponse$(rawResponse))\n .catch(err => {\n return this.handleError$(err);\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a new VRDeviceOrientationGamepadCamera | function VRDeviceOrientationGamepadCamera(name,position,scene,compensateDistortion,vrCameraMetrics){if(compensateDistortion===void 0){compensateDistortion=true;}if(vrCameraMetrics===void 0){vrCameraMetrics=BABYLON.VRCameraMetrics.GetDefault();}var _this=_super.call(this,name,position,scene,compensateDistortion,vrCameraMetrics)||this;_this.inputs.addGamepad();return _this;} | [
"function DeviceOrientationCamera(name,position,scene){var _this=_super.call(this,name,position,scene)||this;_this._quaternionCache=new BABYLON.Quaternion();_this.inputs.addDeviceOrientation();return _this;}",
"function UniversalCamera(name,position,scene){var _this=_super.call(this,name,position,scene)||this;_this.inputs.addGamepad();return _this;}",
"function StereoscopicGamepadCamera(name,position,interaxialDistance,isStereoscopicSideBySide,scene){var _this=_super.call(this,name,position,scene)||this;_this.interaxialDistance=interaxialDistance;_this.isStereoscopicSideBySide=isStereoscopicSideBySide;_this.setCameraRigMode(isStereoscopicSideBySide?BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:interaxialDistance});return _this;}",
"setupCamera() {\r\n \r\n var camera = new Camera();\r\n camera.setPerspective(FOV, this.vWidth/this.vHeight, NEAR, FAR);\r\n //camera.setOrthogonal(-30, 30, -30, 30, NEAR, FAR);\r\n camera.setView();\r\n\r\n return camera;\r\n }",
"function GyroPositionSensorVRDevice() {\n // Subscribe to deviceorientation events.\n window.addEventListener('deviceorientation', this.onDeviceOrientationChange.bind(this));\n window.addEventListener('orientationchange', this.onScreenOrientationChange.bind(this));\n this.deviceOrientation = null;\n this.screenOrientation = window.orientation;\n\n // Helper objects for calculating orientation.\n this.finalQuaternion = new THREE.Quaternion();\n this.deviceEuler = new THREE.Euler();\n this.screenTransform = new THREE.Quaternion();\n // -PI/2 around the x-axis.\n this.worldTransform = new THREE.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));\n}",
"function VRDeviceOrientationArcRotateCamera(name,alpha,beta,radius,target,scene,compensateDistortion,vrCameraMetrics){if(compensateDistortion===void 0){compensateDistortion=true;}if(vrCameraMetrics===void 0){vrCameraMetrics=BABYLON.VRCameraMetrics.GetDefault();}var _this=_super.call(this,name,alpha,beta,radius,target,scene)||this;vrCameraMetrics.compensateDistortion=compensateDistortion;_this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR,{vrCameraMetrics:vrCameraMetrics});_this.inputs.addVRDeviceOrientation();return _this;}",
"function DaydreamController(vrGamepad){var _this=_super.call(this,vrGamepad)||this;_this.controllerType=BABYLON.PoseEnabledControllerType.DAYDREAM;return _this;}",
"addCamera() {\n this.camera = new THREE.PerspectiveCamera(\n 70,\n this.width / this.height,\n 0.01,\n 10\n );\n this.camera.position.z = 1;\n }",
"function VirtualJoysticksCamera(name,position,scene){var _this=_super.call(this,name,position,scene)||this;_this.inputs.addVirtualJoystick();return _this;}",
"toggleCamera() {\n this.controls.enable = false;\n if (this.camera === this.orthoCamera) {\n this.camera = this.perspCamera;\n this.controls = this.perspControls;\n }\n else {\n this.camera = this.orthoCamera;\n this.controls = this.orthoControls;\n }\n this.controls.enable = true;\n this.controls.reset();\n }",
"function ViveController(vrGamepad){var _this=_super.call(this,vrGamepad)||this;_this.controllerType=BABYLON.PoseEnabledControllerType.VIVE;_this._invertLeftStickY=true;return _this;}",
"createCamerasAndControls() {\n let width = this.refs.msCanvas.clientWidth, height = this.refs.msCanvas.clientHeight;\n\n // orthographic\n this.orthoCamera = new THREE.OrthographicCamera();\n this.orthoCamera.zoom = 2.5;\n this.orthoCamera.position.set(0, -1, 0.5);\n this.orthoCamera.up.set(0, 0, 1);\n this.orthoCamera.add(new THREE.PointLight(0xffffff, 1));\n this.orthoCamera.name = \"camera\";\n this.updateOrthoCamera(width, height);\n\n this.orthoControls = new OrbitControls(this.orthoCamera, this.renderer.domElement);\n this.orthoControls.enable = false;\n this.orthoControls.screenSpacePanning = true;\n this.orthoControls.minDistance = this.orthoCamera.near;\n this.orthoControls.maxDistance = this.orthoCamera.far;\n this.orthoControls.target0.set(0, 0, 0.5); // setting target0 since controls.reset() uses this... todo: try controls.saveState \n this.orthoControls.addEventListener( 'change', this.renderScene );\n\n // perspective\n const fov = 25; // narrow field of view so objects don't shrink so much in the distance\n const aspect = width / height;\n const near = 0.001;\n const far = 100;\n this.perspCamera = new THREE.PerspectiveCamera(fov, aspect, near, far);\n this.perspCamera.position.set(0, -6, 0.5);\n this.perspCamera.up.set(0, 0, 1);\n this.perspCamera.add(new THREE.PointLight(0xffffff, 1));\n this.perspCamera.name = \"camera\";\n this.updatePerspCamera(width, height);\n \n this.perspControls = new OrbitControls(this.perspCamera, this.renderer.domElement);\n this.perspControls.enable = false;\n this.perspControls.screenSpacePanning = true;\n this.perspControls.minDistance = this.perspCamera.near;\n this.perspControls.maxDistance = this.perspCamera.far;\n this.perspControls.target0.set(0, 0, 0.5); // setting target0 since controls.reset() uses this... todo: try controls.saveState \n this.perspControls.addEventListener( 'change', this.renderScene );\n\n // set default to perspective\n this.camera = this.perspCamera;\n this.controls = this.perspControls;\n this.controls.enable = true;\n }",
"function camera_perspective_view() {\n camera.rotation.y += Math.PI/4;\n camera.position.x = 2.0;\n camera.position.z = 2.8;\n camera.position.y = 0.6; \n}",
"setPlayerCamera() {\n this.scene.updateGameCamera('game')\n }",
"initCameras() {\n this.camera = new CGFcamera(0.4, 0.1, 500, vec3.fromValues(0, 12, -15), vec3.fromValues(0, 10, 0));\n this.interface.setActiveCamera(this.camera);\n }",
"constructor(info: CameraInfo) {\n const { binning_x, binning_y, roi, distortion_model, D, K, P, R } = info;\n\n if (distortion_model === \"\") {\n // Allow CameraInfo with no model to indicate no distortion\n this._distortionState = DISTORTION_STATE.NONE;\n return;\n }\n\n // Binning = 0 is considered the same as binning = 1 (no binning).\n const binningX = binning_x ? binning_x : 1;\n const binningY = binning_y ? binning_y : 1;\n\n const adjustBinning = binningX > 1 || binningY > 1;\n const adjustRoi = roi.x_offset !== 0 || roi.y_offset !== 0;\n\n if (adjustBinning || adjustRoi) {\n throw new Error(\n \"Failed to initialize camera model: unable to handle adjusted binning and adjusted roi camera models.\"\n );\n }\n\n // See comments about Tx = 0, Ty = 0 in\n // http://docs.ros.org/melodic/api/sensor_msgs/html/msg/CameraInfo.html\n if (P[3] !== 0 || P[7] !== 0) {\n throw new Error(\n \"Failed to initialize camera model: projection matrix implies non monocular camera - cannot handle at this time.\"\n );\n }\n\n // Figure out how to handle the distortion\n if (distortion_model === \"plumb_bob\" || distortion_model === \"rational_polynomial\") {\n this._distortionState = D[0] === 0.0 ? DISTORTION_STATE.NONE : DISTORTION_STATE.CALIBRATED;\n } else {\n throw new Error(\n \"Failed to initialize camera model: distortion_model is unknown, only plumb_bob and rational_polynomial are supported.\"\n );\n }\n this.D = D;\n this.P = P;\n this.R = R;\n this.K = K;\n }",
"function initKrpano () {\n krpanoViewer.init({\n el: document.querySelector('#vrmaker-krpano'),\n panoramas\n })\n\n // krpano viewer config\n var config = {\n autoRotateSettings: {\n active: true,\n revert: false,\n rotateDuration: 200000,\n restartTime: 20000\n },\n gyroSettings: {\n active: false\n },\n basicSettings: {\n mwheel: true,\n focus: false\n },\n tripodSettings: {\n image: 'http://i.imgur.com/xNNfJiP.jpg',\n size: 60 // 0 ~ 100\n },\n loadingSettings: {\n onLoadingPanoramaStart () {\n console.log('onLoadingPanoramaStart')\n },\n onLoadingPanoramaFinish () {\n console.log('onLoadingPanoramaFinish')\n },\n onLoadingPanoramaProgress (event) {\n console.log('onLoadingPanoramaProgress', event)\n },\n onLoadingPanoramaError (error) {\n console.log('onLoadingPanoramaError', error)\n }\n },\n initViewSettings: {\n active: true\n }\n }\n // generate krpano viewer\n krpanoViewer.generateKrpano(config)\n}",
"getCameraPlane() {\n\n const camera = this.viewer.navigation.getCamera()\n\n const normal = camera.target.clone().sub(\n camera.position).normalize()\n\n const pos = camera.position\n\n const dist =\n -normal.x * pos.x\n - normal.y * pos.y\n - normal.z * pos.z\n\n return new THREE.Plane(normal, dist)\n }",
"function mCamera() {\n camera(...[...arguments]);\n mPage.camera(...[...arguments]);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function that given a cookie and a field of the registration form it returns the value of that cookie for that field | function getValueFromCookie(cookieName, field) {
/* Get the string of values from the cookie */
var str = getCookie(cookieName);
var values = str.split(','); /* Split the values by the , */
var n = document.forms["registerForm"].length;
/* Go over every field of the registration form to look for the index of the one we're looking for */
for (var i = 0; i < n-3; i++) {
var fieldName = document.forms["registerForm"][i].name;
if (fieldName == field) {
/* Return the cookie value in the index of the field */
return values[i];
}
}
/* Return an empty string if the value wasn't found */
return "";
} | [
"function getCookieLogin() {\r\n\tvar cookies = document.cookie; // gets the cookie\r\n\tif (cookies != \"\") {\r\n\t\tvar cookieArray = cookies.split(';');\r\n\t\tfor (var i = 0; i < cookieArray.length; i++) {\r\n\t\t\tvar key = cookieArray[i].split('=')[0];\r\n\t\t\tkey = key.trim();\r\n\t\t\tvar value = cookieArray[i].split('=')[1];\r\n\t\t\tvar valuesArray = value.split(\"---\");\r\n\t\t\tvar userEmail = decodeURI(valuesArray[0]);\r\n\t\t\treturn userEmail;\r\n\r\n\t\t}\r\n\t}\r\n}",
"function getCookiePassword( name ){\n\n\t//If a user exists, check for password of that user.\n\tif( getCookieName( name ) != -1 ){\n\t\t\n\t\tvar value = document.cookie;\n\t\t\n\t\t//Setting start variable to where the password starts.\n\t\tvar nameIndex = value.indexOf( name );\n\t\tvar start = value.indexOf( \"password\" , nameIndex ) + 9;\n\t\tvar end = value.indexOf( \",\" , start );\n\t\t\n\t\t//Sets value as the password.\n\t\tvalue = decodeURI( value.substring( start, end ) );\n\t\t\n\t\treturn value;//Returns the string between given indexes.\n\t\n\t}\n\t\n\treturn -1;//If the username doesnt exists, then the function returns -1.\n\n}//End function getCookiePassword().",
"function checkCookie(){\n\t// remove jwt\n\tcreateCookie(\"jwt\", \"\", 1);\n\tvar usrName = accessCookie(\"username\");\n\tvar usrPssword = accessCookie(\"usrpassword\");\n\n\tif (usrName!=\"\"){\n\t\tdocument.getElementById('inputUsername').value = usrName;\n\t\tdocument.getElementById('inputPassword').value = usrPssword;\n\t}\n}",
"function get_cookie(request){\n console.log(request.headers.get('Cookie'));\n if (request.headers.get('Cookie')) {\n const pattern = new RegExp('variant=([10])');\n let match = request.headers.get('Cookie').match(pattern);\n if (match) { \n return match[1]; \n }\n }\n return null\n}",
"function getTokenInCookie(){\n let token = document.cookie.slice(document.cookie.lastIndexOf(\"=\")+1);\n return token;\n}",
"function getCookie(name) {\n var index = document.cookie.indexOf(name + \"=\")\n if (index == -1) { return \"undefined\"}\n index = document.cookie.indexOf(\"=\", index) + 1\n var end_string = document.cookie.indexOf(\";\", index)\n if (end_string == -1) { end_string = document.cookie.length }\n return unescape(document.cookie.substring(index, end_string))\n} // Based on JavaScript provided by Peter Curtis at www.pcurtis.com -->",
"keyForCookie(cookie) {\n const { domain, path, name } = cookie;\n return `${domain};${path};${name}`;\n }",
"function getDate(){\n var cookieArray = document.cookie.split(' ');\n return cookieArray[1];\n}",
"function getCookieInfo () {\n // return the contact cookie to be used as an Object\n return concurUtilHttp.getDeserializedQueryString($.cookie('concur_contact_data'));\n }",
"function formField(type, key, val, units) \n{\n if(type == 'chooseOne') return chooseOneField(key, val);\n else return inputField(key, val, units);\n}",
"function getSpCookie(cookieName, appID) {\n var matcher;\n console.log(appID);\n if(appID == undefined){\n matcher = new RegExp(cookieName + 'id\\\\.[0-9a-z]+=([0-9a-z\\-]+).*?');\n }\n else{\n matcher = new RegExp(cookieName + '[a-z0-9]+=([^;]+);?');\n }\n var match = document.cookie.match(matcher);\n console.log(document.cookie);\n console.log(match);\n if (match && match[1])\n return match[1].split()[0];\n else\n return null;\n }",
"function MatchCookie(name, value)\n{\n this.name = name;\n this.value = value;\n}",
"static getCookie(name) {\n var arg = name + \"=\";\n var alen = arg.length;\n var clen = document.cookie.length;\n var i = 0;\n while (i < clen) {\n var j = i + alen;\n if (document.cookie.substring(i, j) == arg) {\n return CookieUtil.getCookieVal(j);\n }\n i = document.cookie.indexOf(\" \", i) + 1;\n if (i == 0) break;\n }\n return null;\n }",
"get fieldValue(){}",
"function kva_uuid() {\n var uuid = Cookies.get('kva_uuid');\n if (typeof uuid === 'undefined') {\n Cookies.set('kva_uuid', UUID(), {expires: 365});\n uuid = Cookies.get('kva_uuid');\n }\n return uuid;\n}",
"function CookieUtilities_getSurveyCookie()\n {\n return this.getCookieValue(SiteRecruit_Config.cookieName);\n }",
"function loadUserInfoFromCookie()\n {\n userName = $.cookie(\"perc_userName\");\n isAdmin = $.cookie(\"perc_isAdmin\") == 'true' ? true : false;\n isDesigner = $.cookie(\"perc_isDesigner\") == 'true' ? true : false;\n isAccessibilityUser = $.cookie(\"perc_isAccessibilityUser\") == 'true' ? true : false;\n\t \n $.perc_utils.info(\"UserInfo\", \"userName: \" + userName + \", isAdmin: \" + isAdmin + \", isDesigner: \" + isDesigner + \", isAccessibilityUser: \" + isAccessibilityUser);\n }",
"function create_cookie(name, res)\n{\n\tvar curr_time = Date.now();\n\tvar id = sha1(curr_time);\n\tconsole.log(\"sha1 hash of \" + curr_time + \" is \" + id);\n\t// set mutli cookie\n\t// expire on 12 hrs\n\tres.cookie(\"id\", id, {expires: new Date(Date.now() + 43200000)});\n\tres.cookie(\"username\", name, {expires: new Date(Date.now() + 43200000)});\n\treturn id;\n}",
"static genNewCookie(cookie){\n let res = cookie.type;\n while (res === cookie.type){\n res = Math.floor((Math.random()*6));\n }\n return new Cookie(res, cookie.ligne, cookie.colonne);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Visit a parse tree produced by Python3Parseryield_stmt. | visitYield_stmt(ctx) {
console.log("visitYield_stmt");
return this.visit(ctx.yield_expr());
} | [
"visitYield_expr(ctx) {\r\n console.log(\"visitYield_expr\");\r\n if (ctx.yield_arg() !== null) {\r\n return { type: \"YieldStatement\", arg: this.visit(ctx.yield_arg()) };\r\n } else {\r\n return { type: \"YieldStatement\", arg: [] };\r\n }\r\n }",
"visitFlow_stmt(ctx) {\r\n console.log(\"visitFlow_stmt\");\r\n if (ctx.break_stmt() !== null) {\r\n return this.visit(ctx.break_stmt());\r\n } else if (ctx.continue_stmt() !== null) {\r\n return this.visit(ctx.continue_stmt());\r\n } else if (ctx.return_stmt() !== null) {\r\n return this.visit(ctx.return_stmt());\r\n } else if (ctx.raise_stmt() !== null) {\r\n return this.visit(ctx.raise_stmt());\r\n } else if (ctx.yield_stmt() !== null) {\r\n return this.visit(ctx.yield_stmt());\r\n }\r\n }",
"visitCompound_stmt(ctx) {\r\n console.log(\"visitCompound_stmt\");\r\n if (ctx.if_stmt() !== null) {\r\n return this.visit(ctx.if_stmt());\r\n } else if (ctx.while_stmt() !== null) {\r\n return this.visit(ctx.while_stmt());\r\n } else if (ctx.for_stmt() !== null) {\r\n return this.visit(ctx.for_stmt());\r\n } else if (ctx.try_stmt() !== null) {\r\n return this.visit(ctx.try_stmt());\r\n } else if (ctx.with_stmt() !== null) {\r\n return this.visit(ctx.with_stmt());\r\n } else if (ctx.funcdef() !== null) {\r\n return this.visit(ctx.funcdef());\r\n } else if (ctx.classdef() !== null) {\r\n return this.visit(ctx.classdef());\r\n } else if (ctx.decorated() !== null) {\r\n return this.visit(ctx.decorated());\r\n }\r\n }",
"function Python3Listener() {\n\tantlr4.tree.ParseTreeListener.call(this);\n\treturn this;\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 }",
"visitLoop_statement(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitQuery_block(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitData_manipulation_language_statements(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitSeq_of_statements(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function cdqlv3Visitor() {\n\tantlr4.tree.ParseTreeVisitor.call(this);\n\treturn this;\n}",
"visitSmall_stmt(ctx) {\r\n console.log(\"visitSmall_stmt\");\r\n if (ctx.expr_stmt() !== null) {\r\n return this.visit(ctx.expr_stmt());\r\n } else if (ctx.del_stmt() !== null) {\r\n return this.visit(ctx.del_stmt());\r\n } else if (ctx.pass_stmt() !== null) {\r\n return this.visit(ctx.pass_stmt());\r\n } else if (ctx.flow_stmt() !== null) {\r\n return this.visit(ctx.flow_stmt());\r\n } else if (ctx.import_stmt() !== null) {\r\n return this.visit(ctx.import_stmt());\r\n } else if (ctx.global_stmt() !== null) {\r\n return this.visit(ctx.global_stmt());\r\n } else if (ctx.nonlocal_stmt() !== null) {\r\n return this.visit(ctx.nonlocal_stmt());\r\n } else if (ctx.assert_stmt() !== null) {\r\n return this.visit(ctx.assert_stmt());\r\n }\r\n }",
"visitContinue_statement(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitGlobal_stmt(ctx) {\r\n console.log(\"visitGlobal_stmt\");\r\n let globallist = [];\r\n for (var i = 0; i < ctx.NAME().length; i++) {\r\n globallist.push(this.visit(ctx.NAME(i)));\r\n }\r\n return { type: \"GlobalStatement\", globallist: globallist };\r\n }",
"visitOpen_statement(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitGoto_statement(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitPipe_row_statement(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function createBlocksForAST(ast, workspace) {\n\tconst parse_node = (node) => {\n\t\t\n\t\tconst node_meta = lpe_babel.types.NODE_FIELDS[node.type];\n\t\t\n\t\tlet block = workspace.newBlock(TYPE_PREFIX + node.type);\n\t\tblock.babel_node = node;\n\t\tnode.blockly_block = block;\n\t\t\n\t\tblock.initSvg();\n\t\tblock.render();\n\n\t\tif(typeof node_meta.value !== 'undefined') {\n\t\t\tblock.getField(\"value\").setValue(node.value);\n\t\t} else {\n\t\t\t// Go through the inputs\n\t\t\tfor(const field_name in node_meta) {\n\t\t\t\tconst field_meta = node_meta[field_name];\n\n\t\t\t\t// Check if this is a chaining input\n\t\t\t\tif(!field_meta.validate) {\n\t\t\t\t\tconsole.log(\"Error: field can't be validated:\");\n\t\t\t\t\tconsole.log(field_meta);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif(field_meta.validate.chainOf) {\n\n\t\t\t\t\t// Decide if this is a series of nodes or a limited selection of nodes\n\t\t\t\t\tif(field_meta.validate.chainOf[0].type === 'array') {\n\t\n\t\t\t\t\t\tlet node_list = node[field_name];\n\n\t\t\t\t\t\tif(node_list && node_list.length > 0) {\n\t\t\t\t\t\t\t// Transform list to tree\n\t\t\t\t\t\t\tfor(let i = node_list.length-1; i > 0; i--) {\n\t\t\t\t\t\t\t\tnode_list[i-1].next = node_list[i];\n\t\t\t\t\t\t\t\t//node_list.pop();\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tblockly_tools.setAsFirstStatement(parse_node(node_list[0]), block, field_name);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t} else {\n\t\t\t\t\t\tblock.getField(field_name).setValue(node[field_name]);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t//console.log(field.validate.chainOf)\n\t\t\t\t} else if (field_meta.validate.oneOfNodeTypes) {\n\t\t\t\t if(node[field_name]) {\n\t\t\t\t\t blockly_tools.setAsInput(parse_node(node[field_name]), block, field_name)\n\t\t\t\t }\n\t\t\t\t} else if (field_meta.validate.type && field_meta.validate.type !== 'string') {\n\t\t\t\t\tif(node[field_name]) {\n\t\t\t\t\t blockly_tools.setAsInput(parse_node(node[field_name]), block, field_name)\n\t\t\t\t }\n\t\t\t\t} else {\n\t\t\t\t\tblock.getField(field_name).setValue(node[field_name]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif(node.next) {\n\t\t\tblockly_tools.setAsNext(parse_node(node.next), block)\n\t\t}\n \n\t\treturn block;\n\t}\n\t\n\tif(ast.program) {\n\t return parse_node(ast.program);\n\t} else if(ast instanceof Array) {\n\t let parsedNodes = ast.map(parse_node);\n\t return parsedNodes;\n\t} else {\n\t return parse_node(ast);\n\t}\n\t\n}",
"visitReturn_stmt(ctx) {\r\n console.log(\"visitReturn_stmt\");\r\n if (ctx.testlist() !== null) {\r\n return {\r\n type: \"ReturnStatement\",\r\n returned: this.visit(ctx.testlist()),\r\n };\r\n } else {\r\n return {\r\n type: \"ReturnStatement\",\r\n returned: [],\r\n };\r\n }\r\n }",
"function parse_StatementList(){\n\t\n\n\t\n\n\tvar tempDesc = tokenstreamCOPY[parseCounter][0]; //check desc of token\n\tvar tempType = tokenstreamCOPY[parseCounter][1]; //check type of token\n\n\tif (tempDesc == ' print' || tempType == 'identifier' || tempType == 'type' || tempDesc == ' while' || tempDesc == ' if' || tempDesc == '{' ){ //if next token is a statment\n\t\tdocument.getElementById(\"tree\").value += \"PARSER: parse_StatementList()\" + '\\n';\n\t\tCSTREE.addNode('StatementList', 'branch');\n\t\t\n\t\t\n\t\tparse_Statement(); \n\t\n\t\tparse_StatementList();\n\t\t\n\t\tCSTREE.endChildren();\n\t\n\t\t\n\t\t\n\t}\n\telse{\n\t\t\n\t\t\n\t\t//e production\n\t}\n\n\n\n\n\t\n\t\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the default options (DEPRECATED). | defaultOptions() {
console.error('.defaultOptions() is deprecated, use .DEFAULT_OPTIONS instead.');
return DEFAULT_CONFIG;
} | [
"static GetOptions(options, defaultOptions) {\n let _options = {};\n if (!options) {\n options = {};\n }\n if (!defaultOptions) {\n defaultOptions = LowPolyPathBuilder.GetDefaultOptions(options ? options.version : undefined);\n }\n for (let param in defaultOptions) {\n if (options[param] === undefined) {\n _options[param] = defaultOptions[param];\n }\n else {\n _options[param] = options[param];\n }\n }\n return _options;\n }",
"get options() {\n if (typeof MI === 'undefined') {\n window.MI = { options: {} };\n }\n const { options } = MI;\n return options;\n }",
"static get defaultOptions() {\n const options = super.defaultOptions;\n options.template = \"public/modules/ffg-roller/templates/roller-window.html\";\n options.width = 150;\n options.height = \"auto\";\n return options;\n }",
"static set_default_options(options) {\n $.extend(default_dialog_options, options);\n }",
"get options() {\n return this._options;\n }",
"static get defaultOptions() {\n\t const options = super.defaultOptions;\n\t options.classes = options.classes.concat([\"worldbuilding\", \"actor-sheet\"]);\n\t options.template = \"public/systems/cod/templates/actor-sheet.html\";\n options.width = 600;\n options.height = 600;\n\t return options;\n }",
"function getStorageTableOperationDefaultOption() {\n var option = StorageUtil.getStorageOperationDefaultOption();\n\n // Add table specific options here\n\n return option;\n }",
"function DEFAULTS(){\n defaultArgs = [];\n for (var i = 0; i<arguments.length; i++) {\n defaultArgs.push(arguments[i]);\n }\n}",
"function defaultFastifyOptions() {\n return {\n return503OnClosing: false,\n ignoreTrailingSlash: false,\n caseSensitive: true,\n // use “legacy” header version with prefixed x- for better compatibility with existing enterprises infrastructures\n requestIdHeader: 'x-request-id',\n // set 30 seconds to\n pluginTimeout: 30000,\n // virtually disable the max body size limit\n bodyLimit: Number.MAX_SAFE_INTEGER,\n }\n}",
"function getOptions() {\n var options = {},\n cProp,\n gOption; // update grapher options from component spec & defaults\n\n for (cProp in grapherOptionForComponentSpecProperty) {\n if (grapherOptionForComponentSpecProperty.hasOwnProperty(cProp)) {\n gOption = grapherOptionForComponentSpecProperty[cProp];\n options[gOption] = component[cProp];\n }\n } // These options are specific for Lab and require some more work that just copying\n // values.\n\n\n if (component.syncXAxis) {\n setupAxisSync('x', component.syncXAxis, options);\n }\n\n if (component.syncYAxis) {\n setupAxisSync('y', component.syncYAxis, options);\n }\n\n return options;\n }",
"function getDefaultConfig() {\n\tvar config = {};\n\t\n\tvar configZen = CSScomb.getConfig('zen');\n\t\n\t// Copy only sort-order data:\n\tconfig['sort-order'] = configZen['sort-order'];\n\t\n\t// If sort-order is separated into sections, add an empty section at top:\n\tif (config['sort-order'].length > 1) {\n\t\tconfig['sort-order'].unshift([]);\n\t}\n\t\n\t// Add sort-order info for SCSS, Sass and Less functions into the first section:\n\tconfig['sort-order'][0].unshift('$variable', '$include', '$import');\n\t\n\t// Add configuration that mimics most of the settings from Espresso:\n\tconfig['block-indent'] = process.env.EDITOR_TAB_STRING;\n\tconfig['strip-spaces'] = true;\n\tconfig['always-semicolon'] = true;\n\tconfig['vendor-prefix-align'] = true;\n\tconfig['unitless-zero'] = true;\n\tconfig['leading-zero'] = true;\n\tconfig['quotes'] = 'double';\n\tconfig['color-case'] = 'lower';\n\tconfig['color-shorthand'] = false;\n\tconfig['space-before-colon'] = '';\n\tconfig['space-after-colon'] = ' ';\n\tconfig['space-before-combinator'] = ' ';\n\tconfig['space-after-combinator'] = ' ';\n\tconfig['space-before-opening-brace'] = ' ';\n\tconfig['space-after-opening-brace'] = process.env.EDITOR_LINE_ENDING_STRING;\n\tconfig['space-before-closing-brace'] = process.env.EDITOR_LINE_ENDING_STRING;\n\tconfig['space-before-selector-delimiter'] = '';\n\tconfig['space-after-selector-delimiter'] = process.env.EDITOR_LINE_ENDING_STRING;\n\tconfig['space-between-declarations'] = process.env.EDITOR_LINE_ENDING_STRING;\n\t\n\treturn config;\n}",
"getDefaultAttrs() {\n let defaults = Object.create(null)\n for (let attrName in this.attrs) {\n let attr = this.attrs[attrName]\n if (attr.default === undefined) return null\n defaults[attrName] = attr.default\n }\n return defaults\n }",
"static get defaultParameters () {\n return {\n paginate: true,\n limit: 10,\n offset: 0,\n orderDirection: 'ASC',\n multipleOrderColumns: false\n };\n }",
"static getMarkedOptions () {\n\n\t\treturn {\n\t\t\tgfm: true,\n\t\t\t//highlight: highlight_syntax_code_syntaxhiglighter,\n\t\t\ttables: true,\n\t\t\tbreaks: false,\n\t\t\tpedantic: false,\n\t\t\tsanitize: true,\n\t\t\tsmartLists: true,\n\t\t\tsmartypants: false,\n\t\t\tlangPrefix: 'lang-'\n\t\t};\n\n\t}",
"function MppOptions() {\n throw new Error('This is a static class');\n}",
"function mergeDefaults(options) {\n\toptions = options || {};\n\n // create a new object, merging `options` over the top of defaults\n\treturn Object.assign({}, {\n\t\tcwd: process.cwd(),\n\t\tdryRun: false,\n\t\tfilePaths: null,\n\t\tfs,\n\t\tprune: false,\n\t\ts3: null,\n\t\tskip: true\n\t}, options);\n}",
"loadOptions() {\n browser.storage.local.get(\"options\").then(res => {\n if (Object.getOwnPropertyNames(res).length != 0) {\n this.options = res.options;\n } else {\n this.options = DEFAULT_OPTIONS;\n }\n });\n }",
"function parseDefaultSettings() {\n const {defaultSettings: defaultSettingsInCategories} = require('../data/schema/');\n throw new Error('not implemented yet');\n}",
"function getCommandDefaults(flags) {\n const f = flags;\n Object.entries(f).forEach(([key]) => {\n f[key] = (0, default_flag_args_1.getDefaultValue)(key) || flags[key];\n });\n // this will return a bunch of flags that don't have values\n // and wont know which are required or not\n return f;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add a button to the layer. | button(x, y, content, opts){
let button = new Button(x, y, content, opts);
this.layer.buttons.push(button);
return button;
} | [
"createButton () {\n\n this.button = document.createElement('button')\n\n this.button.title = 'This model has multiple views ...'\n\n this.button.className = 'viewable-selector btn'\n\n this.button.onclick = () => {\n this.showPanel(true)\n }\n\n const span = document.createElement('span')\n span.className = 'fa fa-list-ul'\n this.button.appendChild(span)\n\n const label = document.createElement('label')\n this.button.appendChild(label)\n label.innerHTML = 'Views'\n \n this.viewer.container.appendChild(this.button)\n }",
"function addBaseLayerButton(layer,layerCollection){\n buildToolbar();\n document.querySelector('.baselayer-button-container') === null ? createNode('.toolbar', 'div', ['baselayer-button-container', 'button-container']): false;\n\n let i = layerCollection.array_.filter(layer => layer.values_.isBaseLayer === true).length;\n let layers = [];\n let layerTitle = layer.get('title');\n let layerId = layer.ol_uid;\n createNode('.baselayer-button-container', 'div', ['baselayer-button','tool-button', `baselayer-${layerId}`, layerTitle.toLowerCase().replace(/ /g,'_'),],'',[{'title': 'Klik hier voor de ' + layerTitle + ' achtergrondkaart'}]);\n let layerButton = document.querySelector(`.baselayer-${layerId}`);\n layerButton.addEventListener('click', () => {\n layers = GeoApp.layers.array_.filter(layer => layer.values_.isBaseLayer === true);\n let otherLayers = layers.filter(thisLayer => thisLayer.ol_uid !== layer.ol_uid);\n otherLayers.forEach(otherLayer => {otherLayer.setVisible(false);});\n layer.setVisible(true);\n let buttons = Array.from(document.querySelectorAll('.baselayer-button'));\n let otherButton = buttons.filter(thisButton => thisButton !== layerButton)[0];\n if (layerButton.classList.contains('active') === false) {\n layerButton.classList.add('active');\n otherButton.classList.remove('active');\n }\n });\n if (i === 1) {\n layerButton.classList.add('active');\n layer.setVisible(true);\n }\n}",
"function Button(label, size = ImVec2.ZERO) {\r\n return bind.Button(label, size);\r\n }",
"addButton(char) {\n //Create an input type dynamically.\n let element = document.createElement(\"button\");\n //Assign different attributes to the element.\n element.textContent = char;\n element.setAttribute(\"id\", char);\n element.setAttribute(\"value\", char);\n element.setAttribute(\"type\", \"button\");\n element.setAttribute(\"name\", char);\n element.setAttribute(\"onclick\", \"game.guess(this)\");\n //Append the element in page (in span).\n buttonsDisplay.appendChild(element);\n }",
"function createButton(inrTxt) {\r\n const elem = document.createElement(`button`);\r\n elem.classList.add(`buttons`);\r\n elem.innerText = `${inrTxt}`;\r\n active.buttons.push({\r\n e: elem\r\n });\r\n box.appendChild(elem);\r\n }",
"addButtonWithHandler(text, handler) {\n let button = new Button(text);\n button.on('tap', handler);\n this.addSubview(button);\n this.buttons.push(button);\n return button;\n }",
"function drawButton(btn) {\n // Move text down 1 pixel and lighten background colour on mouse hover\n var textOffset;\n if (btn.state === 1) {\n btn.instances.current.background[3] = 0.8;\n textOffset = 1;\n } else {\n btn.instances.current.background[3] = 1.;\n textOffset = 0;\n }\n // Draw button rectangle\n mgraphics.set_source_rgba(btn.instances.current.background);\n mgraphics.rectangle(btn.rect);\n mgraphics.fill();\n // Draw button text\n mgraphics.select_font_face(MPU.fontFamily.bold);\n mgraphics.set_font_size(MPU.fontSizes.p);\n // Calculate text position\n var Xcoord = MPU.margins.x + (btn.rect[2] / 2) - (mgraphics.text_measure(btn.instances.current.text)[0] / 2);\n var Ycoord = MPU.margins.y + btn.rect[1] + (mgraphics.font_extents()[0] / 2) + textOffset;\n mgraphics.move_to(Xcoord, Ycoord);\n mgraphics.set_source_rgba(btn.instances.current.color);\n mgraphics.text_path(btn.instances.current.text);\n mgraphics.fill();\n}",
"function make_button(text, hover, click) {\n var btn = buttons.append('g').classed('button', true);\n \n var bg = btn.append('ellipse')\n .attr(\"rx\", rx).attr(\"ry\", ry)\n .attr(\"cx\", cx).attr(\"cy\", cy);\n var txt = btn.append('text').text(text)\n .attr(\"text-anchor\", \"middle\")\n .attr(\"x\", cx).attr(\"y\", function () {\n var height = d3.select(this).style(\"height\").split(\"px\")[0];\n return height / 3 + cy;\n });\n \n // Setup Event Handlers\n btn.on(\"mouseover\", function () {\n btn.classed(\"hover\", true);\n txt.text(hover);\n bg.transition().duration(250).attr(\"ry\",\n function () {\n return d3.select(this).attr(\"rx\");\n });\n }).on(\"mouseout\", function () {\n btn.classed(\"hover\", false);\n txt.text(text);\n bg.transition().duration(250).ease('linear').attr(\"ry\", ry);\n }).on(\"click\", click);\n return btn;\n }",
"function addButton(size) {\r\n\r\n}",
"function addButtons() {\n target.css({\n 'border-width': '5px'\n });\n //console.log(\"INSIDE addButtons, thisID: \" + thisId + \" and thisKittenId: \" + thisKittenId);\n // append the delete and edit buttons, with data of metric document id, and kitten document id\n target.append(\"<button type='button' class='btn btn-default btn-xs littleX' data_idKitten=\" + \n thisKittenId + \" data_id=\" + \n thisId + \"><span class='glyphicon glyphicon-remove' aria-hidden='true'></span></button>\");\n target.append(\"<button type='button' class='btn btn-default btn-xs littleE' data_idKitten=\" + \n thisKittenId + \" data_id=\" + \n thisId + \"><span class='glyphicon glyphicon-pencil' aria-hidden='true'></span></button>\");\n // set boolean to true that delete and edit buttons exist\n littleButton = true;\n }",
"function button(div, id, gid, cb, tooltip) {\n if (!divExists(div, 'button')) return null;\n\n var btnDiv = createDiv(div, 'button', id),\n cbFnc = fs.isF(cb) || noop;\n\n is.loadIcon(btnDiv, gid, btnSize, true);\n if (tooltip) { tts.addTooltip(btnDiv, tooltip); }\n\n btnDiv.on('click', cbFnc);\n\n return {\n id: id,\n width: buttonWidth,\n };\n }",
"function addUplinkButton() {\r\n\tvar upBtn = document.createElement('button');\r\n\tupBtn.setAttribute('type', 'button');\r\n\tupBtn.setAttribute('class', 'btn btn-default btn-sm');\r\n\r\n\tvar upBtnIcn = document.createElement('i');\r\n\tupBtnIcn.setAttribute('class', 'fa fa-level-up');\r\n\tupBtnIcn.setAttribute('aria-hidden', 'true');\r\n\r\n\tupBtn.appendChild(upBtnIcn);\r\n\r\n\tdocument.getElementById('kapitel-btn').innerHTML = \"\";\r\n\tdocument.getElementById('kapitel-btn').appendChild(upBtn);\r\n}",
"function addButton(Button) {\n Button.on('push', function(e) {\n var newDirection = direction;\n\n switch (Button.pin) {\n case '04': newDirection = -1; break;\n case '02': newDirection = 1; break;\n }\n \n if (newDirection != direction) {\n startSequence(newDirection, curInterval); \n } \n });\n}",
"add_click(func) {\n this.add_event(\"click\", func);\n }",
"function makeOctopusButton() {\n\n // Create the clickable object\n octopusButton = new Clickable();\n \n octopusButton.text = \"\";\n\n octopusButton.image = images[21]; \n\n // makes the image transparent\n octopusButton.color = \"#00000000\";\n octopusButton.strokeWeight = 0; \n\n // set width + height to image size\n octopusButton.width = 290; \n octopusButton.height = 160;\n\n // places the button \n octopusButton.locate( width * (13/16) - octopusButton.width * (13/16), height * (1/2) - octopusButton.height * (1/2));\n\n // Clickable callback functions, defined below\n octopusButton.onPress = octopusButtonPressed;\n octopusButton.onHover = beginButtonHover;\n octopusButton.onOutside = animalButtonOnOutside;\n}",
"function appendButton(ribbon) {\n var customTab, customGroup, customLayout, customSection, customControlProp,\n customButton, controlComponent, btnLocation;\n\n customTab = ribbon.getChildByTitle(\"Files\");\n\n customGroup = new CUI.Group(ribbon, 'Custom.Tab.Group', 'Archive Link', 'Group Description', 'Custom.Group.Command', null);\n customTab.addChild(customGroup);\n\n customLayout = new CUI.Layout(ribbon, 'Custom.Layout', 'The Layout');\n customGroup.addChild(customLayout);\n\n customSection = new CUI.Section(ribbon, 'Custom.Section', 2, 'Top');\n customLayout.addChild(customSection);\n\n customControlProp = new CUI.ControlProperties();\n customControlProp.Command = 'Custom.Button.Command';\n customControlProp.Id = 'Custom.ControlProperties';\n customControlProp.TemplateAlias = 'o1';\n customControlProp.ToolTipDescription = 'Move selected page to pages archive library';\n customControlProp.Image32by32 = '_layouts/15/images/placeholder32x32.png';\n customControlProp.ToolTipTitle = 'Send to pages archive';\n customControlProp.LabelText = 'Archive Page';\n customButton = new CUI.Controls.Button(ribbon, 'Custom.Button', customControlProp);\n controlComponent = customButton.createComponentForDisplayMode('Large');\n\n btnLocation = customSection.getRow(1);\n btnLocation.addChild(controlComponent);\n customGroup.selectLayout('The Layout');\n\n SelectRibbonTab('Ribbon.Read', true);\n }",
"createMoveButton(index) {\n let scope = this;\n let modifyButtonElement = document.createElement('button');\n modifyButtonElement.className = cssConstants.ICON + ' ' + cssConstants.EDITOR_FEATURE_MODIFY;\n modifyButtonElement.title = langConstants.EDITOR_FEATURE_MODIFY;\n modifyButtonElement.setAttribute('feat_id', index);\n jQuery(modifyButtonElement).click(function(event) {\n scope.modifyFeatureFunction(event);\n });\n return modifyButtonElement;\n }",
"function createButton(label, func)\n{\n\tvar button = document.createElement(\"button\");\n\tbutton.textContent = label;\n\tbutton.addEventListener(\"click\", func);\n\tdocument.body.appendChild(button);\n}",
"function _createButton(label, name, action, disabled) {\n var retorno = {};\n retorno.buttonAction = action;\n retorno.disabled = disabled;\n retorno.label = label;\n retorno.name = name;\n retorno.type = \"button\";\n return retorno;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
WRITE A FUNCTION THAT TAKES TWO ARGUMENTS, ARRAY AND NUMBER, IT SHOULD COUNT OCCURRENCES OF THAT NUMBER IN PROVIDED ARRAY AND RETURN IT FOR | function countNumber(arrayOfNumbers,number){
let result = 0;
for(let i = 0; i < arrayOfNumbers.length; i++){
if(arrayOfNumbers[i]===number){
result++;
}
}
return result;
} | [
"function countNum (array) {\n\tvar uniqueArr = [];\n\tfor (i=0; i<=uniqueNumbers.length - 1; i++){\n\t\tvar count = array.filter (function (n) {\n\t\t\treturn n === uniqueNumbers [i];\n\t\t})\n\t\tuniqueArr.push (count.length);\n\t}\n\treturn uniqueArr;\n}",
"function numOfAppear(a, array) {\n var i;\n var n = 0;\n for (i = 0; i < array.length; i++) {\n if (array[i] == a) {\n n++;\n }\n }\n return n;\n}",
"function calculatesNumberOFIntegers (array) {\n\nlet result = 0;\n for (let i = 0; i < array.length; i++) {\n\n if(isFinite(array[i]) && typeof array[i] === \"number\" && parseInt(array[i]) === array[i]) {\n\n result++;\n }\n }\n return result;\n}",
"function arrayOfNumbers (array) { //function that takes in an array\n var array = [2,4,6,8,10]; //local array inside the function \n \n return array[3]; //return the 3 (index) of the array (0,1,2,3)\n }",
"function countNormal(arr) {\n // Your code here\n return 0;\n}",
"function countOf(array, element) {\n var x = 0;\n for (var i = 0; i < array.length; i++) {\n if (array[i] == element) {\n x++;\n }\n }\n return x;\n}",
"function sumOfNumbers(arr) {\n function sum(total, num) {\n return total + num;\n }\n return arr.reduce(sum);\n}",
"function numarray(n) {\n resultArr = [n];\n for (i = 0; i < n; i++) {\n resultArr[i] = i ;\n }\n console.log(resultArr);\n}",
"function getPortNumber(portsArr,cnt){\n\tif(ForNumberExist(portsArr,cnt)){\n\t\tcnt++;\n\t\tcnt = getPortNumber(portsArr,cnt);\n\t}\n\treturn cnt;\n}",
"function getBoardNumbers(numbers){\n\n let outerArray = [];\n let count = 0;\n\n for (let i=0; i<numbers; i++){\n let innerArray= []\n \n for (let j=0; j<numbers; j++){\n count++\n innerArray.push(count);\n}\nouterArray.push(innerArray);\n }\n return outerArray\n }",
"function arrayOfNumbers(number) {\n var newArray = [];\n for (i = 1; i <= number; i++) {\n newArray.push(i);\n }\n return newArray;\n}",
"function frequency(arr) {\n var retArr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];\n for (let elem of arr) {\n switch (elem) {\n case 0:\n retArr[0]++;\n break;\n case 1:\n retArr[1]++;\n break;\n case 2:\n retArr[2]++;\n break;\n case 3:\n retArr[3]++;\n break;\n case 4:\n retArr[4]++;\n break;\n case 5:\n retArr[5]++;\n break;\n case 6:\n retArr[6]++;\n break;\n case 7:\n retArr[7]++;\n break;\n case 8:\n retArr[8]++;\n break;\n case 9:\n retArr[9]++;\n break;\n case 10:\n retArr[10]++;\n break;\n }\n }\n return retArr;\n}",
"function w3_ext_param_array_match_num(arr, n, func)\n{\n var found = false;\n arr.forEach(function(a_el, i) {\n var a_num = parseFloat(a_el);\n //console.log('w3_ext_param_array_match_num CONSIDER '+ i +' '+ a_num +' '+ n);\n if (!found && a_num == n) {\n //console.log('w3_ext_param_array_match_num MATCH '+ i);\n if (func) func(i, n);\n found = true;\n }\n });\n return found;\n}",
"function countStudents(arrayOfStudents) {\n const counts = {\n Gryffindor: 0,\n Slytherin: 0,\n Hufflepuff: 0,\n Ravenclaw: 0\n };\n arrayOfStudents.forEach(student => {\n counts[student.house]++;\n document.querySelector(\".gryffindorenlisted span\").innerHTML =\n counts.Gryffindor;\n document.querySelector(\".hufflepuffenlisted span\").innerHTML =\n counts.Hufflepuff;\n document.querySelector(\".slytherinenlisted span\").innerHTML =\n counts.Slytherin;\n document.querySelector(\".ravenclawenlisted span\").innerHTML =\n counts.Ravenclaw;\n document.querySelector(\".totalnumber span\").innerHTML =\n arrayOfStudents.length;\n /*counts.Gryffindor +\n counts.Slytherin +\n counts.Hufflepuff +\n counts.Ravenclaw;*/\n document.querySelector(\".numberofexpelled span\").innerHTML =\n 35 - arrayOfStudents.length;\n /*(counts.Gryffindor +\n counts.Slytherin +\n counts.Hufflepuff +\n counts.Ravenclaw);*/\n });\n //return countStudents();\n}",
"function how_many_even(arr){\n count = 0;\n for(i = 0; i < arr.length; i++){\n if (arr[i] % 2 == 0){\n count ++;\n }\n }\n return count;\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 countFiveInArray({ array }) {\n array = arrayParser(array);\n return array.filter(item => item == \"5\").length;\n}",
"static compute_page_counts(N, p) {\n let a = Math.ceil(N/p);\n let b = Math.ceil(N/a);\n let c = b - 1;\n let d = N - a * c;\n let e = a - d;\n\n return [a, b, c, d, e];\n }",
"function total_sub_instruction_count_aux(id_of_top_ins, aic_array){\n let result = 0 //this.added_items_count[id_of_top_ins]\n let tally = 1 //this.added_items_count[id_of_top_ins]\n for(let i = id_of_top_ins; true ; i++){\n let aic_for_i = aic_array[i] //this.added_items_count[i]\n if (aic_for_i === undefined) {\n shouldnt(\"total_sub_instruction_count_aux got undefined from aic_array: \" + aic_array)\n }\n result += aic_for_i //often this is adding 0\n tally += aic_for_i - 1\n if (tally == 0) { break; }\n else if (tally < 0) { shouldnt(\"in total_sub_instruction_count got a negative tally\") }\n }\n return result\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a function that executes its arguments (which should be cancelables) in sequence, so that each of them passes its return values to the next. Execution is aborted if one of the functions returns an error; in that case the last function in the sequence is called with the error. See util/cancelize.js for an explanation of what cancelables are. | function chain() {
// The list of functions to chain together.
var argList = Array.prototype.slice.call(arguments, 0);
return function chained() {
// List of remaining functions to be executed.
// Make a copy of the original list so we can mutate the former while
// preserving the latter intact for future invocations of the chain.
var fnList = argList.slice(0);
// Currently executing function.
var fn = null;
// Cancel method for the currently executing function.
var cfn = null;
// Arguments for the first function.
var args = arguments.length ? Array.prototype.slice.call(arguments, 0, arguments.length - 1) : [];
// Callback for the chain.
var done = arguments.length ? arguments[arguments.length - 1] : noop;
// Execute the next function in the chain.
// Receives the error and return values from the previous function.
function exec() {
// Extract error from arguments.
var err = arguments[0];
// Abort chain on error.
if (err) {
fn = cfn = null;
done.apply(null, arguments);
return;
}
// Terminate if there are no functions left in the chain.
if (!fnList.length) {
fn = cfn = null;
done.apply(null, arguments);
return;
}
// Advance to the next function in the chain.
fn = fnList.shift();
var _fn = fn;
// Extract arguments to pass into the next function.
var ret = Array.prototype.slice.call(arguments, 1);
// Call next function with previous return value and call back exec.
ret.push(exec);
var _cfn = fn.apply(null, ret); // fn(null, ret..., exec)
// Detect when fn has completed synchronously and do not clobber the
// internal state in that case. You're not expected to understand this.
if (_fn !== fn) {
return;
}
// Remember the cancel method for the currently executing function.
// Detect chaining on non-cancellable function.
if (typeof _cfn !== 'function') {
throw new Error('chain: chaining on non-cancellable function');
} else {
cfn = _cfn;
}
}
// Cancel chain execution.
function cancel() {
if (cfn) {
cfn.apply(null, arguments);
}
}
// Start chain execution.
// We call exec as if linking from a previous function in the chain,
// except that the error is always null. As a consequence, chaining on an
// empty list yields the identity function.
args.unshift(null);
exec.apply(null, args); // exec(null, args...)
return cancel;
};
} | [
"function run() {\n var index = -1;\n var input = slice$1.call(arguments, 0, -1);\n var done = arguments[arguments.length - 1];\n\n if (typeof done !== 'function') {\n throw new Error('Expected function as last argument, not ' + done)\n }\n\n next.apply(null, [null].concat(input));\n\n // Run the next `fn`, if any.\n function next(err) {\n var fn = fns[++index];\n var params = slice$1.call(arguments, 0);\n var values = params.slice(1);\n var length = input.length;\n var pos = -1;\n\n if (err) {\n done(err);\n return\n }\n\n // Copy non-nully input into values.\n while (++pos < length) {\n if (values[pos] === null || values[pos] === undefined) {\n values[pos] = input[pos];\n }\n }\n\n input = values;\n\n // Next or done.\n if (fn) {\n wrap_1(fn, next).apply(null, input);\n } else {\n done.apply(null, [null].concat(input));\n }\n }\n }",
"function get_args(arg_funcs, env, succeed, fail) {\n return is_null(arg_funcs)\n ? succeed(null, fail)\n : head(arg_funcs)(env,\n // success continuation for this arg_func\n (arg, fail2) => {\n get_args(tail(arg_funcs),\n env,\n (args, fail3) => {\n succeed(pair(arg, args), fail3);\n },\n fail2);\n },\n fail);\n}",
"function sequence(callbacks) {\n\t\t\treturn callbacks.reduce((seq, fn) => seq = seq.then(fn), Promise.resolve()); // eslint-disable-line no-param-reassign\n\t\t}",
"*execute() { yield* Array.from(arguments); }",
"function seq(){var args=arguments\n return function(s,p){var i,l,cp\n cp=s.checkpoint()\n for(i=0,l=args.length;i<l;i++)\n if(!args[i](s,p)){s.restore(cp);return false}\n return true}}",
"function combineOperations(startVal, arrOfFuncs) {\n let output;\n for (let i = 0; i < arrOfFuncs.length; i += 1) {\n if (output === undefined) {\n output = arrOfFuncs[i](startVal);\n } else {\n output = arrOfFuncs[i](output);\n }\n }\n return output;\n}",
"function compose(...funcs) {\n return funcs.reduce((a, b) => {\n // console.log(a.toString(), 'aaaaa');\n // console.log(b.toString());\n // console.log('===================', a, b)\n return (...args) => a(b(...args));\n })\n}",
"function OXN_ALift_Apply(async_f, xc, env, args) {\n this.xc = xc;\n this.xc.current = this;\n \n var pars = [bind(this.cont, this)];\n pars = pars.concat(args);\n this.abort_f = async_f.apply(env, pars);\n}",
"function Sequence$cancel(){\n\t cancel();\n\t action && action.cancel();\n\t while(it = nextHot()) it.cancel();\n\t }",
"function cpe (C, A, E, a, b) {\n if (safe()) {\n if (arguments.length == 5) {\n cp(() => e(() => e(C, C, b), C, a), A, E, a, b)\n } else if (arguments.length == 4) {\n cpe(() => cpe(C, A, E, a), C, A, E, a)\n }\n }\n}",
"function foo () {\n return fargs(arguments);\n }",
"function analyze_sequence(stmts) {\n function sequentially(fun1, fun2) {\n return (env, succeed, fail) => {\n fun1(env,\n (fun1_val, fail2) => {\n if (is_return_value(fun1_val)) {\n succeed(fun1_val, fail2);\n } else {\n fun2(env, succeed, fail2);\n }\n },\n fail);\n };\n }\n function loop(first_fun, rest_funs) {\n return is_null(rest_funs)\n ? first_fun\n : loop(sequentially(first_fun,\n head(rest_funs)),\n tail(rest_funs));\n }\n const funs = map(analyze, stmts);\n return is_null(funs)\n ? (env, succeed, fail) => undefined\n : loop(head(funs), tail(funs));\n\n}",
"function next(arg, isErr) {\n // Preventive measure. If we end up here, then there is really something wrong\n if (!mainTask.isRunning) {\n throw new Error('Trying to resume an already finished generator');\n }\n\n try {\n var result = void 0;\n if (isErr) {\n result = iterator.throw(arg);\n } else if (arg === TASK_CANCEL) {\n /**\n getting TASK_CANCEL automatically cancels the main task\n We can get this value here\n - By cancelling the parent task manually\n - By joining a Cancelled task\n **/\n mainTask.isCancelled = true;\n /**\n Cancels the current effect; this will propagate the cancellation down to any called tasks\n **/\n next.cancel();\n /**\n If this Generator has a `return` method then invokes it\n This will jump to the finally block\n **/\n result = _utils__WEBPACK_IMPORTED_MODULE_0__[/* is */ \"n\"].func(iterator.return) ? iterator.return(TASK_CANCEL) : { done: true, value: TASK_CANCEL };\n } else if (arg === CHANNEL_END) {\n // We get CHANNEL_END by taking from a channel that ended using `take` (and not `takem` used to trap End of channels)\n result = _utils__WEBPACK_IMPORTED_MODULE_0__[/* is */ \"n\"].func(iterator.return) ? iterator.return() : { done: true };\n } else {\n result = iterator.next(arg);\n }\n\n if (!result.done) {\n runEffect(result.value, parentEffectId, '', next);\n } else {\n /**\n This Generator has ended, terminate the main task and notify the fork queue\n **/\n mainTask.isMainRunning = false;\n mainTask.cont && mainTask.cont(result.value);\n }\n } catch (error) {\n if (mainTask.isCancelled) {\n logError(error);\n }\n mainTask.isMainRunning = false;\n mainTask.cont(error, true);\n }\n }",
"static conduct(a, b, callback, on) {\r\n callback(a, b)\r\n\r\n }",
"function compose(...fns) {\n return fns.reduce(function(pre, curr) {\n return function(...args) {\n return pre(curr(...args))\n }\n })\n}",
"convertLastCallToReturn(...valuesToReturn) {\n this.methodReturnSetups.push({\n arguments: this.lastCallArgs,\n returnValues: valuesToReturn,\n isAsync: false,\n nextIndex: 0\n });\n this.calls.pop();\n if (this.calls.length > 0) {\n this.lastCallArgs = this.calls[this.calls.length - 1];\n }\n }",
"function chainDeferreds(deferreds){\n\t/*return deferreds.reduce(function(previous, current){\n\t return previous.then(current);\n\t }, resolvedPromise());*/\n\t\n\tvar promise = deferreds[0];\n\tfor(var i = 1; i < deferreds.length; i++){\n\t\tpromise = promise.then(deferreds[i]);\n\t}\n\t\n\treturn deferreds[deferreds.length-1];\n}",
"function combineOperations(startVal,arrOfFuncs){\n\n //////////solution 1\n // return arrOfFuncs.reduce((acc,func)=> {\n // return func(acc)\n // },startVal)\n\n ///////////solution 2\n // let output = startVal\n // arrOfFuncs.forEach(element=>{\n // output = element(output)\n // })\n // return output\n}",
"function unsafe_cancel_exn() /* () -> exception */ {\n return exception(\"computation is canceled\", Cancel);\n}",
"convertLastCallToReturnAsync(...valuesToReturn) {\n this.methodReturnSetups.push({\n arguments: this.lastCallArgs,\n returnValues: valuesToReturn,\n isAsync: true,\n nextIndex: 0\n });\n this.calls.pop();\n if (this.calls.length > 0) {\n this.lastCallArgs = this.calls[this.calls.length - 1];\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Encode the full glTF file as a binary GLB file Returns an ArrayBuffer that represents the complete GLB image that can be saved to file Encode the full GLB buffer with header etc glbfileformatspecification | encodeAsGLB(options = {}) {
// TODO - avoid double array buffer creation
this._packBinaryChunk();
if (options.magic) {
console.warn('Custom glTF magic number no longer supported'); // eslint-disable-line
}
const glb = {
version: 2,
json: this.json,
binary: this.arrayBuffer
};
// Calculate length and allocate buffer
const byteLength = encodeGLBSync(glb, null, 0, options);
const glbArrayBuffer = new ArrayBuffer(byteLength);
// Encode into buffer
const dataView = new DataView(glbArrayBuffer);
encodeGLBSync(glb, dataView, 0, options);
return glbArrayBuffer;
} | [
"imageToBytes (img, flipY = false, imgFormat = 'RGBA') {\n // Create the gl context using the image width and height\n const {width, height} = img\n const gl = this.createCtx(width, height, 'webgl', {\n premultipliedAlpha: false\n })\n const fmt = gl[imgFormat]\n\n // Create and initialize the texture.\n const texture = gl.createTexture()\n gl.bindTexture(gl.TEXTURE_2D, texture)\n if (flipY) // Mainly used for pictures rather than data\n gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true)\n // Insure [no color profile applied](https://goo.gl/BzBVJ9):\n gl.pixelStorei(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE)\n // Insure no [alpha premultiply](http://goo.gl/mejNCK).\n // False is the default, but lets make sure!\n gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false)\n\n // gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img)\n gl.texImage2D(gl.TEXTURE_2D, 0, fmt, fmt, gl.UNSIGNED_BYTE, img)\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST)\n\n // Create the framebuffer used for the texture\n const framebuffer = gl.createFramebuffer()\n gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer)\n gl.framebufferTexture2D(\n gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0)\n\n // See if it all worked. Apparently not async.\n const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER)\n if (status !== gl.FRAMEBUFFER_COMPLETE)\n this.error(`imageToBytes: status not FRAMEBUFFER_COMPLETE: ${status}`)\n\n // If all OK, create the pixels buffer and read data.\n const pixSize = imgFormat === 'RGB' ? 3 : 4\n const pixels = new Uint8Array(pixSize * width * height)\n // gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, pixels)\n gl.readPixels(0, 0, width, height, fmt, gl.UNSIGNED_BYTE, pixels)\n\n // Unbind the framebuffer and return pixels\n gl.bindFramebuffer(gl.FRAMEBUFFER, null)\n return pixels\n }",
"downloadModelGLB() {\n\t\tthis.emitWarningMessage(\"Preparing GLTF file...\", 60000);\n\t\tthis.props.loadingToggle(true);\n\t\twindow.LITHO3D.downloadGLTF(1, 1, 1, false, true).then(() => {\n\t\t\tthis.props.loadingToggle(false);\n\t\t\tthis.emitWarningMessage(\"File is ready for download.\", 500);\n\t\t})\n\t\t\t.catch(err => {\n\t\t\t\tthis.props.loadingToggle(false);\n\t\t\t\tthis.emitWarningMessage(err.message);\n\t\t\t});\n\t}",
"buildFile() {\n\t\tvar build = [];\n\n\t\t// Data consists of chunks which consists of data\n\t\tthis.data.forEach((d) => build = build.concat(d.type, d.size, d.data));\n\n\t\treturn new Uint8Array(build);\n\t}",
"function GLTFData() {\n this.glTFFiles = {};\n }",
"function loadGLB(data) {\n console.log(data);\n let fileURL = data.assetUrl;\n let position = data.position;\n let rotation = data.rotation;\n let scale = data.scale;\n // ref to the mesh object\n let mesh;\n loader.load(\n // GLTF/GLB mesh URL\n fileURL,\n // callback when mesh is loaded\n function (glb) {\n mesh = glb.scene;\n mesh.position.set(position.x, position.y, position.z);\n mesh.rotation.set(rotation.x, rotation.y, rotation.z);\n mesh.scale.set(scale.x, scale.y, scale.z);\n scene.add(mesh);\n // console.log(mesh);\n // addPhysics(mesh, 'convex', 'static');\n addTriangleMesh(mesh);\n }\n )\n}",
"bufferData() {\n const gl = this._gl,\n bufferType = this._bufferType,\n drawType = this._drawType,\n data = this._data;\n gl.bufferData(bufferType, data, drawType);\n }",
"addBufferView(buffer) {\n const byteLength = buffer.byteLength || buffer.length;\n\n // Add a bufferView indicating start and length of this binary sub-chunk\n this.json.bufferViews.push({\n buffer: 0,\n // Write offset from the start of the binary body\n byteOffset: this.byteLength,\n byteLength\n });\n\n // We've now written the contents to the body, so update the total length\n // Every sub-chunk needs to be 4-byte aligned\n this.byteLength += padTo4Bytes(byteLength);\n\n // Add this buffer to the list of buffers to be written to the body.\n this.sourceBuffers.push(buffer);\n\n // Return the index to the just created bufferView\n return this.json.bufferViews.length - 1;\n }",
"function createDataTexture(gl, floatArray) {\n var width = floatArray.length / 4, // R,G,B,A\n height = 1,\n texture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, texture);\n gl.texImage2D(gl.TEXTURE_2D,\n 0, gl.RGBA, width, height, 0, gl.RGBA, gl.FLOAT, floatArray);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n return texture;\n }",
"base64() {\n\t\tif (typeof btoa === 'function') return btoa(String.fromCharCode.apply(null, this.buildFile()));\n\t\treturn new Buffer(this.buildFile()).toString('base64');\n\t}",
"function makeBuffer(data) {\n\tvar buff = new Buffer(0), chunk;\n\tvar i = 0, j;\n\tfor(; i < data.length; ++i) {\n\t\tswitch (data[i].type) {\n\t\t\tcase type.short:\n\t\t\t\tchunk = new Buffer(2);\n\t\t\t\tchunk.writeInt16BE(data[i].value, 0);\n\t\t\t\tbreak;\n\n\t\t\tcase type.byte:\n\t\t\t\tchunk = new Buffer(1);\n\t\t\t\tchunk.writeInt8(data[i].value, 0);\n\t\t\t\tbreak;\n\n\t\t\tcase type.string:\n\t\t\t\tchunk = new Buffer(2 + (data[i].value.length * 2));\n\t\t\t\tchunk.fill(0);\n\n\t\t\t\t// Write the size (-2 because size is included in chunk.length)\n\t\t\t\tchunk.writeInt16BE(chunk.length - 2, 0);\n\n\t\t\t\t// Write the string character at a time because uft8 only encodes one byte per character\n\t\t\t\tvar j = 0;\n\t\t\t\tfor (; j < data[i].value.length; ++j) {\n\t\t\t\t\tchunk.writeInt16BE(data[i].value.charCodeAt(j), 2 + (j * 2));\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tconsole.log('Unrecognized type: \"' + data[i].type + '\"');\n\t\t\t\treturn buff;\n\t\t}\n\n\t\tbuff = Buffer.concat([buff, chunk]);\n\t}\n\n\treturn buff;\n}",
"_setupFramebuffers(opts) {\n const {\n textures,\n framebuffers,\n maxMinFramebuffers,\n minFramebuffers,\n maxFramebuffers,\n meanTextures,\n equations\n } = this.state;\n const {\n weights\n } = opts;\n const {\n numCol,\n numRow\n } = opts;\n const framebufferSize = {\n width: numCol,\n height: numRow\n };\n\n for (const id in weights) {\n const {\n needMin,\n needMax,\n combineMaxMin,\n operation\n } = weights[id];\n textures[id] = weights[id].aggregationTexture || textures[id] || Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_11__[\"getFloatTexture\"])(this.gl, {\n id: `${id}-texture`,\n width: numCol,\n height: numRow\n });\n textures[id].resize(framebufferSize);\n let texture = textures[id];\n\n if (operation === _aggregation_operation_utils__WEBPACK_IMPORTED_MODULE_5__[\"AGGREGATION_OPERATION\"].MEAN) {\n // For MEAN, we first aggregatet into a temp texture\n meanTextures[id] = meanTextures[id] || Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_11__[\"getFloatTexture\"])(this.gl, {\n id: `${id}-mean-texture`,\n width: numCol,\n height: numRow\n });\n meanTextures[id].resize(framebufferSize);\n texture = meanTextures[id];\n }\n\n if (framebuffers[id]) {\n framebuffers[id].attach({\n [_luma_gl_constants__WEBPACK_IMPORTED_MODULE_0__[\"default\"].COLOR_ATTACHMENT0]: texture\n });\n } else {\n framebuffers[id] = Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_11__[\"getFramebuffer\"])(this.gl, {\n id: `${id}-fb`,\n width: numCol,\n height: numRow,\n texture\n });\n }\n\n framebuffers[id].resize(framebufferSize);\n equations[id] = _gpu_grid_aggregator_constants__WEBPACK_IMPORTED_MODULE_4__[\"EQUATION_MAP\"][operation] || _gpu_grid_aggregator_constants__WEBPACK_IMPORTED_MODULE_4__[\"EQUATION_MAP\"].SUM; // For min/max framebuffers will use default size 1X1\n\n if (needMin || needMax) {\n if (needMin && needMax && combineMaxMin) {\n if (!maxMinFramebuffers[id]) {\n texture = weights[id].maxMinTexture || this._getMinMaxTexture(`${id}-maxMinTexture`);\n maxMinFramebuffers[id] = Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_11__[\"getFramebuffer\"])(this.gl, {\n id: `${id}-maxMinFb`,\n texture\n });\n }\n } else {\n if (needMin) {\n if (!minFramebuffers[id]) {\n texture = weights[id].minTexture || this._getMinMaxTexture(`${id}-minTexture`);\n minFramebuffers[id] = Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_11__[\"getFramebuffer\"])(this.gl, {\n id: `${id}-minFb`,\n texture\n });\n }\n }\n\n if (needMax) {\n if (!maxFramebuffers[id]) {\n texture = weights[id].maxTexture || this._getMinMaxTexture(`${id}-maxTexture`);\n maxFramebuffers[id] = Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_11__[\"getFramebuffer\"])(this.gl, {\n id: `${id}-maxFb`,\n texture\n });\n }\n }\n }\n }\n }\n }",
"_setupFramebuffers(opts) {\n const {\n textures,\n framebuffers,\n maxMinFramebuffers,\n minFramebuffers,\n maxFramebuffers,\n meanTextures,\n equations\n } = this.state;\n const {weights} = opts;\n const {numCol, numRow} = opts;\n const framebufferSize = {width: numCol, height: numRow};\n for (const id in weights) {\n const {needMin, needMax, combineMaxMin, operation} = weights[id];\n textures[id] =\n weights[id].aggregationTexture ||\n textures[id] ||\n Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_9__[\"getFloatTexture\"])(this.gl, {id: `${id}-texture`, width: numCol, height: numRow});\n textures[id].resize(framebufferSize);\n let texture = textures[id];\n if (operation === _aggregation_operation_utils__WEBPACK_IMPORTED_MODULE_3__[\"AGGREGATION_OPERATION\"].MEAN) {\n // For MEAN, we first aggregatet into a temp texture\n meanTextures[id] =\n meanTextures[id] ||\n Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_9__[\"getFloatTexture\"])(this.gl, {id: `${id}-mean-texture`, width: numCol, height: numRow});\n meanTextures[id].resize(framebufferSize);\n texture = meanTextures[id];\n }\n if (framebuffers[id]) {\n framebuffers[id].attach({[_luma_gl_constants__WEBPACK_IMPORTED_MODULE_0___default.a.COLOR_ATTACHMENT0]: texture});\n } else {\n framebuffers[id] = Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_9__[\"getFramebuffer\"])(this.gl, {\n id: `${id}-fb`,\n width: numCol,\n height: numRow,\n texture\n });\n }\n framebuffers[id].resize(framebufferSize);\n equations[id] = _gpu_grid_aggregator_constants__WEBPACK_IMPORTED_MODULE_2__[\"EQUATION_MAP\"][operation] || _gpu_grid_aggregator_constants__WEBPACK_IMPORTED_MODULE_2__[\"EQUATION_MAP\"].SUM;\n // For min/max framebuffers will use default size 1X1\n if (needMin || needMax) {\n if (needMin && needMax && combineMaxMin) {\n if (!maxMinFramebuffers[id]) {\n texture = weights[id].maxMinTexture || this._getMinMaxTexture(`${id}-maxMinTexture`);\n maxMinFramebuffers[id] = Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_9__[\"getFramebuffer\"])(this.gl, {id: `${id}-maxMinFb`, texture});\n }\n } else {\n if (needMin) {\n if (!minFramebuffers[id]) {\n texture = weights[id].minTexture || this._getMinMaxTexture(`${id}-minTexture`);\n minFramebuffers[id] = Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_9__[\"getFramebuffer\"])(this.gl, {\n id: `${id}-minFb`,\n texture\n });\n }\n }\n if (needMax) {\n if (!maxFramebuffers[id]) {\n texture = weights[id].maxTexture || this._getMinMaxTexture(`${id}-maxTexture`);\n maxFramebuffers[id] = Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_9__[\"getFramebuffer\"])(this.gl, {\n id: `${id}-maxFb`,\n texture\n });\n }\n }\n }\n }\n }\n }",
"bufferData(gl, funcName, args) {\n const [target, src, /* usage */, srcOffset = 0, length = undefined] = args;\n let obj;\n switch (target) {\n case ELEMENT_ARRAY_BUFFER:\n {\n const info = webglObjectToMemory.get(sharedState.currentVertexArray);\n obj = info.elementArrayBuffer;\n }\n break;\n default:\n obj = bindings.get(target);\n break;\n }\n if (!obj) {\n throw new Error(`no buffer bound to ${target}`);\n }\n let newSize = 0;\n if (length !== undefined) {\n newSize = length;\n } else if (isBufferSource(src)) {\n newSize = src.byteLength;\n } else if (isNumber(src)) {\n newSize = src;\n } else {\n throw new Error(`unsupported bufferData src type ${src}`);\n }\n\n const info = webglObjectToMemory.get(obj);\n if (!info) {\n throw new Error(`unknown buffer ${obj}`);\n }\n\n memory.buffer -= info.size;\n info.size = newSize;\n memory.buffer += newSize;\n }",
"function RenderFrameContext( o )\r\n{\r\n\tthis.width = 0; //0 means the same size as the viewport, negative numbers mean reducing the texture in half N times\r\n\tthis.height = 0; //0 means the same size as the viewport\r\n\tthis.precision = RenderFrameContext.DEFAULT_PRECISION; //LOW_PRECISION uses a byte, MEDIUM uses a half_float, HIGH uses a float, or directly the texture type (p.e gl.UNSIGNED_SHORT_4_4_4_4 )\r\n\tthis.filter_texture = true; //magFilter: in case the texture is shown, do you want to see it pixelated?\r\n\tthis.format = GL.RGB; //how many color channels, or directly the texture internalformat \r\n\tthis.use_depth_texture = true; //store the depth in a texture\r\n\tthis.use_stencil_buffer = false; //add an stencil buffer (cannot be read as a texture in webgl)\r\n\tthis.num_extra_textures = 0; //number of extra textures in case we want to render to several buffers\r\n\tthis.name = null; //if a name is provided all the textures will be stored in the ONE.ResourcesManager\r\n\r\n\tthis.generate_mipmaps = false; //try to generate mipmaps if possible (only when the texture is power of two)\r\n\tthis.adjust_aspect = false; //when the size doesnt match the canvas size it could look distorted, settings this to true will fix the problem\r\n\tthis.clone_after_unbind = false; //clones the textures after unbinding it. Used when the texture will be in the 3D scene\r\n\r\n\tthis._fbo = null;\r\n\tthis._color_texture = null;\r\n\tthis._depth_texture = null;\r\n\tthis._textures = []; //all color textures (the first will be _color_texture)\r\n\tthis._cloned_textures = null; //in case we set the clone_after_unbind to true\r\n\tthis._cloned_depth_texture = null;\r\n\r\n\tthis._version = 1; //to detect changes\r\n\tthis._minFilter = gl.NEAREST;\r\n\r\n\tif(o)\r\n\t\tthis.configure(o);\r\n}",
"function convertGeometryToBufferGeometry( geometry ) {\n\n return new BufferGeometry().fromGeometry( geometry );\n\n}",
"createTexCoordBuffer () {\n\t\tif (this.texCoordArray === null) {\n\t\t\tconsole.log(\"texCoordArray uninitialized\");\n\t\t}\n\n\t\tconst gl = this.gl;\n\t\tthis.texCoordBuffer = gl.createBuffer();\n\t\tgl.bindBuffer(gl.ARRAY_BUFFER, this.texCoordBuffer);\n\t\tgl.bufferData(gl.ARRAY_BUFFER,\n \t\tnew Float32Array(this.texCoordArray),\n \t\tgl.STATIC_DRAW);\n\t}",
"printBuffers() {\n for (var i = 0; i < this.numVertices; i++) {\n console.log(\"v \", this.positionData[i*3], \" \",\n this.positionData[i*3 + 1], \" \",\n this.positionData[i*3 + 2], \" \");\n }\n for (var i = 0; i < this.numVertices; i++) {\n console.log(\"n \", this.normalData[i*3], \" \",\n this.normalData[i*3 + 1], \" \",\n this.normalData[i*3 + 2], \" \");\n }\n for (var i = 0; i < this.numFaces; i++) {\n console.log(\"f \", this.faceData[i*3], \" \",\n this.faceData[i*3 + 1], \" \",\n this.faceData[i*3 + 2], \" \");\n }\n }",
"function onReadComplete(gl, model, objDoc) {\n\n // Acquire the vertex coordinates and colors from OBJ file\n var drawingInfo = objDoc.getDrawingInfo();\n // Write date into the buffer object\n gl.bindBuffer(gl.ARRAY_BUFFER, model.vertexBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, drawingInfo.vertices, gl.STATIC_DRAW);\n\n //gl.bindBuffer(gl.ARRAY_BUFFER, model.normalBuffer);\n //gl.bufferData(gl.ARRAY_BUFFER, drawingInfo.normals, gl.STATIC_DRAW);\n\n gl.bindBuffer(gl.ARRAY_BUFFER, model.colorBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, drawingInfo.colors, gl.STATIC_DRAW);\n\n // Write the indices to the buffer object\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, model.indexBuffer);\n gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, drawingInfo.indices, gl.STATIC_DRAW);\n\n return drawingInfo;\n}",
"function parseBuffer(gl, bufferJSON) {\n checkParameter(\"parseBuffer\", gl, \"gl\");\n checkParameter(\"parseBuffer\", bufferJSON, \"bufferJSON\");\n var data = bufferJSON[\"data\"];\n checkParameter(\"parseBuffer\", data, \"bufferJSON[data]\");\n var verticesBuffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, verticesBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(data), gl.STATIC_DRAW);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
a function to detect if the tooltip is going off the screen horizontally. If so, reposition the crap out of it! | function dontGoOffScreenX() {
var windowLeft = $(window).scrollLeft();
// if the tooltip goes off the left side of the screen, line it up with the left side of the window
if((myLeft - windowLeft) < 0) {
arrowReposition = myLeft - windowLeft;
myLeft = windowLeft;
}
// if the tooltip goes off the right of the screen, line it up with the right side of the window
if (((myLeft + tooltipWidth) - windowLeft) > windowWidth) {
arrowReposition = myLeft - ((windowWidth + windowLeft) - tooltipWidth);
myLeft = (windowWidth + windowLeft) - tooltipWidth;
}
} | [
"function tooltipXposition(d){\n\t\t\treturn x(d)+leftOffset(\"stage_wrapper\")+\"px\";\n\t\t}",
"function tooltip_placement(context, source) {\n\t\tvar $source = $(source);\n\t\tvar $parent = $source.closest('table')\n\t\tvar off1 = $parent.offset();\n\t\tvar w1 = $parent.width();\n\n\t\tvar off2 = $source.offset();\n\t\t//var w2 = $source.width();\n\n\t\tif( parseInt(off2.left) < parseInt(off1.left) + parseInt(w1 / 2) ) return 'right';\n\t\treturn 'left';\n\t}",
"function positionTip(evt) {\r\n\tif (!tipFollowMouse) {\r\n\t\tmouseX = (ns4||ns5)? evt.pageX: window.event.clientX + document.documentElement.scrollLeft;\r\n\t\tmouseY = (ns4||ns5)? evt.pageY: window.event.clientY + document.documentElement.scrollTop;\r\n\t}\r\n\t// tooltip width and height\r\n\tvar tpWd = (ns4)? tooltip.width: (ie4||ie5)? tooltip.clientWidth: tooltip.offsetWidth;\r\n\tvar tpHt = (ns4)? tooltip.height: (ie4||ie5)? tooltip.clientHeight: tooltip.offsetHeight;\r\n\t// document area in view (subtract scrollbar width for ns)\r\n\tvar winWd = (ns4||ns5)? window.innerWidth-20+window.pageXOffset: document.body.clientWidth+document.body.scrollLeft;\r\n\tvar winHt = (ns4||ns5)? window.innerHeight-20+window.pageYOffset: document.body.clientHeight+document.body.scrollTop;\r\n\t// check mouse position against tip and window dimensions\r\n\t// and position the tooltip \r\n\r\n\tif ((mouseX+offX+tpWd)>winWd)\r\n\t{\r\n\t\ttipcss.left = (ns4)? mouseX-(tpWd+offX): mouseX-(tpWd+offX)+\"px\";\r\n\t}\r\n\telse\r\n\t{\r\n\t\ttipcss.left = (ns4)? mouseX+offX: mouseX+offX+\"px\";\r\n\t}\r\n\tif ((mouseY+offY+tpHt)>winHt)\r\n\t{\r\n\t\ttipcss.top = (ns4)? winHt-(tpHt+offY): winHt-(tpHt+offY)+\"px\";\r\n\t}\r\n\telse\r\n\t{\r\n\t\ttipcss.top = (ns4)? mouseY+offY: mouseY+offY+\"px\";\r\n\t}\r\n\r\n\tif (!tipFollowMouse) t1=setTimeout(\"tipcss.visibility='visible'\",100);\r\n}",
"resetPosition() {\n if (this.hasGoneOffScreen()) {\n this.x = this.canvas.width;\n }\n }",
"function checkPosition() {\n\tconst heart = document.getElementById(\"profile-heart\");\n\tconst cross = document.getElementById(\"profile-cross\");\n\tconst qmark = document.getElementById(\"qmark\");\n\n\tif (this.x > 0) {\n\t\tcross.style.opacity = 0;\n\t\theart.style.opacity = 0.5;\n\t\tqmark.style.opacity = 0.5;\n\t\theart.style.animationPlayState = \"running\";\n\t}\n\tif (this.x < 0) {\n\t\theart.style.opacity = 0;\n\t\tcross.style.opacity = 0.5;\n\t\tqmark.style.opacity = 0.5;\n\t\tcross.style.animationPlayState = \"running\";\n\t}\n}",
"function alignHorizontally(systemPopup, position, tries) {\n var extra = systemPopup.data(\"popup-extra\");\n // Sender's offset in parent\n var senderOffset = extra['senderOffset'];\n // Onscreen alignment distance\n var aliDist = extra['alignOffset'];\n // Point of reference\n var pivotPoint;\n // Sender\n var sender = extra.sender;\n // Amount that popup exceeds window\n var elemDiff;\n\n var dock = (extra.invertedHorizontalDock === true ? \"right\" : \"left\");\n // Switching map\n var switchMap = {\n \"left\": \"right\",\n \"right\": \"left\",\n \"center\": \"right\"\n };\n\n systemPopup.data(\"popup-extra\").pointer.alignment = $.trim(position);\n var borderSize = 1;\n\n switch ($.trim(position)) {\n case \"left\":\n // Left alignment\n // Pivot point depends on the docking of the sender\n if (extra.invertedHorizontalDock === true)\n pivotPoint = extra['parent'].width() - senderOffset.left - systemPopup.outerWidth() + borderSize;\n else\n pivotPoint = senderOffset.left - borderSize;\n break;\n case \"right\":\n // Right alignment\n // Pivot point depends on the docking of the sender\n if (extra.invertedHorizontalDock === true)\n pivotPoint = extra['parent'].width() - senderOffset.left - sender.outerWidth() - borderSize;\n else\n pivotPoint = senderOffset.left + sender.outerWidth() - systemPopup.outerWidth() + borderSize;\n break;\n case \"center\":\n // Center alignment\n // Pivot point depends on the docking of the sender\n if (extra.invertedHorizontalDock === true)\n pivotPoint = extra['parent'].width() - senderOffset.left - sender.outerWidth() - ((systemPopup.outerWidth() - sender.outerWidth()) / 2);\n else\n pivotPoint = senderOffset.left - ((systemPopup.outerWidth() - sender.outerWidth()) / 2);\n break;\n default:\n // invalid -> switch to center orientation\n systemPopup.data(\"popup-extra\").calculatedPosition = \"center\";\n repositionPopup(systemPopup);\n return;\n }\n\n // Check if popup is out of parent bounds\n var inParent = isInsideHorizontalElementBounds(systemPopup, extra['parent'].offset().left + pivotPoint, extra['parent']) || extra['parent'].is($(document.body));\n // Check if popup is out of window bounds\n var inViewport = isInsideHorizontalWindowBounds(systemPopup, extra['parent'].offset().left + pivotPoint);\n\n // Set alignment or try another\n if ((inParent && inViewport) || tries > 1) {\n systemPopup.data(\"popup-extra\").calculatedPosition += dock + \":\" + (pivotPoint + aliDist);\n stickToSender(systemPopup);\n } else\n alignHorizontally(systemPopup, switchMap[position], ++tries);\n }",
"scrollToMousePos() {\n this._followingCursor = true;\n if (this._mouseTrackingMode != GDesktopEnums.MagnifierMouseTrackingMode.NONE)\n this._changeROI({ redoCursorTracking: true });\n else\n this._updateMousePosition();\n\n // Determine whether the system mouse pointer is over this zoom region.\n return this._isMouseOverRegion();\n }",
"wrapx()\n\t{\n\t\t//if the right hand edge of the sprite is less than the left edge of screen\n\t\t//then position its left edge to the right hand side of the screen\n\t\tif (this.right < 0)\n\t\t\tthis.pos.x += this.screensize.width + this.size.width;\n\t\t//if the left hadn edge is off the right hand side of the screen then\n\t\t//position it so its right hand edge is to the left of the screen\n\t\telse if (this.left >= this.screensize.width)\n\t\t\tthis.pos.x -= this.screensize.width + this.size.width;\n\t}",
"function _setTooltipPosition() {\n // eslint-disable-next-line no-new\n new PopperJs($element, _tooltip, {\n placement: lumx.position || 'top',\n modifiers: {\n arrow: {\n // eslint-disable-next-line id-blacklist\n element: `.${CSS_PREFIX}-tooltip__arrow`,\n enabled: true,\n },\n },\n });\n }",
"function horizontalLinePosition(p_event) {\n\tdocument.getElementById('horizontal-resize-line').style.left = p_event.pageX;\n}",
"function orientatePopupHorizontally(systemPopup, position, tries) {\n var extra = systemPopup.data(\"popup-extra\");\n var posArr = position.split(\"|\");\n // Popup's onscreen distance from sender in px\n var offDist = extra['distanceOffset'] + 10;\n // Reference point\n var pivotPoint;\n // Sender\n var sender = extra.sender;\n // Sender's offset in parent\n var senderOffset = extra['senderOffset'];\n\n var dock = (extra.invertedHorizontalDock === true ? \"right\" : \"left\");\n // Switching map\n var switchMap = {\n \"left\": \"right\",\n \"right\": \"left\"\n };\n posArr[0] = $.trim(posArr[0]);\n systemPopup.data(\"popup-extra\").pointer.orientation = switchMap[posArr[0]];\n // Check given orientation\n if (posArr[0] == \"left\") {\n // Left side of sender\n // Pivot point depends on the docking of the sender\n if (extra.invertedHorizontalDock === true)\n pivotPoint = extra['parent'].width() - senderOffset.left + offDist;\n else\n pivotPoint = senderOffset.left - offDist - systemPopup.outerWidth();\n } else {\n // Right\n // Pivot point depends on the docking of the sender\n if (extra.invertedHorizontalDock === true)\n pivotPoint = extra['parent'].width() - senderOffset.left - sender.outerWidth() - systemPopup.outerWidth() - offDist;\n else\n pivotPoint = senderOffset.left + sender.outerWidth() + offDist;\n }\n\n // Check if popup is out of parent bounds\n var inParent = isInsideHorizontalElementBounds(systemPopup, extra['parent'].offset().left + pivotPoint, extra['parent']) || extra['parent'].is($(document.body));\n\n // Check if popup is out of window bounds\n var inViewport = isInsideHorizontalWindowBounds(systemPopup, extra['parent'].offset().left + pivotPoint);\n\n if ((inParent && inViewport) || tries > 1) {\n // Set left orientation\n systemPopup.data(\"popup-extra\").calculatedPosition = dock + ':' + (pivotPoint) + '|';\n // Sets Vertical alignment with the sender\n alignVertically(systemPopup, posArr[1], 0);\n } else {\n // Change to right orientation\n orientatePopupHorizontally(systemPopup, switchMap[posArr[0]] + \"|\" + posArr[1], ++tries);\n }\n }",
"function PopUp_Hover() {\n var _return = false;\n\n\n if ((_mouse[\"x\"] > _popUp.offset().left) && _mouse[\"x\"] < (_popUp.offset().left + _popUp.outerWidth())) {\n if ((_mouse[\"y\"] > _popUp.offset().top) && _mouse[\"y\"] < (_popUp.offset().top + _popUp.outerHeight())) {\n _return = true\n }\n }\n\n return _return;\n }",
"scrollToMousePos() {\n let [xMouse, yMouse] = global.get_pointer();\n\n if (xMouse != this.xMouse || yMouse != this.yMouse) {\n this.xMouse = xMouse;\n this.yMouse = yMouse;\n\n let monitorIdx = this._tree.find([xMouse, yMouse]);\n let zoomRegion = this._zoomRegions[monitorIdx];\n let sysMouseOverAny = false;\n if (zoomRegion.scrollToMousePos())\n sysMouseOverAny = true;\n\n if (sysMouseOverAny)\n this.hideSystemCursor();\n else\n this.showSystemCursor();\n }\n return true;\n }",
"repositionDetails() {\n if (this.details && this.ibScapeDetails) {\n // Position the details based on its size.\n let ibScapeDetailsDiv = this.ibScapeDetails.node();\n let detailsRect = ibScapeDetailsDiv.getBoundingClientRect();\n ibScapeDetailsDiv.style.position = \"absolute\";\n\n\n // Relative to top left corner of the graph, move up and left half\n // of the details height/width.\n ibScapeDetailsDiv.style.left = (this.rect.left + this.center.x - (detailsRect.width / 2)) + \"px\";\n\n // Special handling for the top, because virtual keyboards on mobile\n // devices take up real estate and it's not worth it to check for\n // keyboard manually. Just have the top of the details higher than center.\n let topOffset = this.getIsPortrait() ? this.rect.height / 5 : 20;\n ibScapeDetailsDiv.style.top = (this.rect.top + topOffset) + \"px\";\n }\n }",
"_calculateErrorMsgTooltipPosition(inputElement, errorMsgHolder) {\n const bodyRect = document.body.getBoundingClientRect(),\n elemRect = inputElement.getBoundingClientRect(),\n offsetTop = elemRect.top - bodyRect.top;\n\n errorMsgHolder.style.top = offsetTop + elemRect.height + 'px';\n errorMsgHolder.style.left = elemRect.left + 'px';\n }",
"__moveThresholdReached(clientX, clientY) {\n return Math.abs(clientX - this.data.startMouseX) >= this.moveThreshold || Math.abs(clientY - this.data.startMouseY) >= this.moveThreshold;\n }",
"function repositionHintBox(e, graph) {\n\t\tvar hbox = $(graph.hintBoxItem),\n\t\t\toffset = graph.offset(),\n\t\t\tpage_bottom = jQuery(window.top).scrollTop() + jQuery(window.top).height(),\n\t\t\tl = (document.body.clientWidth >= e.clientX + hbox.outerWidth() + 20)\n\t\t\t\t? e.clientX - offset.left + 20\n\t\t\t\t: e.clientX - hbox.outerWidth() - offset.left - 15,\n\t\t\tt = e.pageY - offset.top - graph.parent().scrollTop(),\n\t\t\tt = page_bottom >= t + offset.top + hbox.outerHeight() + 60 ? t + 60 : t - hbox.height();\n\n\t\thbox.css({'left': l, 'top': t});\n\t}",
"function getLeftPosition() {\n return randomFunction(0, viewportWidth - 100);\n}",
"positionOnTimeline(posX) {\n let rect = this.timelineNode.getBoundingClientRect();\n let posClickedX = posX - rect.left + this.timelineNode.scrollLeft;\n return posClickedX;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Closes the dialog after saving or cancelling, scrolling the web page to where it was prior to opening. | function closeDialog () {
controls.validator.resetValidationErrors();
table.clearHighlight();
popup.hide();
window.scrollTo(permissionManager.bookmark.scrollX, permissionManager.bookmark.scrollY);
} | [
"@action closeDialog() {\r\n\t\tif (this.dialog) this.dialog.opened = false;\r\n\t}",
"function closeAndMove(targetPage) {\r\n\topener.document.location = targetPage;\r\n\tself.close();\r\n}",
"function save() {\n dialogOut.dialog( \"close\" );\n }",
"function closeTaxDetail() {\r\n if (!$isOnView)\r\n $validateTax.resetForm(); \r\n $('#divTaxBreakdown').dialog('close');\r\n}",
"close() {\n this.showModal = false;\n\n this.onClose();\n }",
"function closeReportWindow () {\n\tset_element_display_by_id_safe('ReportWindow', 'none');\n\tset_element_display_by_id_safe('report_error1', 'none');\n\tset_element_display_by_id_safe('report_error2', 'none');\n\tset_element_display_by_id_safe('error_div', 'none');\n}",
"function closeEditingWindow() {\n document.getElementById(\"fileEditing\").style.display = \"none\";\n document.getElementById(\"pageTitle\").childNodes[1].textContent = \"Files\";\n document.getElementById(\"fileBrowser\").style.display = \"block\";\n\n console.log(\"HUB: Closing editing tool\");\n}",
"close() {\n return spPost(WebPartDefinition(this, \"CloseWebPart\"));\n }",
"closeFile() {\n\t\tthis.code.closeEditor(this.path);\n\t}",
"function handleWidgetClose(){\n confirmIfDirty(function(){\n if(WidgetBuilderApp.isValidationError)\n {\n WidgetBuilderApp.dirtyController.setDirty(true,\"Widget\",WidgetBuilderApp.saveOnDirty);\n return;\n }\n $(\".perc-widget-editing-container\").hide();\n $(\"#perc-widget-menu-buttons\").hide();\n $(\"#perc-widget-def-tabs\").tabs({disabled: [0,1,2, 3]});\n });\n }",
"closeDetails() {\n this.setDetailsView(0);\n }",
"close() {\n\n // Pop the activity from the stack\n utils.popStackActivity();\n\n // Hide the disclaimer\n this.disclaimer.scrollTop(0).hide();\n\n // Hide the screen\n this.screen.scrollTop(0).hide();\n\n // Reset the fields\n $(\"#field--register-email\").val(\"\");\n $(\"#field--register-password\").val(\"\");\n $(\"#field--register-confirm-password\").val(\"\");\n\n // Reset the selectors\n utils.resetSelector(\"register-age\");\n utils.resetSelector(\"register-gender\");\n utils.resetSelector(\"register-occupation\");\n\n // Set the flag to false\n this._isDisclaimerOpen = false;\n\n }",
"function CloseArticleInfoWindow ()\n {\n CloseWindow ( wInfo );\n }",
"function closeWin()\r\n{\r\n var browserWin = getBrowserWindow();\r\n if (browserWin && browserWin.gStatusManager\r\n && browserWin.gStatusManager.closeMsgDetail)\r\n {\r\n browserWin.gStatusManager.closeMsgDetail();\r\n }\r\n else\r\n { \r\n self.close();\r\n }\r\n return;\r\n}",
"function closeAddNewDriveWindow() {\n deactivateOverlay()\n document.getElementById(\"drive-list\").style.pointerEvents = \"all\";\n document.getElementById(\"add-new-drive-window\").style.display = \"none\"\n document.getElementById(\"unadded-drive-list\").textContent = \"\"\n}",
"function closePopup()\n{\n win.close();\n return true;\n}",
"function fn_downloaddoc()\n{\n\tvar filename=$('#activityfilename').val();\n\twindow.open('library/activities/library-activities-download.php?&filename='+filename,'_self');\n\treturn false;\n}",
"close() {\n if(this.added) {\n this.added = false;\n this.getJQueryObject().remove();\n\n // Remove entry from global entries variable\n entries = _.omit(entries, this.id);\n\n GUI.onEntriesChange();\n GUI.updateWindowHeight();\n }\n }",
"function closeLightboxReloadPage() {\n closeLightbox();\n top.window.location.reload(true);\n}",
"function closecancelpanel(){\n $.modal.close();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Asserts that the type being dynamically instantiated is a Component. | _assertTypeIsComponent(type:Type):void {
var annotation = this._directiveMetadataReader.read(type).annotation;
if (!(annotation instanceof Component)) {
throw new BaseException(`Could not load '${stringify(type)}' because it is not a component.`);
}
} | [
"createComponent(scenario) {\r\n class DynamicComponent {\r\n constructor() {\r\n Object.assign(this, scenario.context);\r\n }\r\n }\r\n return Component({\r\n selector: 'playground-host',\r\n template: scenario.template,\r\n styles: scenario.styles,\r\n providers: scenario.providers,\r\n })(DynamicComponent);\r\n }",
"getComponentType() {\n return utilities_1.getComponentInstanceTypeFromComponentName(this.constructor.getComponentName());\n }",
"function createComponent(Ctor, props, context) {\n var list = components[Ctor.name],\n inst;\n\n if (Ctor.prototype && Ctor.prototype.render) {\n inst = new Ctor(props, context);\n Component$1.call(inst, props, context);\n } else {\n inst = new Component$1(props, context);\n inst.constructor = Ctor;\n inst.render = doRender;\n }\n\n if (list) {\n for (var i = list.length; i--;) {\n if (list[i].constructor === Ctor) {\n inst.nextBase = list[i].nextBase;\n list.splice(i, 1);\n break;\n }\n }\n }\n return inst;\n }",
"function _getValidComponent( node ) {\n\tif ( node && ( node._instance || node.constructor.name == 'ReactCompositeComponentWrapper' ) ) {\n\t\tnode = node._instance;\n\t}\n\tif ( node && IGNORED_COMPONENTS.indexOf( node.constructor.name ) >= 0 ) {\n\t\tnode = null;\n\t}\n\treturn node;\n}",
"function createComponentUnderTest() {\n const element = createElement('c-cart-contents', {\n is: CartContents\n });\n document.body.appendChild(element);\n return element;\n}",
"create(environment, state, args, dynamicScope, callerSelfRef, hasBlock) {\n if (DEBUG) {\n this._pushToDebugStack(`component:${state.name}`, environment);\n }\n // Get the nearest concrete component instance from the scope. \"Virtual\"\n // components will be skipped.\n let parentView = dynamicScope.view;\n // Get the Ember.Component subclass to instantiate for this component.\n let factory = state.ComponentClass;\n // Capture the arguments, which tells Glimmer to give us our own, stable\n // copy of the Arguments object that is safe to hold on to between renders.\n let capturedArgs = args.named.capture();\n let props = processComponentArgs(capturedArgs);\n // Alias `id` argument to `elementId` property on the component instance.\n aliasIdToElementId(args, props);\n // Set component instance's parentView property to point to nearest concrete\n // component.\n props.parentView = parentView;\n // Set whether this component was invoked with a block\n // (`{{#my-component}}{{/my-component}}`) or without one\n // (`{{my-component}}`).\n props[HAS_BLOCK] = hasBlock;\n // Save the current `this` context of the template as the component's\n // `_target`, so bubbled actions are routed to the right place.\n props._target = callerSelfRef.value();\n // static layout asserts CurriedDefinition\n if (state.template) {\n props.layout = state.template;\n }\n // Now that we've built up all of the properties to set on the component instance,\n // actually create it.\n let component = factory.create(props);\n let finalizer = _instrumentStart('render.component', initialRenderInstrumentDetails, component);\n // We become the new parentView for downstream components, so save our\n // component off on the dynamic scope.\n dynamicScope.view = component;\n // Unless we're the root component, we need to add ourselves to our parent\n // component's childViews array.\n if (parentView !== null && parentView !== undefined) {\n addChildView(parentView, component);\n }\n component.trigger('didReceiveAttrs');\n let hasWrappedElement = component.tagName !== '';\n // We usually do this in the `didCreateElement`, but that hook doesn't fire for tagless components\n if (!hasWrappedElement) {\n if (environment.isInteractive) {\n component.trigger('willRender');\n }\n component._transitionTo('hasElement');\n if (environment.isInteractive) {\n component.trigger('willInsertElement');\n }\n }\n // Track additional lifecycle metadata about this component in a state bucket.\n // Essentially we're saving off all the state we'll need in the future.\n let bucket = new ComponentStateBucket(environment, component, capturedArgs, finalizer, hasWrappedElement);\n if (args.named.has('class')) {\n bucket.classRef = args.named.get('class');\n }\n if (DEBUG) {\n processComponentInitializationAssertions(component, props);\n }\n if (environment.isInteractive && hasWrappedElement) {\n component.trigger('willRender');\n }\n return bucket;\n }",
"function Component() {\n this._m_data = null;\n this._m_refs = null;\n this._m_children = null;\n var ctor = this.constructor;\n this._m_node = document.createElement(ctor.tag);\n this._m_node.className = ctor.className;\n }",
"loadIntoExistingLocation(type:Type, location:ElementRef, injector:Injector = null):Promise<ComponentRef> {\n this._assertTypeIsComponent(type);\n var annotation = this._directiveMetadataReader.read(type).annotation;\n var componentBinding = DirectiveBinding.createFromType(type, annotation);\n\n return this._compiler.compile(type).then(componentProtoView => {\n var componentView = this._viewFactory.getView(componentProtoView);\n this._viewHydrator.hydrateDynamicComponentView(\n location, componentView, componentBinding, injector);\n\n var dispose = () => {throw new BaseException(\"Not implemented\");};\n return new ComponentRef(location, location.elementInjector.getDynamicallyLoadedComponent(), componentView, dispose);\n });\n }",
"function assertInstanceof(instance, type) {\n if (!(instance instanceof type))\n throw 'Error: Not an instance of ' + type.name;\n return instance;\n}",
"function isElementOfType(element, Component) {\n var _element$props;\n\n if (element == null || ! /*#__PURE__*/React.isValidElement(element) || typeof element.type === 'string') {\n return false;\n }\n\n const {\n type: defaultType\n } = element; // Type override allows components to bypass default wrapping behavior. Ex: Stack, ResourceList...\n // See https://github.com/Shopify/app-extension-libs/issues/996#issuecomment-710437088\n\n const overrideType = (_element$props = element.props) == null ? void 0 : _element$props.__type__;\n const type = overrideType || defaultType;\n const Components = Array.isArray(Component) ? Component : [Component];\n return Components.some(AComponent => typeof type !== 'string' && isComponent(AComponent, type));\n} // Returns all children that are valid elements as an array. Can optionally be",
"function assertType(value,type){var valid;var expectedType=getType(type);if(expectedType==='String'){valid=(typeof value==='undefined'?'undefined':_typeof2(value))===(expectedType='string');}else if(expectedType==='Number'){valid=(typeof value==='undefined'?'undefined':_typeof2(value))===(expectedType='number');}else if(expectedType==='Boolean'){valid=(typeof value==='undefined'?'undefined':_typeof2(value))===(expectedType='boolean');}else if(expectedType==='Function'){valid=(typeof value==='undefined'?'undefined':_typeof2(value))===(expectedType='function');}else if(expectedType==='Object'){valid=isPlainObject(value);}else if(expectedType==='Array'){valid=Array.isArray(value);}else{valid=value instanceof type;}return{valid:valid,expectedType:expectedType};}",
"requireValidComponent(componentResource, referencingComponent) {\n if (!this.isValidComponent(componentResource)) {\n throw new Error(`Resource ${componentResource.value} is not a valid component, either it is not defined, has no type, or is incorrectly referenced${referencingComponent ? ` by ${referencingComponent.value}` : ''}.`);\n }\n }",
"registerComponent(component) {\n this.requireValidComponent(component);\n if (component.term.termType !== 'NamedNode') {\n this.logger.warn(`Registered a component that is identified by a ${component.term.termType} (${component.value}) instead of an IRI identifier.`);\n }\n this.componentResources[component.value] = component;\n }",
"loadIntoNewLocation(type:Type, parentComponentLocation:ElementRef, elementOrSelector:any,\n injector:Injector = null):Promise<ComponentRef> {\n this._assertTypeIsComponent(type);\n\n return this._compiler.compileInHost(type).then(hostProtoView => {\n var hostView = this._viewFactory.getView(hostProtoView);\n this._viewHydrator.hydrateInPlaceHostView(\n parentComponentLocation, elementOrSelector, hostView, injector\n );\n\n var newLocation = hostView.elementInjectors[0].getElementRef();\n var component = hostView.elementInjectors[0].getComponent();\n var dispose = () => {\n this._viewHydrator.dehydrateInPlaceHostView(parentComponentLocation, hostView);\n this._viewFactory.returnView(hostView);\n };\n return new ComponentRef(newLocation, component, hostView.componentChildViews[0], dispose);\n });\n }",
"generateComponent(scriptName) {\n if (!this._store[scriptName]) {\n return null;\n }\n\n let component = Object.create(this._store[scriptName].prototype);\n component._name = scriptName;\n\n // now we need to assign all the instance properties defined:\n let properties = this._store[scriptName].properties.getAll();\n let propertyNames = Object.keys(properties);\n\n if (propertyNames && propertyNames.length > 0) {\n propertyNames.forEach(function(propName) {\n // assign the default value if exists:\n component[propName] = properties[propName].default;\n });\n }\n\n return component;\n }",
"function renderComponent(ComponentClass, props = {}, state = {}) {\n //ComponentClass refers to component class build (ex. CommentBox extends Component)\n //make instance of said class (below)\n //renderIntoDocument requires DOM, need react-dom library.\n const componentInstance = TestUtils.renderIntoDocument(\n // probably going to need to wrap this in Provider once reducers come into play....\n <ComponentClass {...props} />\n\n );\n //find & return DOM node.\n //ReactDOM.findDOMNode gives reference to html\n //wrapped in jQuery to connect it to helpers from jQuery Chai.\n return $(ReactDOM.findDOMNode(componentInstance));\n}",
"function isInstanceOf(varInput, objConstructor) {\n\t//make sure the constructor is defined\n\tif (objConstructor == undefined) {throw new Error(\"isInstanceOf: objConstructor is undefined\");}\n\n\t//if the input isn't an object or doesn't have the desired constructor, return false\n\tif ((typeof varInput != \"object\") || (varInput.constructor != objConstructor)) {\n\t\treturn false;\n\t} else { //if it passed the above test, the input is an instance of the constructor, so return true\n\t\treturn true;\n\t} //end if\n} //end function isInstanceOf",
"function ComponentHarness() {\n EventEmitter.call(this);\n this.app = new AppForHarness(this);\n this.model = new Model();\n\n if (arguments.length > 0) {\n this.setup.apply(this, arguments);\n }\n}",
"function getComponentModel(params) {\n var componentInfo = params.componentName ? AppPlayer.Views.componentInfos[params.componentName] : null, bindingProperties = [], componentViewModel = AppPlayer.propertyVisitor(params.viewModel, function (context) {\n var value = context.value, propName = context.name, isEvent = false, result = value, fn;\n if (componentInfo && componentInfo.events) {\n isEvent = componentInfo.events.some(function (eventName) { return eventName === propName; });\n }\n if (isEvent) {\n fn = params.functions[value];\n var runContext = $.extend({}, params.runContext);\n result = function (e) {\n var event = e ? e.jQueryEvent : null;\n if (event && event.stopPropagation && params.componentName !== \"command\") {\n event.stopPropagation();\n }\n // TODO Pletnev Choose itemData or data depending on event and object\n if (e && (e.itemData || e.data)) {\n runContext.$data = e.itemData || e.data;\n }\n else {\n runContext.$data = params.runContext.$data;\n }\n return fn(runContext);\n };\n }\n else {\n if (typeof value === \"string\") {\n var val = value;\n if (val.indexOf(\"'\") === 0 && val.lastIndexOf(\"'\") === val.length - 1) {\n val = val.substr(1, val.length - 2);\n }\n result = AppPlayer.wrapModelReference(val, params.runContext, params.callerInfo);\n if (result !== val) {\n bindingProperties.push(context.path ? context.path + \".\" + propName : propName);\n }\n }\n }\n return result;\n });\n if (componentInfo && componentInfo.componentViewModel) {\n componentViewModel = componentInfo.componentViewModel(componentViewModel);\n }\n if (bindingProperties.length > 0) {\n componentViewModel[\"_bindingProperties\"] = bindingProperties;\n }\n return componentViewModel;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The facebook logout handler | function facebookLogoutHandler(e) {
if (e.success) {
var client = Titanium.Network.createHTTPClient();
client.clearCookies('https://login.facebook.com');
} else if (e.error) {
// Error!
}
} | [
"function logout() {\n // clear the token\n AuthToken.setToken();\n }",
"function logout_response(disconnect) {\n $login_view.show();\n $class_view.hide();\n $group_view.hide();\n\n\n $error_username.hide();\n $error_class_id.hide();\n\n $class_id.css(\"border-color\", null);\n $username.css(\"border-color\", null);\n\n $class_id.val(\"\");\n $username.val(\"\");\n \n if(!disconnect){\n sessionStorage.removeItem('class_id');\n sessionStorage.removeItem('username');\n sessionStorage.removeItem('group_id');\n sessionStorage.removeItem('toolbar');\n sessionStorage.removeItem('group_colors');\n\n }\n}",
"function logout() {\n didAbandonGame = true;\n _send(messages.LOGOUT, main.username);\n }",
"function game_logout() {\r\n\t\t\r\n\t\t$.ajax({\r\n\t\t\turl: 'logout.php',\r\n\t\t\tsuccess: function( data ) {\r\n\t\t\t\tif ( data=='0' )\r\n\t\t\t\t\twindow.location = REDIRECT_TO;\r\n\t\t\t\telse\r\n\t\t\t\t\t$( '#hv_alert_wrapper' ).hv_alert( 'show_alert', {\r\n\t\t\t\t\t\t'message': c['error_gm_exit']+' '+data\r\n\t\t\t\t\t});\r\n\t\t\t}\r\n\t\t});\r\n\t\t\r\n\t}",
"logoutUser() {\n this.get('session').invalidate();\n }",
"_handleLogout(){\r\n sessionStorage.clear();\r\n this.set('route.path', './login-page');\r\n }",
"function logout(){\n tokenFactory.deleteToken();\n $window.location.reload();\n }",
"function logout() {\n $logoutButton.on('click', function() {\n sockets.logout();\n $(this).fadeOut(function() {\n $(this).remove();\n });\n $waitingTime.fadeOut();\n });\n }",
"logout() {\n debug(\"=== Hotjar logout running... ===\")\n debug(\"Remove local storage and cookie with: %s\", this.hjSessionKeyName)\n removeLocalStorageItem(this.hjSessionKeyName)\n removeLocalItem(this.hjSessionKeyName)\n debug(\"=== Hotjar logout finished... ===\")\n }",
"function logout() {\n $.removeCookie(\"userId\");\n /// redirect to login\n window.location.replace(\"/\");\n}",
"function forceLogout(){\r\n\t$.post(\"utente\", {\"action\": \"logout\"}, function(resp, stat, xhr){\r\n\t\tif(xhr.readyState == 4 && stat == \"success\"){\r\n\t\t\tvar o = JSON.parse(resp);\r\n\t\t\tvar esito = o.done;\r\n\t\t\t//no utilizzo del risultato\r\n\t\t}else{\r\n\t\t\twindow.location.href = \"./error.jsp\"; //pagina errore 404\r\n\t\t}\r\n\t});\r\n}",
"function logoutListener() {\n loggedIn = false;\n }",
"logout() {\n\t\tplaylistsContainer.innerHTML = '<iframe src=\"https://www.spotify.com/logout/\"></iframe>';\n\t\tplaylistsContainer.style.display = 'none';\n\t\tsetTimeout(() => window.location = [location.protocol, '//', location.host, location.pathname].join(''), 1500);\n\t}",
"_logoutUser() {\n /* End Session of User */\n SessionStore.endSession();\n /* Return to Start Screen of App */\n this.props.navigation.navigate('Start');\n }",
"function logout() {\n sessionStorage.removeItem(\"userId\");\n sessionStorage.removeItem(\"jwt\");\n }",
"function spotifyLogout() {\n // Wipe localStorage values.\n localStorage.removeItem(SPOTIFY_ACCESS_TOKEN_KEY);\n localStorage.removeItem(SPOTIFY_REFRESH_TOKEN_KEY);\n localStorage.removeItem(SPOTIFY_VOLUME_KEY);\n\n // Refresh the page.\n window.location.href = window.location.href;\n}",
"function logOut() {\n localStorage.removeItem('token');\n newView();\n}",
"function handleLoginEnd(req, res) {\n var verifier = req.param('oauth_verifier');\n\n if (!verifier) {\n res.contentType('text/html');\n res.write('ERROR: could not find oauth_verifier. The user probably denied access.<br><br>');\n res.write('<a href=\"' + endpoints.main + '\">Click here to return to the main example page.</a>');\n res.end();\n return;\n }\n\n rdio.completeAuthentication(req.param('oauth_verifier'), function() {\n store.write(res, function() {\n // Save the auth token to the cookie and then redirect to the main page.\n res.redirect('/' + endpoints.main);\n });\n });\n}",
"function logOff(all) {\n removeJwtToken();\n document.location.assign(\"/login\")\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
repeat string `str` up to total length of `len` | function repeatString(str, len) {
return Array.apply(null, {length: len + 1}).join(str).slice(0, len)
} | [
"function repeatString(str, count) { \n // TODO: your code here \n if(count === 0){\n return \"\";\n }\n return str + repeatString(str, count - 1);\n}",
"function modifyLast(str, n) {\n\treturn str.slice(0, -1) + str.slice(-1).repeat(n);\n}",
"function GetFixLenStr(str, len, insChar, type)\n{\n var o = \"\";\n str = \"\" + str; // make sure it is string\n var count = len - str.length;\n var lc = rc = 0;\n if (type == 1)\n {\n rc = count;\n }\n else if (type == 2)\n {\n lc = count / 2;\n rc = count - lc;\n }\n else\n {\n lc = count;\n }\n if (lc > 0)\n {\n var i = 0;\n for (i = 0; i < lc; i++)\n {\n o += insChar;\n }\n }\n o += str;\n if (rc > 0)\n {\n var i = 0;\n for (i = 0; i < rc; i++)\n {\n o += insChar;\n }\n }\n return o;\n}",
"function leftPad(string, length, fillCharacter) {\n var newString = \"\";\n if (string.length < length) {\n for (let i = 0; i < (length - string.length); i++) {\n newString += fillCharacter\n }\n return newString + string;\n } else {\n return string\n }\n}",
"function checkRepetition(pLen,str)\n{\n res = \"\";\n for ( i=0; i<str.length ; i++ ) {\n repeated=true;\n for (j=0;j < pLen && (j+i+pLen) < str.length;j++) {\n repeated=repeated && (str.charAt(j+i)==str.charAt(j+i+pLen));\n }\n\n if (j<pLen) repeated=false;\n if (repeated) {\n i+=pLen-1;\n repeated=false;\n } else {\n res+=str.charAt(i);\n }\n }\n return res\n}",
"function repeatStringNumTimes(string, times) {\n// Create an empty string to host the repeated string\nvar repeatedString = \"\";\n//Step 2, set the while loop with (times > 0) as the condition to check\nwhile (times > 0) { //as long as times is greater than 0, statement is executed\n repeatedString += string; // repeatedString = repeatedString + string;\n times-- ;\n}\n\n// Step 3 return the repeated String\nreturn repeatedString;\n}",
"function limitWidth(string, len) {\n var lines = string.split('\\n');\n len = (typeof len === 'number') ? len : 80;\n var chars;\n for (var i = 0; i < lines.length; i++) {\n if (lines[i].length > len) {\n chars = lines[i].split('');\n lines[i] = lines[i].slice(0, len - 1);\n lines.splice(i + 1, 0, chars.slice(len - 1).join(''));\n }\n }\n return lines.join('\\n');\n}",
"function padEnd(str,num, pad){\n if (num < str.length) return str;\n if (str.length < num){\n if (arguments.length === 3){\n let diff = Math.ceil((num-str.length)/pad.length);\n for (let i = 0; i < diff; i++){\n str += pad;\n }\n }\n else if ( arguments.length === 2) {\n let diff2 = num-str.length;\n for (let k = 0; k < diff2; k++){\n str += \" \";\n }\n }\n }\n \n if (str.length > num) str = str.slice(0,num);\n return str;\n}",
"function shorten(str) {\n // Don't shorten if adding the ... wouldn't make the string shorter\n if (!str || str.length < 10) {\n return str;\n }\n return `${str.substr(0, 3)}...${str.slice(-3)}`;\n}",
"function repetition(txt, n) {\n return txt.repeat(n);\n}",
"function repeat(input, n){\n var output = ''\n for(var i = 0; i < n; i++){\n output = output + input\n }\n return output\n }",
"static Repeat(value, length) {\n return value - Math.floor(value / length) * length;\n }",
"function makeStr(str) {\n\tif(str.length <= 35){\n\t\treturn str;\n\t} else {\n\t\tvar index = 35;\n\t\twhile(index >= 0) {\n\t\t\tif(str.charAt(index) === \" \") {\n\t\t\t\treturn str.substr(0, index+1) + \"...\";\n\t\t\t} else {\n\t\t\t\tindex--;\n\t\t\t}\n\t\t}\n\t\treturn str.substr(0, 36) + \" ...\";\n\t}\n}",
"function non_repeat_substring(str) {\n let windowStart = 0;\n let maxLength = 0;\n let charIndexMap = {};\n\n // try to extend the range [windowStart, windowEnd]\n for (let windowEnd = 0; windowEnd < str.length; windowEnd++) {\n const rightChar = str[windowEnd];\n // if the map already contains the 'rightChar', shrink the window from the beginning so that\n // we have only one occurrence of 'rightChar'\n if (rightChar in charIndexMap) {\n // this is tricky; in the current window, we will not have any 'rightChar' after its previous index\n // and if 'windowStart' is already ahead of the last index of 'rightChar', we'll keep 'windowStart'\n windowStart = Math.max(windowStart, charIndexMap[rightChar] + 1);\n }\n // insert the 'rightChar' into the map\n charIndexMap[rightChar] = windowEnd;\n // remember the maximum length so far\n maxLength = Math.max(maxLength, windowEnd - windowStart + 1);\n }\n return maxLength;\n}",
"function concat(string, n) {\n n = n || 1;\n var con = '';\n for (var i = 0; i < n; i++) {\n con += string;\n }\n return con;\n}",
"function truncateString(str, length) {\n if(length >= str.length) return str\n else if(length <= 3) return str.slice(0, length) + '...'\n return str.slice(0, length - 3) + '...'\n}",
"buildReplacement(character, length) {\n let replacement = '';\n for (let i = 0; i < length; i++) {\n replacement += character;\n }\n return replacement;\n }",
"static chopRight(string, length) {\r\n\t\treturn string.slice(0, string.length - length);\r\n\t}",
"function pad (str) {\n \"use strict\";\n var max = 0;\n\n for (var i = 0, l = levels.length; i < l; i++)\n max = Math.max(max, levels[i].length);\n\n if (str.length < max)\n return str + new Array(max - str.length + 1).join(' ');\n\n return str;\n}",
"function buildRandomString(length) {\n //declare and initialize a string of the alphabet caracters\n var alphabet = 'abcdefghijklmnopqrstuvwxyz';\n //declare an empty result string\n var resultString = '';\n //REPEAT length times\n for (var i = 0; i <length; i++) {\n //add a random character to the result string\n resultString += alphabet[Math.round(Math.random() * (alphabet.length - 1))];\n }\n //return the result string\n return resultString;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
When another player gets a coin it removes the coin for all players. | function removeCoin(coin_id){
for (let i = 0 ; i < coinObjects.length ; i++){
let coin = coinObjects[i]
if (coin.coin_id == coin_id){
coin.is_dead = true;
}
}
} | [
"takeCoin(player, coin){\n coin.kill();\n }",
"function collectCoin(player, Coin){\n \tCoinPU.play();\n Coin.kill();\n coinsCollected+=1;\n }",
"'players.reduceVentureCoins'(num_coins){\n var current_coins = Players.findOne({'owner': Meteor.userId()}).goldCoin;\n if(current_coins < num_coins){\n return false;\n }\n \n Players.update(\n { 'owner': Meteor.userId()},\n { $inc:{'goldCoin': -1 * num_coins}}\n );\n return true;\n }",
"die() {\n this.dieSfx.play('die');\n this.scene.time.delayedCall(6000, (sounds)=> {\n sounds.forEach( (sound) => {\n sound.destroy();\n })\n }, [[this.dieSfx, this.takeDamageSfx, this.dealDamageSfx, this.shoutSfx]]);\n for(let i = this.minCoins; i < Math.random() * this.maxCoins + this.minCoins; i++) {\n let coin = new GameCoin({scene:this.scene, x:this.x, y:this.y});\n coin.body.setVelocityX(Math.random() * 100 - 50);\n coin.body.setVelocityY(Math.random() * 100 - 50);\n }\n if(this.nextMoveEvent) {\n this.nextMoveEvent.destroy();\n }\n if(this.senseEvents) {\n this.senseEvents.forEach( (event)=> {\n event.destroy();\n });\n }\n dataManager.emitter.emit(\"enemyDied\");\n this.destroy();\n }",
"function clearTable(){\n playerNode = document.getElementById(\"player-hand\");\n dealerNode = document.getElementById(\"dealer-hand\");\n if (playerNode.hasChildNodes()){\n while (playerNode.firstChild){\n playerNode.removeChild(playerNode.firstChild);\n };\n while (dealerNode.firstChild){\n dealerNode.removeChild(dealerNode.firstChild);\n };\n };\n document.getElementById(\"messages\").innerHTML = \"Pick the bet amount\";\n }",
"function prune()\n{\n for (i = 0; i < lobbies.length; i += 1)\n {\n if (lobbies[i].players.length == 0)\n {\n lobbies.splice(i, 1);\n i -= 1;\n }\n }\n}",
"async function remove() {\n const x = await Pair.find({ gpu: 'GeForce RTX 2070 Super' });\n for (pair of x) {\n for (let i = 0; i < pair.priceHistory.length; i++) {\n if (pair.priceHistory[i].price > pair.priceHistory[pair.priceHistory.length - 1].price + 200) {\n pair.priceHistory.splice(i, 1);\n pair.save();\n }\n }\n }\n}",
"clear() {\n this._players = [];\n }",
"handleUnstakingEvents() {\n // Updating locked gold balances if the locking time has elapsed.\n if (this.unstakingEvents.has(this.chainLength)) {\n let q = this.unstakingEvents.get(this.chainLength);\n q.forEach(({clientID, amount}) => {\n let totalStaked = this.stakeBalances.get(clientID);\n console.log(`Unstaking ${totalStaked} for ${clientID}`);\n this.stakeBalances.set(clientID, totalStaked - amount);\n });\n\n // No longer need to track these locking events.\n this.unstakingEvents.delete(this.chainLength);\n }\n }",
"onPlayerDisconnect(player) {\n this.restoreDefaultPlayerStatus(player);\n this.playerStats_.delete(player);\n }",
"function removeInvestment (symbol) {\n portfolio = portfolio.filter(item => item.symbol !== symbol)\n // blacklist.push(symbol) //\n buying = true\n}",
"function removeGame() {\n\t//todo: add formal message telling client other player disconnected\n\tsocket.emit('delete game', gameID);\n\tclient.fleet = ['temp2', 'temp3', 'temp4', 'temp5'];\n\tenemyFleet = new Array(4);\n\tclient.clearGrids();\n\tsocket.off(gameID + ' player disconnect');\t\n\tgameID = -1;\n\tprepWindow = -1;\n\tpositionWindow = -1;\n\tplayWindow = -1;\n}",
"removeBike(bike) {\n //Removes bike from basket\n for (let i of basket) {\n if (bike == i) {\n this.totalPrice -= basket[basket.indexOf(i)].displayPrice;\n basket.splice(basket.indexOf(i), 1);\n shared.basketLength = basket.length;\n this.updateBasket();\n this.calcDiscount();\n }\n }\n\n //Removes all equipment belong to bike with it\n for (var i = 0; equipmentBasket.length > i; i++) {\n if (equipmentBasket[i].bike_id == bike.id) {\n equipmentBasket.splice(i, 1);\n this.totalPrice -= equipmentBasket[i].displayPrice;\n i--;\n }\n }\n }",
"function resetTurn() {\n playerBet = 0;\n}",
"function RemoveUpgrade(){\n\tplayer.upgraded = false;\n\tplayer.sprite =Sprite(currentActivePlayer);\n}",
"onDisconnect(client){\n\t\tthis.clients.splice(this.clients.indexOf(client),1);\n\t\tif(this.player1 == client) this.player1 = null;\n\t\tif(this.player2 == client) this.player2 = null;\n\t\tif(this.player1 == null || this.player2 == null){\n\t\t\tGame.reset();\n\t\t\tthis.broadcastStatus();\n\t\t}\n\t}",
"function stayPlay(){ \n // Turn off the hit and stay buttons\n hitHand.removeEventListener('click', hitPlay);\n stayHand.removeEventListener('click',stayPlay);\n // Function that checks if dealer should hit or stay\n updateDlrHnd();\n // Function that checks who wins the game\n checkWinner();\n}",
"function Cleanup_Entities() {\n\tfor(var k in game.ents) {\n\t\tif(game.ents[k].remove) {\n\t\t\t// Entity should clean up its own game.ents index when remove is called\n\n\t\t\t// It's important not to forcably remove from game.ents in case \n\t\t\t// to do a cleanup for some reason after its removal is signaled\n\t\t\tgame.ents[k].remove();\n\t\t}\n\t}\n\t// Remove player data structures\n\tfor(var k in game.clients) {\n\t\tdelete game.clients[k];\n\t\tFireEvent('player_leave',{userId: k});\n\t}\n\tgame.async = {};\n}",
"disbandTeam(teamName) {\n this.entrants.forEach((entrant) => {\n if (entrant.team === teamName) {\n entrant.team = \"\";\n }\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Chapter 101 RopeGroup Knot reponsise when chaste | function C101_KinbakuClub_RopeGroup_HelplessKnot() {
if (Common_PlayerChaste) OverridenIntroText = GetText("ChasteKnot");
if (C101_KinbakuClub_RopeGroup_CurrentStage == 830) C101_KinbakuClub_RopeGroup_WaitingForMistress();
else C101_KinbakuClub_RopeGroup_HelplessTime();
} | [
"function C101_KinbakuClub_RopeGroup_HelplessStruggle() {\n\tif (Common_PlayerChaste) OverridenIntroText = GetText(\"ChasteStruggle\");\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 830) C101_KinbakuClub_RopeGroup_WaitingForMistress();\n\telse C101_KinbakuClub_RopeGroup_HelplessTime();\n}",
"function C101_KinbakuClub_RopeGroup_WillLucyTie() {\n\tif (ActorGetValue(ActorLove) >= 3 || ActorGetValue(ActorSubmission) >= 2) {\n\t\tOverridenIntroText = GetText(\"LucyNotTieYou\");\n\t\tC101_KinbakuClub_RopeGroup_CurrentStage = 600;\n\t} else C101_KinbakuClub_RopeGroup_PlayerTied();\n}",
"function C101_KinbakuClub_RopeGroup_PlayerWhimperLucy() {\n\tif (C101_KinbakuClub_RopeGroup_LucyIsAnnoyed <= 0) {\n\t\tPlayerUngag();\n\t\tActorChangeAttitude( 1, -1)\n\t} else {\n\t\tif (C101_KinbakuClub_RopeGroup_LucyIsAnnoyed >= 2 || ActorGetValue(ActorLove) >= 1) {\n\t\t\tOverridenIntroText = GetText(\"AnnoyedNoUngag\");\n\t\t\tC101_KinbakuClub_RopeGroup_CurrentStage = 640;\n\t\t} else {\n\t\t\tPlayerUngag();\n\t\t\tOverridenIntroText = GetText(\"AnnoyedUngag\");\n\t\t}\n\t}\n}",
"function C101_KinbakuClub_RopeGroup_PluggedHappily() {\n\tC101_KinbakuClub_RopeGroup_PlugMood = \"Happily\";\n\tC101_KinbakuClub_RopeGroup_PlayerPlugged();\n}",
"function C101_KinbakuClub_RopeGroup_CassiContinue() {\n\tActorAddOrgasm();\n\tC101_KinbakuClub_RopeGroup_PlayerArousal = C101_KinbakuClub_RopeGroup_PlayerArousal - 200;\n\tC101_KinbakuClub_RopeGroup_ForcingCassi = false;\n\tC101_KinbakuClub_RopeGroup_PressingCassi = false;\n\tC101_KinbakuClub_RopeGroup_CanPressCassi = true;\n\tif (ActorGetValue(ActorLove) <= 2) {\n\t\tC101_KinbakuClub_RopeGroup_CurrentStage = 686;\n\t\tif (ActorHasInventory(\"Cuffs\")) {\n\t\t\tOverridenIntroText = GetText(\"CassiDoneUnCuff\");\n\t\t\tActorRemoveInventory(\"Cuffs\");\n\t\t} else OverridenIntroText = GetText(\"CassiDone\");\n\t} else {\n\t\tC101_KinbakuClub_RopeGroup_OrgasmCount++\n\t\tif (C101_KinbakuClub_RopeGroup_OrgasmCount >= 2) {\n\t\t\tC101_KinbakuClub_RopeGroup_AnkleGrab = false;\n\t\t\tC101_KinbakuClub_RopeGroup_fingerinsertion = false;\n\t\t\tC101_KinbakuClub_RopeGroup_CurrentStage = 685;\n\t\t\tOverridenIntroText = GetText(\"CassiAsks\");\n\t\t}\n\t}\n}",
"function C101_KinbakuClub_RopeGroup_SafeWord() {\n\tC101_KinbakuClub_RopeGroup_Guessing = true;\n\tC101_KinbakuClub_RopeGroup_HeatherTugging = false;\n}",
"function C101_KinbakuClub_RopeGroup_AddedExtras(ExtraNumber) {\n\tif (ExtraNumber == 1 && ActorGetValue(ActorSubmission) >= 3) {\n\t\tOverridenIntroText = GetText(\"NotBelted\");\n\t\tC101_KinbakuClub_RopeGroup_PlayerFreed()\n\t\tC101_KinbakuClub_RopeGroup_CurrentStage = 691;\n\t} else {\n\t\tif (!PlayerHasLockedInventory(\"VibratingEgg\") && !PlayerHasLockedInventory(\"ButtPlug\")) {\n\t\t\tPlayerLockInventory(\"VibratingEgg\");\n\t\t\tPlayerLockInventory(\"ButtPlug\");\n\t\t} else {\n\t\t\tif (!PlayerHasLockedInventory(\"VibratingEgg\")) {\n\t\t\t\tPlayerLockInventory(\"VibratingEgg\");\n\t\t\t\tif (ExtraNumber == 1) OverridenIntroText = GetText(\"ArgueEggNBelted\");\n\t\t\t\telse OverridenIntroText = GetText(\"EggNBelted\");\n\t\t\t} else {\n\t\t\t\tif (!PlayerHasLockedInventory(\"ButtPlug\")) {\n\t\t\t\t\tPlayerLockInventory(\"ButtPlug\");\n\t\t\t\t\tif (ExtraNumber == 1) OverridenIntroText = GetText(\"ArguePlugNBelted\");\n\t\t\t\t\telse OverridenIntroText = GetText(\"PlugNBelted\");\n\t\t\t\t} else {\n\t\t\t\t\tif (ExtraNumber == 1) OverridenIntroText = GetText(\"ArgueJustBelted\");\n\t\t\t\t\telse OverridenIntroText = GetText(\"JustBelted\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tC101_KinbakuClub_RopeGroup_FullyExposed = false;\n\t\tPlayerLockInventory(\"ChastityBelt\");\n\t}\n}",
"function PrisonCatchKneelingEscape() {\n\tCharacterSetActivePose(Player, null, true);\n\tInventoryWear(Player, \"Chains\", \"ItemArms\", \"Default\", 3);\n\tInventoryGet(Player, \"ItemArms\").Property = { Type: \"Hogtied\", SetPose: [\"Hogtied\"], Difficulty: 0, Block: [\"ItemHands\", \"ItemLegs\", \"ItemFeet\", \"ItemBoots\"], Effect: [\"Block\", \"Freeze\", \"Prone\"] };\n\tCharacterRefresh(Player);\n\tPrisonPolice.Stage = \"CatchAggressive5\";\n\tPrisonPolice.CurrentDialog = DialogFind(PrisonPolice, \"CatchAggressiveFailedEscape\");\n}",
"function C101_KinbakuClub_RopeGroup_ReleaseTwin() {\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 400) C101_KinbakuClub_RopeGroup_LeftTwinStatus = \"Released\";\n\telse C101_KinbakuClub_RopeGroup_RightTwinStatus = \"Released\";\n\tif (ActorGetValue(ActorName) == \"Lucy\") C101_KinbakuClub_RopeGroup_LucyFree = true;\n\tC101_KinbakuClub_RopeGroup_CurrentStage = 700;\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 C101_KinbakuClub_RopeGroup_PluggedPanic() {\n\tC101_KinbakuClub_RopeGroup_PlugMood = \"Panic\";\n\tC101_KinbakuClub_RopeGroup_PlayerPlugged();\n}",
"function C101_KinbakuClub_RopeGroup_Run() {\n\tBuildInteraction(C101_KinbakuClub_RopeGroup_CurrentStage);\n\t\n\t// changing images\n\t// Group view\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 100) {\n\t\tDrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RopeGroupAmelia.png\", 600, 20);\n\t\tDrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RopeGroupCharlotte.jpg\", 818, 0);\n\t\tif (C101_KinbakuClub_RopeGroup_LeftTwinStatus == \"StartTied\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RopeGroupTwinLeftStart.png\", 985, 98);\n\t\tif (C101_KinbakuClub_RopeGroup_LeftTwinStatus == \"Released\" || C101_KinbakuClub_RopeGroup_RightTwinStatus == \"Released\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RopeGroupTwinFree.png\", 1005, 0);\n\t\tif (C101_KinbakuClub_RopeGroup_RightTwinStatus == \"StartTied\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RopeGroupTwinRightStart.png\", 847, 110);\n\t}\n\n\t// Twins image after releasing one of them\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 430) {\n\t\tif (C101_KinbakuClub_RopeGroup_LeftTwin == \"Lucy\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/LeftTwin.jpg\", 600, 0);\n\t\telse DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RightTwin.jpg\", 600, 0);\n\t}\n\tif ((C101_KinbakuClub_RopeGroup_CurrentStage >= 600 && C101_KinbakuClub_RopeGroup_CurrentStage <= 631) || (C101_KinbakuClub_RopeGroup_CurrentStage >= 700 && C101_KinbakuClub_RopeGroup_CurrentStage <= 710) || C101_KinbakuClub_RopeGroup_CurrentStage == 900) {\n\t\tif (C101_KinbakuClub_RopeGroup_LeftTwinStatus == \"StartTied\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/TwinLeftStillTied.png\", 600, 167);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage <= 700) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/TwinJustReleased.png\", 750, 5);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage >= 710) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/TwinReleased.png\", 750, 5);\n\t\tif (C101_KinbakuClub_RopeGroup_RightTwinStatus == \"StartTied\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/TwinRightStillTied.png\", 930, 230);\n\t}\n\n\t// During Tsuri Kinbaku (Suspension)\n\t// Suspended1\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 633) {\n\t\tif (PlayerHasLockedInventory(\"BallGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended1BallGag.jpg\", 878, 94);\n\t\tif (PlayerHasLockedInventory(\"ClothGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended1ClothGag.jpg\", 878, 94);\n\t}\n\t// Suspended2\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 634) {\n\t\tif (PlayerHasLockedInventory(\"BallGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended2BallGag.jpg\", 904, 105);\n\t\tif (PlayerHasLockedInventory(\"ClothGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended2ClothGag.jpg\", 904, 105);\n\t}\n\t// Suspended3\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 635) {\n\t\tif (PlayerHasLockedInventory(\"BallGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended3BallGag.jpg\", 890, 105);\n\t\tif (PlayerHasLockedInventory(\"ClothGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended3ClothGag.jpg\", 890, 105);\n\t}\n\t// Suspended4\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage >= 636 && C101_KinbakuClub_RopeGroup_CurrentStage <= 660) {\n\t\tif (PlayerHasLockedInventory(\"BallGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended4BallGag.jpg\", 863, 125);\n\t\tif (PlayerHasLockedInventory(\"ClothGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended4ClothGag.jpg\", 863, 125);\n\t}\n\t// Suspended5\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage >= 661 && C101_KinbakuClub_RopeGroup_CurrentStage <= 662) {\n\t\tif (PlayerHasLockedInventory(\"BallGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended5BallGag.jpg\", 865, 126);\n\t\tif (PlayerHasLockedInventory(\"ClothGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended5ClothGag.jpg\", 865, 126);\n\t\tif (PlayerHasLockedInventory(\"TapeGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended5TapeGag.jpg\", 865, 126);\n\t}\n\n\t//Suspended\n\tif ((C101_KinbakuClub_RopeGroup_CurrentStage >= 636 && C101_KinbakuClub_RopeGroup_CurrentStage <= 642) || (C101_KinbakuClub_RopeGroup_CurrentStage >= 650 && C101_KinbakuClub_RopeGroup_CurrentStage <= 690)) {\n\t\t// Player images\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage >= 672 && C101_KinbakuClub_RopeGroup_PlayerPose != \"\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/\" + C101_KinbakuClub_RopeGroup_PlayerPose + \".jpg\", 835, 75);\n\t\tif (PlayerHasLockedInventory(\"ChastityBelt\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended4ChastityBelt.jpg\", 880, 290);\n\t\tif (C101_KinbakuClub_RopeGroup_TsuriFrogTied) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended5FrogTie.png\", 769, 231);\n\t\tif (C101_KinbakuClub_RopeGroup_FullyExposed) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended5Pantieless.jpg\", 880, 294);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 662) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended5LookUp.png\", 864, 136);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 671 && PlayerHasLockedInventory(\"SockGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended8S.jpg\", 888, 157);\n\t\t\n\t\t// Cassi iamges\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 662) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended5Cassi1.png\", 948, 65);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 666) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_InspectBelt.jpg\", 842, 72);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 667) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_InspectKey.jpg\", 842, 72);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 668) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_RemovingBelt.jpg\", 842, 72);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 672) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_LeftHoldingTape.jpg\", 608, 70);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 673) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_Scissors.png\", 700, 77);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 674) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_KneelDown.png\", 660, 120);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 674 && ActorGetValue(ActorSubmission) >= 0) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_KneelDownCuffs.png\", 776, 403);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage >= 675 && C101_KinbakuClub_RopeGroup_CurrentStage <= 686){\n\t\t\tif (C101_KinbakuClub_RopeGroup_PressingCassi) {\n\t\t\t\tif (ActorHasInventory(\"Cuffs\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_CunniCuffedPressed.png\", 770, 230);\n\t\t\t\telse {\n\t\t\t\t\tif (C101_KinbakuClub_RopeGroup_fingerinsertion) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_CunniFingerPressed.png\", 770, 230);\n\t\t\t\t\telse DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_CunniPressed.png\", 770, 230);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (C101_KinbakuClub_RopeGroup_ForcingCassi) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_CunniCuffedStruggle.png\", 770, 230);\n\t\t\t\telse {\n\t\t\t\t\tif (C101_KinbakuClub_RopeGroup_AnkleGrab) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_CunniAnkleHold.png\", 770, 230);\n\t\t\t\t\telse {\n\t\t\t\t\t\tif (ActorHasInventory(\"Cuffs\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_CunniCuffed.png\", 825, 251);\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tif (C101_KinbakuClub_RopeGroup_fingerinsertion) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_CunniFinger.png\", 825, 251);\n\t\t\t\t\t\t\telse DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_Cunni.png\", 825, 251);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 687) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_Done.png\", 835, 73);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 687 && ActorHasInventory(\"Cuffs\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_DoneCuffs.png\", 874, 193);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage >= 688 && C101_KinbakuClub_RopeGroup_CurrentStage <= 689) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_DoneBelt.png\", 835, 63);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 690) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_DoneBelted.png\", 835, 66);\n\t\t\n\n\t\t// Lucy images\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage >= 662 && C101_KinbakuClub_RopeGroup_CurrentStage <= 665) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended5Lucy.png\", 629, 51);\n\t\t\n\t\t// Player arousal\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage >= 675 && C101_KinbakuClub_RopeGroup_CurrentStage <= 680) {\n\t\t\tif (C101_KinbakuClub_RopeGroup_PreviousTime == 0) C101_KinbakuClub_RopeGroup_PreviousTime = CurrentTime;\n\t\t\tif (CurrentTime > (C101_KinbakuClub_RopeGroup_PreviousTime + 1000)) {\n\t\t\t\tC101_KinbakuClub_RopeGroup_PreviousTime = CurrentTime;\n\t\t\t\tC101_KinbakuClub_RopeGroup_PlayerArousal++;\n\t\t\t\tif (ActorGetValue(ActorSubmission) < 0) C101_KinbakuClub_RopeGroup_PlayerArousal++;\n\t\t\t\tif (PlayerHasLockedInventory(\"VibratingEgg\")) C101_KinbakuClub_RopeGroup_PlayerArousal++;\n\t\t\t}\n\t\t\tif (C101_KinbakuClub_RopeGroup_PlayerArousal > 500) {\n\t\t\t\tC101_KinbakuClub_RopeGroup_PlayerArousal = 500;\n\t\t\t\tC101_KinbakuClub_RopeGroup_CurrentStage = 681\n\t\t\t\tOverridenIntroText = GetText(\"SuspendedOrgasm\");\n\t\t\t}\n\t\t}\n\t\t// Draw the players arousal level\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage >= 675 && C101_KinbakuClub_RopeGroup_CurrentStage <= 681) {\n\t\t\tDrawRect(638, 48, 14, 504, \"white\");\n\t\t\tDrawRect(640, 50, 10, (500 - C101_KinbakuClub_RopeGroup_PlayerArousal), \"#66FF66\");\n\t\t\tDrawRect(640, (550 - C101_KinbakuClub_RopeGroup_PlayerArousal), 10, C101_KinbakuClub_RopeGroup_PlayerArousal, \"red\");\n\t\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 300) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Gushing.png\", 601, 2);\n\t\t}\n\t}\n\t\n\t// Images when Hether uses nipple clamps\n\tif ((C101_KinbakuClub_RopeGroup_CurrentStage >= 800 && C101_KinbakuClub_RopeGroup_CurrentStage <= 841) || C101_KinbakuClub_RopeGroup_CurrentStage == 850) {\n\t\tif (C101_KinbakuClub_RopeGroup_NipplesExposed) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/WithHeatherExposed.jpg\", 600, 0);\n\t\tif (C101_KinbakuClub_RopeGroup_NippleClamped) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/WithHeatherNippleClamped.jpg\", 600, 0);\n\t\tif (C101_KinbakuClub_RopeGroup_HeatherTugging) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/WithHeatherNippleTug.jpg\", 600, 0);\n\t\tif (!C101_KinbakuClub_RopeGroup_Expression == \"\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/\" + C101_KinbakuClub_RopeGroup_Expression + \".jpg\", 1040, 280);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 830) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/HeatherGone.jpg\", 600, 392);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 841) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/JennaIntervene.jpg\", 600, 0);\n\t}\n\n\t// Images during plug play\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 854 && C101_KinbakuClub_RopeGroup_Clentched) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/PluggingClentch.jpg\", 617, 354);\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 855) {\n\t\tDrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Plugged.jpg\", 900, 110);\n\t\tDrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Plugged\" + C101_KinbakuClub_RopeGroup_PlugMood + \".jpg\", 617, 354);\n\t}\n}",
"function C101_KinbakuClub_RopeGroup_Run() {\n\tBuildInteraction(C101_KinbakuClub_RopeGroup_CurrentStage);\n\t\n\t// changing images\n\t// Group view\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 100) {\n\t\tDrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RopeGroupAmelia.png\", 600, 20);\n\t\tDrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RopeGroupCharlotte.jpg\", 818, 0);\n\t\tif (C101_KinbakuClub_RopeGroup_LeftTwinStatus == \"StartTied\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RopeGroupTwinLeftStart.png\", 985, 98);\n\t\tif (C101_KinbakuClub_RopeGroup_LeftTwinStatus == \"Released\" || C101_KinbakuClub_RopeGroup_RightTwinStatus == \"Released\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RopeGroupTwinFree.png\", 1005, 0);\n\t\tif (C101_KinbakuClub_RopeGroup_RightTwinStatus == \"StartTied\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RopeGroupTwinRightStart.png\", 847, 110);\n\t}\n\n\t// Twins image after releasing one of them\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 430) {\n\t\tif (C101_KinbakuClub_RopeGroup_LeftTwin == \"Lucy\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/LeftTwin.jpg\", 600, 0);\n\t\telse DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RightTwin.jpg\", 600, 0);\n\t}\n\tif ((C101_KinbakuClub_RopeGroup_CurrentStage >= 600 && C101_KinbakuClub_RopeGroup_CurrentStage <= 631) || (C101_KinbakuClub_RopeGroup_CurrentStage >= 700 && C101_KinbakuClub_RopeGroup_CurrentStage <= 710) || C101_KinbakuClub_RopeGroup_CurrentStage == 900) {\n\t\tif (C101_KinbakuClub_RopeGroup_LeftTwinStatus == \"StartTied\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/TwinLeftStillTied.png\", 600, 167);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage <= 700) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/TwinJustReleased.png\", 750, 5);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage >= 710) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/TwinReleased.png\", 750, 5);\n\t\tif (C101_KinbakuClub_RopeGroup_RightTwinStatus == \"StartTied\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/TwinRightStillTied.png\", 930, 230);\n\t}\n\n\t// Images during Tsuri Kinbaku (Suspension)\n\t// Suspended1\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 633) {\n\t\tif (PlayerHasLockedInventory(\"BallGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended1BallGag.jpg\", 878, 94);\n\t\tif (PlayerHasLockedInventory(\"ClothGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended1ClothGag.jpg\", 878, 94);\n\t}\n\t// Suspended2\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 634) {\n\t\tif (PlayerHasLockedInventory(\"BallGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended2BallGag.jpg\", 904, 105);\n\t\tif (PlayerHasLockedInventory(\"ClothGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended2ClothGag.jpg\", 904, 105);\n\t}\n\t// Suspended3\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 635) {\n\t\tif (PlayerHasLockedInventory(\"BallGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended3BallGag.jpg\", 890, 105);\n\t\tif (PlayerHasLockedInventory(\"ClothGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended3ClothGag.jpg\", 890, 105);\n\t}\n\t// Suspended4\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 636) {\n\t\tif (PlayerHasLockedInventory(\"BallGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended4BallGag.jpg\", 863, 125);\n\t\tif (PlayerHasLockedInventory(\"ClothGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended4ClothGag.jpg\", 863, 125);\n\t\tif (PlayerHasLockedInventory(\"ChastityBelt\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended4ChastityBelt.jpg\", 880, 290);\n\t}\n\t\n\t// Images when Hether uses nipple clamps\n\tif ((C101_KinbakuClub_RopeGroup_CurrentStage >= 800 && C101_KinbakuClub_RopeGroup_CurrentStage <= 841) || C101_KinbakuClub_RopeGroup_CurrentStage == 850) {\n\t\tif (C101_KinbakuClub_RopeGroup_NipplesExposed) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/WithHeatherExposed.jpg\", 600, 0);\n\t\tif (C101_KinbakuClub_RopeGroup_NippleClamped) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/WithHeatherNippleClamped.jpg\", 600, 0);\n\t\tif (C101_KinbakuClub_RopeGroup_HeatherTugging) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/WithHeatherNippleTug.jpg\", 600, 0);\n\t\tif (!C101_KinbakuClub_RopeGroup_Expression == \"\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/\" + C101_KinbakuClub_RopeGroup_Expression + \".jpg\", 1040, 280);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 830) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/HeatherGone.jpg\", 600, 392);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 841) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/JennaIntervene.jpg\", 600, 0);\n\t}\n\n\t// Images during plug play\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 854 && C101_KinbakuClub_RopeGroup_Clentched) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/PluggingClentch.jpg\", 617, 354);\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 855) {\n\t\tDrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Plugged.jpg\", 900, 110);\n\t\tDrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Plugged\" + C101_KinbakuClub_RopeGroup_PlugMood + \".jpg\", 617, 354);\n\t}\n}",
"function C101_KinbakuClub_RopeGroup_StruggleForLucy() {\n\tif (!C101_KinbakuClub_RopeGroup_StruggledForLucy) ActorChangeAttitude( 1, -1)\n\tC101_KinbakuClub_RopeGroup_StruggledForLucy = true;\n}",
"function C101_KinbakuClub_RopeGroup_PluggedAccept() {\n\tC101_KinbakuClub_RopeGroup_PlugMood = \"Accept\";\n\tC101_KinbakuClub_RopeGroup_PlayerPlugged();\n}",
"function C006_Isolation_Yuki_AddRope() {\n\tPlayerClothes(\"Underwear\");\n\tPlayerLockInventory(\"Rope\");\n}",
"function PrisonFightPoliceEnd() {\n\tCommonSetScreen(\"Room\", \"Prison\");\n\tSkillProgress(\"Willpower\", ((Player.KidnapMaxWillpower - Player.KidnapWillpower) + (PrisonPolice.KidnapMaxWillpower - PrisonPolice.KidnapWillpower)) * 2);\n\tif (!KidnapVictory) {\n\t\tCharacterRelease(PrisonPolice);\n\t\tInventoryRemove(PrisonPolice, \"ItemNeck\");\n\t\tPrisonWearPoliceEquipment(PrisonPolice);\n\t\tPrisonPolice.CurrentDialog = DialogFind(PrisonPolice, \"CatchDefeat\");\n\t\tPrisonPolice.Stage = \"Catch\";\n\t}else{\n\t\tPrisonPolice.CurrentDialog = DialogFind(PrisonPolice, \"CatchVictoryIntro\");\n\t\tPrisonPolice.Stage = \"CatchVictory\";\n\t}\n\tCharacterSetCurrent(PrisonPolice);\n}",
"handleEatingClue(clue) {\n // Calculate distance from this predator to the prey\n let d = dist(this.x, this.y, clue.x, clue.y);\n // Check if the distance is less than their two radii (an overlap)\n if (d < (this.radius + clue.radius) && clue.isAlive === true) {\n timeToGrowPower = 0;\n // Increase predator health and constrain it to its possible range\n this.health += this.healthGainPerEat;\n this.health = constrain(this.health, 0, this.maxHealth);\n //update the clues caught score if its not alive anymore\n this.cluesCaught += 1;\n itemCaughtSound.play(); //plays the catch sound when someone gets caught by spies\n clue.isAlive = false; //the clue is not alive anymore\n }\n }",
"function PunishmentCheck() {\r\n // We check if a restraint is invalid\r\n for (let i = cursedConfig.punishmentRestraints.length - 1; i >= 0; i--) {\r\n if (!Asset.find(A => A.Name === cursedConfig.punishmentRestraints[i].name && A.Group.Name === cursedConfig.punishmentRestraints[i].group)) {\r\n delete cursedConfig.punishmentRestraints[i];\r\n popChatSilent({ Tag: \"ErrorInvalidPunishment\"}, \"System\");\r\n }\r\n }\r\n\r\n cursedConfig.punishmentRestraints = cursedConfig.punishmentRestraints.filter(PR => PR);\r\n\r\n // Check if we need to punish\r\n const difference = cursedConfig.strikes - cursedConfig.lastPunishmentAmount;\r\n const stageFactor = cursedConfig.strictness * 15;\r\n let r = false;\r\n if (difference > stageFactor && !cursedConfig.punishmentsDisabled) {\r\n //More restraints per stages, resets every week\r\n cursedConfig.punishmentRestraints.forEach(PR => {\r\n r = WearPunishment(PR.stage, PR.name, PR.group) || r;\r\n });\r\n if (r) {\r\n TryPopTip(41);\r\n SendChat({ Tag: \"PunishmentTriggered\"});\r\n }\r\n cursedConfig.lastPunishmentAmount = cursedConfig.strikes;\r\n }\r\n return r;\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the list of attributes. | getAttributeList() {
this.ensureParsed();
return this.attributes_;
} | [
"static get observedAttributes() {\n // note: piggy backing on this to ensure we're finalized.\n this.finalize();\n const attributes = [];\n // Use forEach so this works even if for/of loops are compiled to for loops\n // expecting arrays\n this._classProperties.forEach((v, p) => {\n const attr = this._attributeNameForProperty(p, v);\n if (attr !== undefined) {\n this._attributeToPropertyMap.set(attr, p);\n attributes.push(attr);\n }\n });\n return attributes;\n }",
"function getLdapAttributes(instance, _) {\n\tvar res = getAllUsers(instance, false, _);\n\tfor (var k in res) { // dummy loop: there can only be one key\n\t\treturn Object.keys(res[k]);\n\t}\n\treturn [];\n}",
"function listAttributes(data, selectedItem) {\n let _items = _.keys(data[0])\n let dropDown = d3.select(\"#attributes\");\n let options = dropDown.selectAll(\"a\")\n .data(_items)\n .enter()\n .append(\"a\")\n .attr(\"class\", \"waves-effect waves-light btn btn-block\")\n .attr(\"id\", _attr => _attr)\n .attr(\"href\", \"#\")\n .on('click', _attribute => {\n handleAttributeClick(_attribute, data);\n })\n .text(_d => {\n return _.truncate(_d, {length: 10})\n });\n d3.select(`#${selectedItem}`)\n .classed(\"disabled\", true)\n}",
"function getAttributes(node) {\n\n var attributes = {};\n\n for (var index = 0; index < node.attributes.length; index++) {\n // Extract the attribute name - checking for clashes with javaScript names.\n // Note that we also remove lara: which is used for the Customer attributes.\n var attributeName = checkForPropertyClash(node.attributes[index].nodeName.replace('gam:', '').replace('lara:', ''));\n\n // Store the attribute name and value in the attributes object.\n attributes[attributeName] = node.attributes[index].nodeValue;\n }\n\n return attributes;\n }",
"fetchAttributes() {\n let result = {};\n Object.values(this.attributes).map(attribute => {\n result[attribute.type] = Utility.getInstance().clone(attribute);\n })\n this.traits.map(trait => {\n Object.values(trait.fetchAttributes()).map(attribute => {\n result[attribute.type].add(attribute.get());\n })\n });\n return result;\n }",
"_getBasisFileAttributes(basisFile) {\r\n const width = basisFile.getImageWidth(0, 0);\r\n const height = basisFile.getImageHeight(0, 0);\r\n const images = basisFile.getNumImages();\r\n const levels = basisFile.getNumLevels(0);\r\n const has_alpha = basisFile.getHasAlpha();\r\n return { width, height, images, levels, has_alpha };\r\n }",
"getAttributes() {\n const animatedAttributes = {};\n\n for (const attributeName in this.transitions) {\n const transition = this.transitions[attributeName];\n\n if (transition.inProgress) {\n animatedAttributes[attributeName] = transition.attributeInTransition;\n }\n }\n\n return animatedAttributes;\n }",
"get index_attrs(){\n\t\treturn [...module.iter(this)] }",
"_getAttributes(elem, mandatory, optional=[]) {\n var res = {};\n for (let i = 0; i < mandatory.length; i++) {\n if (elem.hasAttribute(mandatory[i])) {\n let val = elem.getAttribute(mandatory[i]);\n res[mandatory[i]] = val;\n } else {\n return null;\n }\n }\n\n for (let i = 0; i < optional.length; i++) {\n if (elem.hasAttribute(optional[i])) {\n let val = elem.getAttribute(optional[i]);\n res[optional[i]] = val;\n }\n }\n\n return res;\n }",
"function attrsShouldReturnAttributes() {\n expect(element.attrs(fixture.el.firstElementChild))\n .toEqual({\n class: \"class\",\n id: \"id\"\n })\n}",
"permittedAttributes() {\n return Object.keys(schema.tables[this.getModelName()]);\n }",
"getActivitiesList() {\n return this.getDictionaryWordsList(ADLActivity);\n }",
"function attributeKeys(record) {\n return Object.keys(record).filter(function(key) {\n return key !== 'id' || key !== 'type';\n })\n}",
"function getSortedAttributes(attributes) {\n attributeKeys = Object.keys(attributes)\n attributeKeys.sort();\n if (attributeKeys.includes(\"dates of use\")) {\n // Set start, end, dates of use together\n addToEnd(attributeKeys, \"end date\");\n addToEnd(attributeKeys, \"dates of use\");\n addToEnd(attributeKeys, \"dates notes\");\n }\n\n return attributeKeys;\n}",
"function getAppAttributes(attrs, req, res) {\n if (typeof attrs === 'function') {\n attrs = attrs(req, res);\n }\n return attrs || {};\n }",
"function getProductTypeAttributes(client, productType){\n return client.productTypes.byId(productType).fetch().then(function(data){\n if (data && data.body.attributes) {\n return data.body.attributes;\n }\n });\n}",
"readAttributes() {\n this._previousValueState.state = this.getAttribute('value-state')\n ? this.getAttribute('value-state')\n : 'None';\n\n // save the original attribute for later usages, we do this, because some components reflect\n Object.keys(this._privilegedAttributes).forEach(attr => {\n if (this.getAttribute(attr) !== null) {\n this._privilegedAttributes[attr] = this.getAttribute(attr);\n }\n });\n }",
"newAttributes() {\n\t\treturn {\n\t\t\ttitle: this.$input.val().trim(),\n\t\t\torder: Todos.nextOrder(),\n\t\t\tcompleted: false\n\t\t};\n\t}",
"function allAttributesNamed(attrs, name) {\n var reg = new RegExp(\"^\" + name + \"($|_|\\\\()\");\n return attrs.filter(function(obj) {\n var attrName = obj.get('name');\n return reg.test(attrName);\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if given UUID is valid UUID | function TestUuid(uuid){
let pattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
let isValid = pattern.test(uuid);
return isValid;
} | [
"function isUuid(value) {\n if (typeof value === \"string\" && value.length === 36) {\n return !!value.match(UUID_PATT)\n }\n return false;\n }",
"function validateUUID(arg) {\n if (!arg) {\n console.error('Error: missing UUID');\n process.exit(1);\n }\n if (!UUID_REGEX.test(arg)) {\n console.error('Error: invalid UUID \"%s\"', arg);\n process.exit(1);\n }\n return arg;\n}",
"function IsValidGuid(guid) {\r\n var re = new RegExp(/^[{(]?[0-9A-F]{8}[-]?([0-9A-F]{4}[-]?){3}[0-9A-F]{12}[)}]?$/);\r\n return !guid || (guid !== '00000000-0000-0000-0000-000000000000' && re.test(guid.toUpperCase()));\r\n}",
"function isHex(value) {\n if (value.length == 0) return false;\n if (value.startsWith('0x') || value.startsWith('0X')) {\n value = value.substring(2);\n }\n let reg_exp = /^[0-9a-fA-F]+$/;\n if (reg_exp.test(value) && value.length % 2 == 0) {\n return true;\n } else {\n return false;\n }\n}",
"validateDmac() {\n let regex = /^[a-fA-F0-9]{4}\\.[a-fA-F0-9]{4}\\.[a-fA-F0-9]{4}$/;\n if (regex.test(this.state.dmac.replace(/^\\s+|\\s+$/g, \"\"))) return true;\n this.setState(\n {\n dmacError: true,\n },\n () => {\n return false;\n }\n );\n }",
"function isValidHexCode(str) {\n\treturn /^#[a-f0-9]{6}$/i.test(str);\n}",
"register_random_uuid(desc) {\n let res = randomUUID();\n this._magic.register('uuid', res, desc);\n return res;\n }",
"function uuid() {\n // get sixteen unsigned 8 bit random values\n const u = crypto.getRandomValues(new Uint8Array(16))\n\n // set the version bit to v4\n u[6] = (u[6] & 0x0f) | 0x40\n\n // set the variant bit to \"don't care\" (yes, the RFC\n // calls it that)\n u[8] = (u[8] & 0xbf) | 0x80\n\n // hex encode them and add the dashes\n let uid = ''\n uid += u[0].toString(16)\n uid += u[1].toString(16)\n uid += u[2].toString(16)\n uid += u[3].toString(16)\n uid += '-'\n\n uid += u[4].toString(16)\n uid += u[5].toString(16)\n uid += '-'\n\n uid += u[6].toString(16)\n uid += u[7].toString(16)\n uid += '-'\n\n uid += u[8].toString(16)\n uid += u[9].toString(16)\n uid += '-'\n\n uid += u[10].toString(16)\n uid += u[11].toString(16)\n uid += u[12].toString(16)\n uid += u[13].toString(16)\n uid += u[14].toString(16)\n uid += u[15].toString(16)\n\n return uid\n}",
"function isMAC48Address(inputString) {\n return !!inputString.match(/^[0-9A-F]{2}(-[0-9A-F]{2}){5}$/g);\n}",
"function checkIfValidMongoObjectID(str) {\n\t// regular expression to check if string is a valid MongoDB ObjectID\n\tconst regexExp = /^[0-9a-fA-F]{24}$/\n\n\treturn regexExp.test(str)\n}",
"function isHexPrefixed(str){return str.slice(0,2)==='0x';}",
"function validateFamilyId(family_id) {\n return family_id.match(/[A-Z]+\\d{8}-\\d{2}/);\n}",
"function checkAccessoryForDuplicateUUID( accessory, UUID )\n{\n // check for UUID+subtype conflict\n accessory.log.debug( `Checking ${ accessory.name } for Duplicate UUID: ${ accessory.UUID }` );\n\n for ( let existingAccessory in accessory.createdCmd4Accessories )\n {\n if ( UUID == existingAccessory.UUID )\n {\n // This is the same check as what is in \n // hap-nodejs/dist/lib/Accessory.js\n if ( accessory.service.subtype == existingAccessory.service.subtype )\n {\n accessory.log.error( chalk.red( `Error` ) + `: Cannot add a bridged Accessory with the same UUID as another bridged Accessory: ${ getAccessoryName( existingAccessory ) }` );\n\n if ( accessory.name == existingAccessory.name )\n accessory.log.error( chalk.red( `Duplicate accessory names can cause this issue.` ) );\n\n accessory.log.error( chalk.red( `It is wiser to define the second accessory in a different bridge.` ) );\n\n process.exit( 270 );\n }\n }\n // Check for duplicates in Added accessories.\n if ( accessory.addedAccessories && accessory.LEVEL == 0 )\n {\n accessory.accessories.forEach( ( addedAccessory ) =>\n {\n checkAccessoryForDuplicateUUID( addedAccessory, UUID );\n });\n }\n\n // Check for duplicates in Linked accessories.\n if ( accessory.linkedAccessories && accessory.LEVEL == 0 )\n {\n accessory.linkedAccessories.forEach( ( linkedAccessory ) =>\n {\n checkAccessoryForDuplicateUUID( linkedAccessory, UUID );\n });\n }\n }\n\n accessory.log.debug( `No Duplicate UUID's for this Accessory - ` + chalk.green( `OK` ) + `. Using: ${ accessory.UUID }` );\n}",
"function compute_oid_uuid(data)\n{\n return hex_to_bin(uuid_v5(data, NAMESPACE_OID));\n}",
"function baseFilterValidator(value) {\n var uuidRegexp = /^(stack-)?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,\n match = uuidRegexp.exec(value);\n\n if (match !== null) {\n return match[0];\n }\n\n return null;\n }",
"function isScreenIdValid() {\n\t\tlet screenId = $('#newUrl').val();\n\t\tif (screenId.length < 6 || screenId.length > 10) {\n\t\t\t$('#submitUrlMsg').html(\"Screen Id should have 6 - 10 characters\").css('color', 'red');\n\t\t\treturn false;\n\t\t} else {\n\t\t\treturn true;\n\t\t}\n\t}",
"function validateRut(rut){\n var pat = /^[0-9]{1,9}-([0-9]|k|K)$/;\n if(pat.test(rut)){\n var splited_rut = rut.split(\"-\");\n return dV(splited_rut[0]) == splited_rut[1].toLowerCase();\n }\n return false;\n}",
"function isMD5Encrypted(inputString) {\r\n return /[a-fA-F0-9]{32}/.test(inputString);\r\n }",
"validateDmacMask() {\n let regex = /^[a-fA-F0-9]{4}\\.[a-fA-F0-9]{4}\\.[a-fA-F0-9]{4}$/;\n if (regex.test(this.state.dmacMask.replace(/^\\s+|\\s+$/g, \"\"))) {\n let mask = this.state.dmacMask.toString().replace(/^\\s+|\\s+$/g, \"\");\n let mask1 = mask.replace(/\\./g, \"\");\n let mask2 = mask1.replace(/^0+/, \"\");\n let mask3 = mask2.replace(/0+$/, \"\");\n if (mask3.length > 8){\n this.setState(\n {\n dmacMaxOctetError: true,\n },\n () => {\n return false;\n }\n );\n }\n if (mask3.length <= 8) return true;\n }\n else {\n this.setState(\n {\n dmacMaskError: true,\n },\n () => {\n return false;\n }\n );\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
override to get access to the args before any command is executed | beforeCommand() { } | [
"reset() {\n this._argv = process.argv.slice(2)\n }",
"function setCommand(args) {\n\tSETTINGS.COMMAND = args.next() || SETTINGS.COMMAND\n}",
"function makeArgChanges() {\n //Only do the alterations if the arguments indicate a real or preview\n //run of the program will be executed.\n validateArgs();\n if (-1 !== aargsGiven.indexOf('-repo')) {\n oresult.srepo = PATH.normalize(oresult.srepo);\n if ('' === oresult.sdest) {\n oresult.sdest = oresult.srepo;\n } else {\n oresult.sdest = PATH.normalize(oresult.sdest);\n }\n oresult.sdest = oresult.sdest + PATH.sep +\n oresult.srepo.split(PATH.sep).pop() + '_cDivFiles';\n oresult.aign.push(CDIVUTILS.createGlobRegex(oresult.sdest + '*'));\n }\n }",
"get rawArgs() {\n // Slice prefix + command name and trim the start/ending spaces.\n return this.message.content.slice(this.prefix.length + this.invokedName.length).trim();\n }",
"get arg1() {\n const { 1: first } = __classPrivateFieldGet(this, __command);\n return first;\n }",
"_parse(args) {\n const parsed = args.map(arg => {\n if (arg.includes('=')) {\n const [flag, value] = arg.split('=');\n const command = this._commandParser.getCommand(flag);\n return new Argument(command, value);\n } else {\n const command = this._commandParser.getCommand(arg);\n return new Argument(command, null);\n }\n });\n\n return parsed;\n }",
"_validateAndParseCommandArguments() {\n const validationErrors = this._validateCommandArguments();\n\n if (validationErrors.length > 0) {\n _forEach(validationErrors, (error) => {\n throw error;\n });\n }\n }",
"resetCommandLineOptions () {\n this.setCommandLineOption(\"url\", undefined);\n this.setCommandLineOption(\"dir\", undefined);\n\n super.resetCommandLineOptions();\n }",
"async processCommandArgsAndFlags(commandInstance, args) {\n const parser = new Parser_1.Parser(this.flags);\n const command = commandInstance.constructor;\n /**\n * Parse the command arguments. The `parse` method will raise exception if flag\n * or arg is not\n */\n const parsedOptions = parser.parse(args, command);\n /**\n * We validate the command arguments after the global flags have been\n * executed. It is required, since flags may have nothing to do\n * with the validaty of command itself\n */\n command.args.forEach((arg, index) => {\n parser.validateArg(arg, index, parsedOptions, command);\n });\n /**\n * Creating a new command instance and setting\n * parsed options on it.\n */\n commandInstance.parsed = parsedOptions;\n /**\n * Setup command instance argument and flag\n * properties.\n */\n for (let i = 0; i < command.args.length; i++) {\n const arg = command.args[i];\n if (arg.type === 'spread') {\n commandInstance[arg.propertyName] = parsedOptions._.slice(i);\n break;\n }\n else {\n commandInstance[arg.propertyName] = parsedOptions._[i];\n }\n }\n /**\n * Set flag value on the command instance\n */\n for (let flag of command.flags) {\n const flagValue = parsedOptions[flag.name];\n if (flagValue !== undefined) {\n commandInstance[flag.propertyName] = flagValue;\n }\n }\n }",
"_validateCommandArguments() {\n const validatedCommandList = _map(this.commandList, (command) => {\n if (typeof command === 'undefined') {\n return null;\n }\n\n const errorMessage = command.validateArgs();\n\n if (errorMessage) {\n // we only return here so all the errors can be thrown at once\n // from within the calling method\n return errorMessage;\n }\n\n command.parseArgs();\n });\n\n return _compact(validatedCommandList);\n }",
"function printArguments() {\n var i;\n console.log(OS.eol + 'Commands provided to function:');\n for (i = 0; i < process.argv.length; i += 1) {\n console.log(i + ': ' + process.argv[i]);\n }\n }",
"didUpdateArguments () {\n\n }",
"function handleArgFlags(env) {\n // Make sure that we're not overwriting `help`, `init,` or `version` args in generators\n if (argv._.length === 0) {\n // handle request for usage and options\n if (argv.help || argv.h) {\n out.displayHelpScreen();\n process.exit(0);\n }\n\n // handle request for initializing a new plopfile\n if (argv.init || argv.i) {\n const force = argv.force === true || argv.f === true || false;\n try {\n out.createInitPlopfile(force);\n process.exit(0);\n } catch (err) {\n console.error(chalk.red(\"[PLOP] \") + err.message);\n process.exit(1);\n }\n }\n\n // handle request for version number\n if (argv.version || argv.v) {\n const localVersion = env.modulePackage.version;\n if (localVersion !== globalPkg.version && localVersion != null) {\n console.log(chalk.yellow(\"CLI version\"), globalPkg.version);\n console.log(chalk.yellow(\"Local version\"), localVersion);\n } else {\n console.log(globalPkg.version);\n }\n process.exit(0);\n }\n }\n\n // abort if there's no plopfile found\n if (env.configPath == null) {\n console.error(chalk.red(\"[PLOP] \") + \"No plopfile found\");\n out.displayHelpScreen();\n process.exit(1);\n }\n}",
"function validateArgs() {\n //No arguments or any argument set including the help argument are both\n //automatically valid.\n //If -pre, -dest, -ign, -ext, -enc, or -cst were provided, -repo\n //must also have been provided.\n //The presence of -sets and -args is always optional.\n\n //Allow no arguments or any set with a -help argument.\n if (0 === aargsGiven.length || -1 !== aargsGiven.indexOf('-help')) {\n return;\n }\n\n //Otherwise, require the -repo command if -pre, -dest, -ign, -ext,\n //-enc, or -cst were provided.\n if ((-1 !== aargsGiven.indexOf('-pre') ||\n -1 !== aargsGiven.indexOf('-dest') ||\n -1 !== aargsGiven.indexOf('-ign') ||\n -1 !== aargsGiven.indexOf('-ext') ||\n -1 !== aargsGiven.indexOf('-enc') ||\n -1 !== aargsGiven.indexOf('-cst')) &&\n -1 === aargsGiven.indexOf('-repo')) {\n throw 'Invalid argument set. Must use -repo if using any other ' +\n 'command except -help, -sets, or -args.';\n }\n }",
"function processFrameCommand (argsList_) {\n\tvar name = argsList_[0];\n\tvar command = commands.frameCommands[name];\n\n\targsList_ = argsList_.splice (1);\n\n\tif (command.type === 'property') {\n\t\tugly.context[command.name] = command.params[0].type.value (argsList_);\n\t} else {\n\t\tconsole.assert (command.type === 'method');\n\n\t\tvar args = [];\n\n\t\tfor (var j = 0; j < command.params.length; j++) {\n\t\t\targs.push (command.params[j].type.value (argsList_));\n\t\t}\n\n\t\tugly.context[command.name].apply (ugly.context, args);\n\t}\n}",
"function processArgsState() {\n oresult.bargs = true;\n bok = true;\n sstate = '';\n }",
"canExecute(args) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (args.length > 1) {\n\t\t\t\tthis.$errors.failWithoutHelp(\"This command accepts only one argument.\");\n\t\t\t}\n\n\t\t\tif (args.length) {\n\t\t\t\tresolve(true);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthis.$errors.failWithoutHelp(\"You should pass at least one argument to 'hello-world' command.\");\n\t\t});\n\t}",
"function addCommandLineArgs() {\r\n\r\n var fO = CurFuncObj;\r\n\r\n // Create and add a command line argument vector (similar to argv in C)\r\n // This is a reference to a grid (1D array of strings)\r\n // NOTE: No IndexObj is necessary for a grid in a header step\r\n //\r\n var newGId = fO.allGrids.length;\r\n var newgOArgs = new GridObj(newGId, DefStartupArgsName, 1, 10,\r\n 1, 4, false, false, false, true);\r\n //\r\n newgOArgs.inArgNum = 0; // add as 0th arg\r\n newgOArgs.isConst = true; // cannot write to startup args\r\n //\r\n newgOArgs.typesInDim = -1; // Set global type to string\r\n newgOArgs.dataTypes[0] = DataTypes.String;\r\n //\r\n fO.allGrids.push(newgOArgs);\r\n fO.allSteps[FuncHeaderStepId].allGridIds.push(newGId);\r\n\r\n assert(fO.allSteps[FuncHeaderStepId].isHeader, \"must be header\");\r\n}",
"function handleCommandLineArgs (argv) {\n if (!argv || !argv.length) return\n\n // Ignore if there are too many arguments, only expect one\n // when app is launched as protocol handler. We can handle additional options in the future\n\n if (isDev && argv.length > 3) return // app was launched as: electron index.js $uri\n if (!isDev && argv.length > 2) return // packaged app run as: joystream $uri\n\n var $uri = isDev ? argv[2] : argv[1]\n\n if ($uri) {\n // arg is either a magnetlink or a filepath\n application.handleOpenExternalTorrent($uri, function (err, torrentName) {\n rootUIStore.openingExternalTorrentResult(err, torrentName)\n })\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
DNS cache lookup. the function either returns that the file does not exist. OR logs the errors that could've occured. OR checks in the "dnscache" file if the url exists, if so, return 1, indicating it exits else, will call the DNS lookup function, save the new value, and send it back to the client. | function checkInFile(url,cb){
fs.readFile(__dirname+'/dns-cache.txt', function (err, data) {
//file not found handling
if(err !== null && err.code === "ENOENT"){
process.nextTick(function(){return cb(false)});
}
//other errors
else if(err !== null && err.code !== "ENOENT"){
console.log(err);
}
else if(data.toString('utf-8').match(url)){
//find the url and return the number next to it.
process.nextTick(function(){return cb(1)});
}
else{
dnsLookUp(url,function(address){
var fullAddress = url+" "+address; //send url + ip
process.nextTick(function(){return cb(fullAddress)});
fs.appendFile(__dirname+'/dns-cache.txt', fullAddress+"\n", function(err){
if (err !== null){
console.log(err);
}
});
});
}
});
} | [
"function createDnsFile(url,cb){\n dnsLookUp(url,function(address){ \n var data = url +\" \"+ address+\"\\n\";\n fs.writeFile(__dirname+'/dns-cache.txt',data, function (err) {\n if (err !== null){\n console.log(\"[ERROR]: \" + err);\n }\n else{\n process.nextTick(function(){return cb(data)});\n }\n });\n });\n}",
"function cacheDns () {\n self.getServerTime(function(err) {\n if(!err) {\n calculateTimeDiff();\n } else {\n syncTime();\n }\n });\n }",
"function isDomainCachable(req, res) {\n var finalUrlHeader = res.getHeader('x-final-url');\n if (finalUrlHeader != null) {\n var finalUrl = url.parse(res.getHeader('x-final-url'));\n\n // is the host in the list of domains we should not cache?\n var dontCacheHosts = require('./dont-cache')\n\n if (dontCacheHosts.indexOf(finalUrl.host) >= 0) {\n // in the list of domains to not cache - so don't cache the response\n return false\n } else {\n return true\n }\n } else {\n // cache by default - we know that if the header is not included then this is a cached response from a previous request\n return true;\n }\n}",
"function checkForCache(req, res, next) {\r\n const { country } = req.params;\r\n client.get(country, (err, website) => {\r\n if (err) throw err;\r\n if (website != null) res.send(forwardData(country, website));\r\n else next();\r\n })\r\n}",
"async _cachingFetch(url) {\n // super-hacky cache clearing without opening devtools like a sucker.\n if (/NUKECACHE/.test(url)) {\n this.cache = null;\n await caches.delete(this.cacheName);\n this.cache = await caches.open(this.cacheName);\n }\n\n let matchResp;\n if (this.cache) {\n matchResp = await this.cache.match(url);\n }\n if (matchResp) {\n const dateHeader = matchResp.headers.get('date');\n if (dateHeader) {\n const ageMillis = Date.now() - new Date(dateHeader);\n if (ageMillis > ONE_HOUR_IN_MILLIS) {\n matchResp = null;\n }\n } else {\n // evict if we also lack a date header...\n matchResp = null;\n }\n\n if (!matchResp) {\n this.cache.delete(url);\n } else {\n return matchResp;\n }\n }\n\n const resp = await fetch(url);\n this.cache.put(url, resp.clone());\n\n return resp;\n }",
"function fetchData(url, res){\n\n\tvar response = cachingMap[url];\n\n\t\tif (response == undefined ) {\n\t\t\tresponse = \"\";\n\t\t\tconsole.log(\"new content\");\n\n\t\t\thttp.get(url, function(result) {\n\t\t\t\tresult.on('data', function (chunk) {\n\t\t\t\t\t\tresponse += chunk;\n\t\t\t\t\t\tres.write(chunk);\n\t\t\t\t\t\tcachingMap[url] = response;\n\t\t\t\t\t});\n\t\t\t\tresult.on('end', function () {\n\t\t\t\t\t\tres.end();\n\t\t\t\t});\n\n\t\t\t});\n\t\t} else {\n\t\t\t\tconsole.log(\"cached content\");\n\t\t\t\tres.write(cachingMap[url]);\n\t\t\t\tres.end();\n\t\t}\n\n}",
"function FindProxyForURL(url, host) {\n try {\n expectEq(\"127.0.0.1\", myIpAddress());\n expectEq(\"\", myIpAddressEx());\n\n expectEq(null, dnsResolve(\"not-found\"));\n expectEq(\"\", dnsResolveEx(\"not-found\"));\n\n expectEq(false, isResolvable(\"not-found\"));\n expectEq(false, isResolvableEx(\"not-found\"));\n\n return \"PROXY success:80\";\n } catch(e) {\n alert(e);\n return \"PROXY failed:80\";\n }\n}",
"function urlExists(url) {\n\t\tvar http = new XMLHttpRequest();\n\t\thttp.open('HEAD', url);\n\t\thttp.send();\n\t\tif (http.status !== 404) {\n\t\t\timgsNumber++;\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}",
"function updateCache() {\n request('https://hypno.nimja.com/app', function (error, response, body) {\n if (error) {\n console.log(error);\n }\n var data = JSON.parse(body);\n if (data) {\n cache = data;\n parseCacheForSearchAndLookup();\n }\n });\n}",
"get(url) {\n const cached = splunkd.cached.cache[url];\n\n if (cached) {\n return cached;\n }\n\n const result = splunkd.cached.cache[url] = splunkd.get(url);\n return result;\n }",
"function LookupKeyword(Strings, keyword, validExt) {\r\n\r\n\t// Fields to query at cdnjs.com. The \"latest\" and \"name\" fields are always included\r\n\tvar fields = \"version\";\r\n\tvar showDesc = Script.ReadSetting(\"Show CDNJS library description\", \"1\");\r\n\tif (showDesc == \"1\") {\r\n\t\tfields += \",description\";\r\n\t}\r\n\r\n\t// Make lookup at cdnjs.com\r\n\tvar uri = \"http://api.cdnjs.com/libraries?fields=\" + fields + \"&search=\" + keyword;\r\n var xhr = CreateOleObject(\"MSXML2.ServerXMLHTTP\");\r\n xhr.open(\"GET\", uri, false);\r\n\txhr.setRequestHeader(\"Content-Type\", \"application/json\");\r\n\txhr.setRequestHeader(\"Cache-Control\", \"max-age=3600\");\r\n xhr.send();\r\n\tif (xhr.status != 200) {\r\n\t\tScript.Message(\"XHR Error: \" + xhr.statusText);\r\n\t\treturn \"\";\r\n\t}\r\n\r\n\t// Parse Json response\r\n\tvar objJson = ParseJson(xhr.responseText);\r\n\r\n\t// Populate AutoComplete Object with Json results\r\n\tvar resObj = objJson.getProp(\"results\");\r\n\tvar len = resObj.length;\r\n\tvar plen = _t(Length(_t(len))); // \"fix\"\r\n\r\n\tfor (var i=0;i<len;i++) {\r\n\t\tvar item = resObj.getProp(i);\r\n\t\tvar cdnUri = item.latest;\r\n\r\n\t\t// Skip files that doesn't have the correct file extension\r\n\t\tif (RegexMatch(cdnUri,\"(\\\\.[^.]+)$\", true) != validExt) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\r\n\t\t// Remove URI Scheme\r\n\t\tif (Script.ReadSetting(\"Remove URI Scheme\", \"1\") == \"1\") {\r\n\t\t\tcdnUri = RegexReplace(cdnUri, \"^[^\\\\/]*\", \"\", true);\r\n\t \t}\r\n\r\n\t\t// Return if exact match is found\r\n\t\tif ((Script.ReadSetting(\"Return immediately on exact match\", \"1\") == \"1\") && (item.name == keyword)) {\r\n\t\t\treturn cdnUri;\r\n\t\t}\r\n\r\n\t\tvar desc = \"\";\r\n\t\tif (showDesc == \"1\") {\r\n\t\t \tdesc = \" [\" + item.description + \"]\";\r\n\t\t}\r\n\r\n\t\tvar label = \"{\\\\colortbl\\\\red128\\\\green128\\\\blue128}{\\\\rtf\\\\cf0 CDN }{\\\\rtf\\\\b \" + item.name + \"} {\\\\rtf\\\\cf0 \" + item.version + desc + \" }\";\r\n\r\n\t\t// \"Fix\" to display the items in unsorted order. Adds numbered padding front of URI\r\n\t\t// Drawback is that the padding must be removed afterwards\r\n\t\tcdnUri = format(\"<%.\" + plen + \"d>\", [i]) + cdnUri;\r\n\r\n\t\tvar j = AutoComplete.AddItem(Strings, cdnUri, label);\r\n\t\tAutoComplete.SetImageIndex(j, 4);\r\n\t}\r\n\r\n\treturn \"\";\r\n}",
"async function networkFirst(req) {\n const cache = await caches.open('news-dynamic');\n\n try {\n const res = await fetch(req);\n cache.put(req, res.clone());\n return res;\n } catch (error) {\n const cachedResponse = await cache.match(req);\n return cachedResponse || await caches.match('./fallback.json')\n }\n}",
"function getCachedImage(path){\n\n\tif(!io.fileExistsSync(path)){\n\t\t// File does not exist so.. doenst really matter\n\t\treturn false;\n\t}else{\n\t\t// Should exist\n\t\treturn true;\n\t}\n}",
"function checkDatabase(url, req, next) {\n\tURLModel.findOne({url: url}, function(err, result) {\n\t\tif (err) console.error(err);\n\t\tif (!result) {\n\t\t\taddURLToDatabase(url, req, next);\n\t\t} else {\n\t\t\treq.result = {\n\t\t\t\toriginal_url: \"https://\" + result.url,\n\t\t\t\tshort_url: result.shortURL\n\t\t\t};\n\t\t\tnext();\n\t\t}\n\t});\n}",
"async function main() {\n\n // Login to GDN and Create cache (if not exists)\n fabric = new Fabric(fed_url)\n await fabric.login(guest_email, guest_password)\n await fabric.useFabric(geo_fabric)\n const cache = new Cache(fabric)\n\n //Clean Cache from previous runs\n await cache.purge(keys);\n\n // Use Macrometa GDN as Cache for Remote Origin Database\n console.log(\"----------------------\\n1. First time access:\\n----------------------\")\n\n var before = Date.now();\n for (let key of keys) {\n doc = await cache.get(key)\n if (doc == null) {\n console.log(\"CACHE_MISS: get from remote origin database...\")\n doc = await get_from_origin_db(key)\n cache.set(key, doc)\n }\n else {\n console.log(\"CACHE_HIT: get from closest region cache...\")\n }\n\n }\n console.log(\"\\n------- Execution Time: \" + (Date.now()-before) + \"ms (from Origin) -------\\n\")\n\n // 2nd time access served from GDN edge cache.\n console.log(\"----------------------\\n2. Second time access:\\n----------------------\")\n before = Date.now();\n for (key of keys) {\n doc = await cache.get(key)\n if (doc == null) {\n console.log(\"CACHE_MISS: get from remote origin database...\")\n doc = get_from_origin_db(key)\n cache.set(key, doc)\n }\n else {\n console.log(\"CACHE_HIT: get from closest region cache...\")\n }\n }\n console.log(\"\\n------- Execution Time: \" + (Date.now()-before) + \"ms (from Closest Cache)-------\\n\")\n\n // GDN Cache Geo replication in action... US West Coast\n console.log(\"------------------------------\\n3a. Access from US_WEST_COAST:\\n------------------------------\")\n fabric = new Fabric(fed_url_west)\n await fabric.login(guest_email, guest_password)\n await fabric.useFabric(geo_fabric)\n cache3a = new Cache(fabric)\n\n var before = Date.now();\n for (key of keys) {\n doc = await cache3a.get(key)\n if (doc == null) {\n console.log(\"CACHE_MISS: get from remote origin database...\")\n doc = get_from_origin_db(key)\n cache3a.set(key, doc)\n }\n else {\n console.log(\"CACHE_HIT: doc_id:\" + doc._id)\n }\n }\n console.log(\"\\n------- Execution Time: \" + (Date.now()-before) + \"ms (from US_WEST_COAST Cache) -------\\n\")\n\n\n // GDN Cache Geo replication in action... US East Coast\n console.log(\"------------------------------\\n3b. Access from US_EAST_COAST:\\n------------------------------\")\n fabric = new Fabric(fed_url_eastcoast)\n await fabric.login(guest_email, guest_password)\n await fabric.useFabric(geo_fabric)\n cache3b = new Cache(fabric)\n\n var before = Date.now();\n for (key of keys) {\n doc = await cache3b.get(key)\n if (doc == null) {\n console.log(\"CACHE_MISS: get from remote origin database...\")\n doc = get_from_origin_db(key)\n cache3b.set(key, doc)\n }\n else {\n console.log(\"CACHE_HIT: doc_id:\" + doc._id)\n }\n }\n console.log(\"\\n------- Execution Time: \" + (Date.now()-before) + \"ms (from US_EAST_COAST Cache) -------\\n\")\n\n // GDN Cache Geo replication in action... Europe\n console.log(\"------------------------------\\n3c. Access from EUROPE:\\n------------------------------\")\n fabric = new Fabric(fed_url_europe)\n await fabric.login(guest_email, guest_password)\n await fabric.useFabric(geo_fabric)\n cache3c = new Cache(fabric)\n\n var before = Date.now();\n for (key of keys) {\n doc = await cache3c.get(key)\n if (doc == null) {\n console.log(\"CACHE_MISS: get from remote origin database...\")\n doc = get_from_origin_db(key)\n cache3c.set(key, doc)\n }\n else {\n console.log(\"CACHE_HIT: doc_id:\" + doc._id)\n }\n }\n console.log(\"\\n------- Execution Time: \" + (Date.now()-before) + \"ms (from EUROPE Cache)-------\\n\")\n\n // GDN Cache Geo replication in action... Asia\n console.log(\"------------------------------\\n3c. Access from ASIA:\\n------------------------------\")\n fabric = new Fabric(fed_url_asia)\n await fabric.login(guest_email, guest_password)\n await fabric.useFabric(geo_fabric)\n cache3d = new Cache(fabric)\n\n var before = Date.now();\n for (key of keys) {\n doc = await cache3d.get(key)\n if (doc == null) {\n console.log(\"CACHE_MISS: get from remote origin database...\")\n doc = get_from_origin_db(key)\n cache3d.set(key, doc)\n }\n else {\n console.log(\"CACHE_HIT: doc_id:\" + doc._id)\n }\n }\n console.log(\"\\n------- Execution Time: \" + (Date.now()-before) + \"ms (from ASIA Cache)-------\\n\")\n\n // Invalidate & update cache globally on writes. \n console.log(\"------------------------------\\n4. Writes from Edge to origin and global cache update: \\n------------------------------\")\n for (key of keys) {\n doc = await cache.get(key)\n doc[\"company\"] = \"macrometa\"\n write_to_origin_db(doc)\n cache.set(key, doc)\n }\n\n console.log(\"------------------------------\\n5. After writes... Access from EUROPE:\\n------------------------------\")\n for (key of keys) {\n doc = await cache3b.get(key)\n if (doc == null) {\n console.log(\"CACHE_MISS: get from remote origin database...\")\n doc = get_from_origin_db(key)\n cache3b.set(key, doc)\n }\n else {\n console.log(\"CACHE_HIT: \\ndoc:\" + JSON.stringify(doc))\n }\n\n }\n}",
"function checkCache(neLat, neLng, swLat, swLng, type, season) {\n\tvar neLat_floor = Math.floor(neLat);\n\tvar neLng_floor = Math.floor(neLng);\n\tvar swLat_floor = Math.floor(swLat);\n\tvar swLng_floor = Math.floor(swLng);\n\tvar cache_hit = false;\n\t\n\tconsole.log(\"CHECKING CACHE\");\n\tif (type == \"WIND\") {\n\t\tif (wind_cache.length > 0) {\n\t\t\tconsole.log(\"CHECKING WIND CACHE\");\n\t\t\t\n\t\t\tfor (var lat = swLat_floor; lat <= neLat_floor; lat++) {\n\t\t\t\tif (typeof wind_cache[lat] != 'undefined') {\n\t\t\t\t\tfor (var lng = swLng_floor; lng <= neLng_floor; lng++) {\n\t\t\t\t\t\tif ((typeof wind_cache[lat][lng] != 'undefined') \n\t\t\t\t\t\t\t&& (typeof wind_cache[lat][lng][parseSeason(season)] != 'undefined')) {\n\t\t\t\t\t\t\tcache_hit = true;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tcache_hit = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tcache_hit = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (!cache_hit) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else if (type == \"SOLAR\") {\n\t\tconsole.log(\"CHECKING SOLAR CACHE\");\n\t\tif(typeof solar_cache[parseSeason(season)] != 'undefined') {\n\t\t\tcache_hit = true;\n\t\t}\n\t} else if (type == \"HYDRO\") {\n\t\tconsole.log(\"CHECKING HYDRO CACHE\");\n\t\tif (hydro_cache.length > 0) {\n\t\t\n\t\t\tfor (var lat = swLat_floor; lat <= neLat_floor; lat++) {\n\t\t\t\tif (typeof hydro_cache[lat] != 'undefined') {\n\t\t\t\t\tfor (var lng = swLng_floor; lng <= neLng_floor; lng++) {\n\t\t\t\t\t\tif (typeof hydro_cache[lat][lng] != 'undefined') {\n\t\t\t\t\t\t\tcache_hit = true;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tcache_hit = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tcache_hit = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (!cache_hit) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn cache_hit;\n}",
"function urlCheckAlive(data){\n \n var url = data['url'],\n params = data['params'],\n timeOut = data['timeout'] || null,\n caseId = data['caseid'],\n rType = data['type'] || 'GET',\n crossDomain = data['crossDomain'] || null;\n \n var checkDeferred = $simjq.Deferred(),\n start = new Date().getTime(),\n urlAlive = false;\n \n (function pollUrl(){\n \n console.log('Polling ' + url);\n \n var payload = {\n type: rType,\n url: url,\n data: params\n };\n if(timeOut)\n payload['timeout'] = timeOut;\n if(crossDomain)\n payload['crossDomain'] = crossDomain;\n $simjq.ajax(payload).done(\n function(response){\n console.log('Ping to ' + url + ' was successful');\n urlAlive = true;\n checkDeferred.resolve(response);\n return;\n }\n ).fail(\n function(err){\n \n console.log('Poll failed');\n\n if(new Date().getTime() - start > timeOut){\n console.log('Unable to reach ' + url);\n urlAlive = false;\n checkDeferred.reject(urlAlive);\n return;\n } else {\n setTimeout(pollUrl, 1000);\n }\n }\n ); \n }()); \n \n return checkDeferred.promise();\n}",
"function lookup(q, cb) {\n var req = dns.Request({\n question: q,\n server: { address: '8.8.8.8', port: 53, type: 'udp' },\n timeout: 2000,\n });\n\n function done(err, data) {\n cb(err, data);\n cb = function () {};\n }\n\n req.on('timeout', function () {\n done(new Error('Timeout in making request'));\n });\n\n req.on('message', done);\n\n req.send();\n}",
"function checkConnection(){\n\tdns.lookup('google.com',function(err) {\n\t\n \tif (err && err.code == \"ENOTFOUND\") {\n \t connected = 0;\n \t}\n\t\telse{\n\t\t\t\tconnected = 1;\n\t\t}\n\t});\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get all posts for a category. | static fetchCategoryPosts(category_name) {
return this._getObject(this._CATEGORY_POSTS_URL(category_name));
} | [
"function queryAllPosts(){\n\t\tvar keyword = \"all\";\n\t\t$.ajax({\n\t\t\ttype : \"GET\",\n\t\t\turl : \"post/getJsonPosts\",\n\t\t\tdata : {\"keyword\":keyword},\n\t\t\tsuccess : function(data){\n\t\t\t\t$(\"#posts-query p\").remove();\n\t\t\t\tqueryTemplate(data);\n\t\t\t}\n\t\t});\n\t}",
"function getListOfContentsOfAllcategories(categories) {\r\n $scope.dlListOfContentsOfAllcategories = [];\r\n var sortField = 'VisitCount';\r\n var sortDirAsc = false;\r\n\r\n if (categories instanceof Array) {\r\n categories.filter(function(category) {\r\n var dlCategoryContent = {};\r\n dlCategoryContent.isLoading = true;\r\n dlCategoryContent = angular.extend(Utils.getListConfigOf('pubContent'), dlCategoryContent);\r\n $scope.dlListOfContentsOfAllcategories.push(dlCategoryContent);\r\n\r\n pubcontentService.getContentsByCategoryName(category.name, sortField, sortDirAsc, dlCategoryContent.pagingPageSize).then(function(response) {\r\n if (response && response.data) {\r\n var contents = new EntityMapper(Content).toEntities(response.data.Contents);\r\n var category = new Category(response.data.Category);\r\n var totalCount = response.data.TotalCount;\r\n\r\n dlCategoryContent.items = contents;\r\n dlCategoryContent.headerTitle = category && category.title || '';\r\n dlCategoryContent.headerRightLabel = totalCount + '+ articles';\r\n dlCategoryContent.pagingTotalItems = totalCount;\r\n dlCategoryContent.footerLinkUrl = [dlCategoryContent.footerLinkUrl, category && category.name].join('/');\r\n dlCategoryContent.tags = pubcontentService.getUniqueTagsOfContents(contents);\r\n } else {\r\n resetContentList(dlCategoryContent);\r\n }\r\n dlCategoryContent.isLoading = false;\r\n }, function() {\r\n resetContentList(dlCategoryContent);\r\n });\r\n });\r\n }\r\n\r\n function resetContentList(dlCategoryContent) {\r\n dlCategoryContent.items = new EntityMapper(Content).toEntities([]);\r\n dlCategoryContent.headerRightLabel = '0 articles';\r\n dlCategoryContent.pagingTotalItems = 0;\r\n dlCategoryContent.tags = [];\r\n dlCategoryContent.isLoading = false;\r\n }\r\n }",
"async getPosts({limit, offset, sortingOrder, sortParameter} = {}) {\n return getPosts(client.baseURL, {limit, offset, sortingOrder, sortParameter});\n }",
"async getPosts () {\n\t\tconst postIds = this.models\n\t\t\t.filter(codemark => !codemark.get('providerType'))\n\t\t\t.map(codemark => codemark.get('postId'));\n\t\tif (postIds.length === 0) {\n\t\t\treturn;\n\t\t}\n\t\tthis.posts = await this.data.posts.getByIds(postIds);\n\t\tthis.responseData.posts = this.posts.map(post => post.getSanitizedObject({ request: this }));\n\t}",
"async getAllPublishedPosts(filter) {\n try {\n return await Post.find({\n isPublished: true\n }, null, filter).populate({\n path: 'author',\n model: 'User'\n })\n } catch (e) {\n return new Error(e.message)\n }\n }",
"async getListPublished(page) {\n const posts = await Post.query().paginate(page, 10);\n return posts;\n }",
"async searchPosts(pattern = \"\", {limit, offset, sortingOrder, sortParameter} = {}) {\n return searchPosts(client.baseURL, pattern, {limit, offset, sortingOrder, sortParameter});\n }",
"async function getProductsByCategory(category) {\n\n // Build FireStore document path\n // starting point (all categories)\n let storePath = 'categories';\n\n // Generate path to products in a particular category\n if (category !== '') {\n storePath += `/${category}/Products`\n }\n try {\n // Get products contained in the given category\n const products = await getFireStoreDataAsync(storePath);\n\n // return products\n return products;\n \n } // catch and log any errors\n catch (err) {\n console.log(err);\n }\n }",
"function everythingCategoryAPICall(theCategory) {\n return new Promise((resolve, reject) => {\n newsapi.v2.everything({\n q: theCategory\n }).then(response => {\n resolve(response);\n })\n })\n}",
"async getAllPosts() {\n const result = PostModel.find().exec()\n if (result.length < 1) return false\n return result\n }",
"function seedingPosts(authors, postCategories) {\n const Post = mongoose.model('Post', postSchema);\n\n const posts = [];\n for (let i = 0; i < 100; ++i) {\n const nCategories = faker.random.number(2) + 1;\n const categories = faker.helpers.shuffle(postCategories).slice(0, nCategories);\n\n posts.push({\n title: faker.lorem.words(),\n slug: faker.lorem.slug(),\n image: faker.image.imageUrl(),\n description: faker.lorem.paragraph(),\n author: faker.helpers.randomize(authors)._id,\n content: faker.lorem.paragraphs(faker.random.number(20)).replace('\\n', '<br/>'),\n publishedAt: new Date(),\n isPublished: true,\n categories,\n });\n }\n\n return Post.create(posts);\n}",
"function fetchPosts() { // jshint ignore:line\n // Exit if postURLs haven't been loaded\n if (!postURLs) return;\n\n isFetchingPosts = true;\n $('.infinite-spinner').css('display', 'block');\n // Load as many posts as there were present on the page when it loaded\n // After successfully loading a post, load the next one\n var loadedPosts = 0;\n\n postCount = $('body').find('.js-postcount').length,\n callback = function() {\n loadedPosts++;\n var postIndex = postCount + loadedPosts;\n\n if (postIndex > postURLs.length-1) {\n disableFetching();\n $('.infinite-spinner').css('display', 'none');\n return;\n }\n\n if (loadedPosts < postsToLoad) {\n fetchPostWithIndex(postIndex, callback);\n } else {\n isFetchingPosts = false;\n $('.infinite-spinner').css('display', 'none');\n }\n };\n\n fetchPostWithIndex(postCount + loadedPosts, callback);\n }",
"async getAllUserPublishedPosts(filter, AuthUser) {\n try {\n return await Post.find({\n isPublished: true\n }, null, filter).\n where({ author: AuthUser.id }).\n populate({\n path: 'author',\n model: 'User'\n })\n } catch (e) {\n return new Error(e.message)\n }\n }",
"function seedingCategories() {\n const PostCategory = mongoose.model('PostCategory', postCategorySchema);\n\n const fakeCats = [];\n for (let i = 0; i < 10; ++i) {\n const name = faker.lorem.words();\n fakeCats.push({\n name,\n slug: faker.helpers.slugify(name),\n description: faker.lorem.paragraph(),\n });\n }\n\n return PostCategory.create(fakeCats);\n}",
"function getAllPosts(){\n var postsJSONArr = localStorage.getItem(\"post\");\n return JSON.parse(postsJSONArr);\n}",
"getArticlesCategory (category: string, callback: mixed) {\n\t\tsuper.query(\"select * from NewsArticle where category = ?\",\n\t\t\t[category],\n\t\t\tcallback\n\t\t);\n\t}",
"getSingleCategory(categoryId) {\n return this.webRequestService.get(\"categories/\".concat(categoryId));\n }",
"static findByCategory(searchCategory) {\r\n let results = []\r\n\r\n for (let event in all) {\r\n if (event.category.has(searchCategory)) {\r\n results.add(event);\r\n }\r\n }\r\n return results;\r\n }",
"function displayAllPosts() {\n \n $.ajax({\n \"url\": \"services/allPosts.php\",\n \"success\": function(jsonResponse) {\n \n $(jsonResponse).each(function(index, element) {\n \n var postId = element.id;\n var postTitle = element.title;\n var postDescription = element.description;\n var postCreated = element.created;\n var postUserId = element.user_id;\n \n var aPost = formatPost(postTitle, postDescription, postCreated,\n postUserId, postId);\n \n $(\"#allPostsContainer\").prepend(aPost);\n \n //Add comments section\n addCommentSection(postId);\n \n //Display all post comments\n displayCommentsByPostId(postId);\n\n })\n \n },\n \"error\":function() {\n\n $(\"#actionUnsuccessful\").dialog({\n \"modal\": true,\n \"buttons\": {\n \"Ok\": function() {\n\t\t\t$( this ).dialog( \"close\" );\n }\n }\n });\n \n }, \n \"dataType\":\"json\"\n }) \n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
For each zone, finds circles that the zones are in. Returns a list of lists | function zoneFinder(zoneStrings,circles) {
var ret = [];
for (var i = 0; i < zoneStrings.length; i++) {
var zoneString = zoneStrings[i];
var nextZone = [];
for (var j = 0; j < zoneString.length; j++) {
var circleLabel = zoneString[j];
var circle = circleWithLabel(circleLabel,circles);
nextZone.push(circle);
}
ret.push(nextZone);
}
return ret;
} | [
"function findZoneRectangles(zoneStrings, circles) {\n\n\tvar zones = zoneFinder(zoneStrings,circles);\n\n\tvar rectangles = [];\n\t\n\t// iterate through the zones, finding the best rectangle for each zone\n\tfor (var i = 0; i < zones.length; i++) {\n\t\tvar circlesInZone = zones[i];\n\t\t\n\t\tvar circlesOutZone = getOutZones(circles, circlesInZone);\n\t\tvar rectangle = findZoneRectangle(circlesInZone,circlesOutZone);\n\n\t\tfor (var j = 0; j < circlesInZone.length; j++){\n\t\t\trectangle.label = rectangle.label + \"\" + circlesInZone[j].label;\n\t\t}\n\n\t\tconsole.log(circlesInZone, circlesOutZone, rectangle);\n\t\trectangles.push(rectangle);\n\t}\n\treturn rectangles;\n}",
"function insideCircles(node){\n\tvar strCircles = node.region.label;\n\tvar result = [];\n\t//console.log(circles);\n\n\tfor (var i = 0; i < circles.length; i++){\n\t\tvar circle = circles[i];\n\t\tvar distance = Math.sqrt( Math.pow(node.x - circle.x, 2) + Math.pow(node.y - circle.y, 2) );\n\t\t//does this node's region contain this circle\n\t\tif (strCircles.indexOf(circle.label) != -1) {\n\t\t\t//check node is inside\n\t\t\t\n\t\t\t//console.log(strCircles, label, circle, node, distance);\n\t\t\tif (distance >= circle.r){\n\t\t\t\tresult.push(circle);\n\t\t\t}\n\t\t} else {\n\t\t\t//check if node is outside\n\t\t\tif (distance <= circle.r){\n\t\t\t\tresult.push(circle);\n\t\t\t}\n\n\t\t}\n\t}\n\n/*\n\tfor (var i = 0; i < strCircles.length; i++){\n\t\tvar label = strCircles[i];\n\t\tvar circle = findCircle(label);\n\n\t\tvar distance = Math.sqrt( Math.pow(node.x - circle.x, 2) + Math.pow(node.y - circle.y, 2) );\n\n\t\t//console.log(strCircles, label, circle, node, distance);\n\t\tif (distance > circle.r){\n\t\t\tresult.push(circle);\n\t\t}\n\t}\n*/\t\t\t\treturn result;\n}",
"function zoneToPoints(zone)\n{\n\tlet points = [];\n\tfor(let c of zone) {\n\t\tpoints.push(new Vector2D(c.x,c.y));\n\t}\n\treturn points;\n}",
"function findCorners() {\n var corners = [];\n for (var y = 0; y < map.length; ++y) {\n for (var x = 0; x < map[y].length; ++x) {\n if (map[y][x] !== WALL) {\n var diagonalBoxes = nearBoxes(x, y, COORD_MODE_DIAGONAL);\n for (var i = 0; i < diagonalBoxes.length; ++i) {\n var dBox = diagonalBoxes[i],\n dBoxX = dBox[0],\n dBoxY = dBox[1],\n xDiff = x - dBoxX,\n yDiff = y - dBoxY;\n\n if (map[dBoxY][dBoxX] === WALL) {\n var straightBoxes = [[dBoxX + xDiff, dBoxY],\n [dBoxX, dBoxY + yDiff]];\n if (!containsWall(straightBoxes)) {\n corners.push([x, y]);\n break; // One is enough\n }\n }\n }\n }\n }\n }\n return corners;\n }",
"function pointsToZone(points)\n{\n\tlet zone = [];\n\tfor(let p of points) {\n\t\tzone.push(g_TOMap.gCells[p.x][p.y]);\n\t}\t\t\n\treturn zone;\n}",
"function find_floating_group() {\n var inner_groups = [];\n\n // check every planet in the map\n for (var j = 0; j < map.rows; j++) {\n for (var i = 0; i < map.columns; i++) {\n var planet = map.planets[i][j];\n if(planet.type != -1 && !planet.checked) {\n var iGroup = find_group(i, j, false);\n\n // skip the empty iGroup\n if(iGroup.length <= 0) {\n continue;\n }\n\n // floating check\n var floating = true;\n for (var k = iGroup.length - 1; k >= 0; k--) {\n if(iGroup[k].y == 0) {\n // connect to the top\n floating = false;\n break;\n }\n }\n\n if(floating) {\n inner_groups.push(iGroup);\n }\n }\n }\n }\n \n return inner_groups;\n }",
"getContainerLocations() {\n if (this.containerLocations) { return this.containerLocations; }\n\n this.containerLocations = [];\n\n this.getSourceManagers().forEach(s => {\n s.findMiningSpots().forEach(pos => {\n this.containerLocations.push(pos);\n });\n });\n\n const room = this.object('room');\n const controllerPos = this.agent('controller').object('controller').pos;\n const adjacentOpen = room.lookAtArea(\n controllerPos.y - 1, controllerPos.x - 1,\n controllerPos.y + 1, controllerPos.y - 1, true).filter(lookObj => {\n return (lookObj.type === LOOK_TERRAIN &&\n lookObj[lookObj.type] !== 'wall');\n });\n let k = 0;\n for (let i = 0; i < adjacentOpen.length; i++) {\n this.containerLocations.push({\n x: adjacentOpen[i].x,\n y: adjacentOpen[i].y\n });\n k++;\n if (k > 2) { break; }\n }\n\n return this.containerLocations;\n }",
"function find_group(x, y, match) {\n var planet = map.planets[x][y];\n working_array = [planet];\n planet.checked = true;\n\n var temp_group = [];\n\n while(working_array.length > 0) {\n var current_planet = working_array.pop();\n\n // skip the empty places\n if(current_planet.type == -1) {\n continue;\n }\n\n // skip the removed or assigned places\n if(current_planet.removed || current_planet.assigned) {\n continue;\n }\n\n\n if(!match || (current_planet.type == planet.type)) {\n // addthe current planet to the temp_group\n temp_group.push(current_planet);\n\n // calculate the current planet matrix position\n var position = get_planet_matrix_position(current_planet.x, current_planet.y);\n\n // get the neighbours of the current planet\n var neighbours = get_planet_neighbours(position.x, position.y);\n\n for (var i = neighbours.length - 1; i >= 0; i--) {\n if(!neighbours[i].checked) {\n // add the neighbour to the working array\n working_array.push(neighbours[i]);\n neighbours[i].checked = true;\n }\n }\n }\n }\n\n // return the temp_group of planets\n return temp_group;\n }",
"getPlayersInZone(zone) {\n if(!DeathMatchLocation.hasLocation(zone))\n throw new Error('Unknown zone: ' + zone);\n\n return [...this.playersInDeathMatch_]\n .filter(item => item[1] === zone)\n .length;\n }",
"function findGridAll(x, y, radius) {\n const c = grid.cells.c;\n let found = [findGridCell(x, y)];\n let r = Math.floor(radius / grid.spacing);\n if (r > 0) found = found.concat(c[found[0]]); \n if (r > 1) {\n let frontier = c[found[0]];\n while (r > 1) {\n let cycle = frontier.slice();\n frontier = [];\n cycle.forEach(function(s) {\n\n c[s].forEach(function(e) {\n if (found.indexOf(e) !== -1) return;\n found.push(e);\n frontier.push(e);\n });\n\n });\n r--;\n }\n }\n \n return found;\n\n}",
"function findZoneEntries(zone, millis, pad) {\n if (pad === undefined) pad = 24*3600*1000;\n\n var entries = zone.filter(function(e){ return millis+pad >= e.from && millis-pad < e.to });\n\n if (entries.length > 0)\n\treturn entries;\n\n throw \"Time zone info not available for \"\n\t+ zone.name + \", \" \n\t+ new Date(millis).getFullYear() +\".\";\n}",
"getSurroundingColors(coord) {\n var colors = [];\n for (var x = coord.x - 1; x <= coord.x + 1; x++) {\n for (var y = coord.y - 1; y <= coord.y + 1; y++) {\n var color = this.getColor(new Coord(x, y));\n if (color !== null) {\n colors.push(color);\n }\n }\n }\n return colors;\n }",
"function getIntersectionPoints(circles) {\n\t var ret = [];\n\t for (var i = 0; i < circles.length; ++i) {\n\t for (var j = i + 1; j < circles.length; ++j) {\n\t var intersect = circleCircleIntersection(circles[i], circles[j]);\n\t for (var k = 0; k < intersect.length; ++k) {\n\t var p = intersect[k];\n\t p.parentIndex = [i, j];\n\t ret.push(p);\n\t }\n\t }\n\t }\n\t return ret;\n\t }",
"function resolveCollisions(owner){\n var searchRadius = 80;\n var neighbours = [];\n var c1 = owner.attrs;\n\n Circles.children.forEach(function(child){\n var c2 = child.attrs;\n\n if(isColliding(c1.x, c1.y, c2.x, c2.y, searchRadius)){\n neighbours.push(child);\n }\n\n });\n\n neighbours.forEach(function(n){\n var c2 = n.attrs;\n if(isColliding(c1.x, c1.y, c2.x, c2.y, 50)){\n var dist = Math.abs(Math.sqrt(Math.pow(c1.x - c2.x, 2) + Math.pow(c1.y - c2.y, 2)));\n var midX = (c1.x + c2.x) / 2;\n var midY = (c1.y + c2.y) / 2;\n\n owner.position({\n x: (midX + 50 * (c1.x - c2.x) / dist),\n y: (midY + 50 * (c1.y - c2.y) / dist)\n });\n\n n.position({\n x: (midX + 50 * (c2.x - c1.x) / dist),\n y: (midY + 50 * (c2.y - c1.y) / dist)\n });\n\n layer.draw();\n resolveCollisions(n);\n }\n });\n\n // Base case to prevent stack limit breaching.\n if(! owner){\n }\n}",
"getNeighbors(col, row){\n var res = [];\n //left border\n if(col > 0){\n this.agentController.ocean.lattice[col-1][row].forEach( (agent) =>{\n res.push(agent);\n });\n }\n //right border\n if(col < (100/ocean.latticeSize)-1){\n this.agentController.ocean.lattice[col+1][row].forEach( (agent) =>{\n res.push(agent);\n });\n }\n //upper border\n if(row > 0){\n this.agentController.ocean.lattice[col][row-1].forEach( (agent) => {\n res.push(agent);\n });\n }\n //lower border\n if(row < (100/ocean.latticeSize)-1){\n this.agentController.ocean.lattice[col][row+1].forEach( (agent) =>{\n res.push(agent);\n });\n }\n //upper left corner\n if(row > 0 && col > 0){\n this.agentController.ocean.lattice[col-1][row-1].forEach( (agent) => {\n res.push(agent);\n });\n }\n //upper right corner\n if(row > 0 && col < (100/ocean.latticeSize)-1){\n this.agentController.ocean.lattice[col+1][row-1].forEach( (agent) => {\n res.push(agent);\n });\n }\n //lower left corner\n if(row < (100/ocean.latticeSize)-1 && col > 0){\n this.agentController.ocean.lattice[col-1][row+1].forEach( (agent) => {\n res.push(agent);\n });\n }\n //lower right corner\n if(row < (100/ocean.latticeSize)-1 && col < (100/ocean.latticeSize)-1){\n this.agentController.ocean.lattice[col+1][row+1].forEach( (agent) => {\n res.push(agent);\n });\n }\n //own cell\n this.agentController.ocean.lattice[col][row].forEach( (agent) => {\n res.push(agent);\n });\n return res;\n }",
"function findZoneRectangle(circlesInZone,circlesOutZone) {\n\n\tvar pointsInZone = findSufficientPointsInZone(circlesInZone,circlesOutZone);\n\t\n\tif(pointsInZone.length == 0) {\n\t\treturn new Rectangle(0,0,0,0);\n\t}\n\tvar biggestRectangle;\n\tvar biggestArea = 0;\n\tfor (var i = 0; i < pointsInZone.length; i++) {\n\t\tvar rectangle = findRectangle(pointsInZone[i],circlesInZone,circlesOutZone);\n\t\tif(rectangle.width*rectangle.height > biggestArea) {\n\t\t\tbiggestRectangle = rectangle;\n\t\t\tbiggestArea = rectangle.width*rectangle.height;\n\t\t}\n\t}\n\treturn biggestRectangle;\n}",
"function getAddressesInArea(x,y,dist){\n let temp,xx,yy,count = 0;\n let addresses = [];\n x *= PI/180;\n y *= PI/180;\n for(var i = 0; i < result.length;i++){\n xx = result[i][0] * PI/180;\n yy = result[i][1] * PI/180;\n temp = Math.acos(Math.sin(x)*Math.sin(xx)+Math.cos(x)*Math.cos(xx)*Math.cos(y-yy))*6371\n if(temp < dist){\n addresses[count] = [];\n addresses[count][0] = result[i][0];\n addresses[count][1] = result[i][1];\n addresses[count][2] = result[i][2];\n addresses[count++][3] = temp;\n }\n }\n return sortAddressesByDist(addresses);\n}",
"function getNeighbors(point){\n\t\treturn NODES.reduce((neighbors, node, i) => {\n\t\t\tlet distance = getDistance(point, node)\n\t\t\tif(distance > 0 && distance <= SETTINGS.NEIGHBORHOOD_RADIUS) neighbors.push(i)\n\t\t\treturn neighbors\n\t\t}, [])\n\t}",
"function divideArcs(arcs, opts) {\n var points = findClippingPoints(arcs, opts);\n // TODO: avoid the following if no points need to be added\n var map = insertCutPoints(points, arcs);\n // segment-point intersections currently create duplicate points\n // TODO: consider dedup in a later cleanup pass?\n // arcs.dedupCoords();\n return map;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates the button to change the level cap | function createCapChanger() {
var levelCapChanger = document.createElement('li');
var levelCapStyle = document.createElement('style');
levelCapStyle.innerHTML = "#level_cap_control::after {border-bottom:1px dotted #9b9a9a;bottom:0;content:'';display:block;left:11px;position:absolute;right:11px;}";
levelCapChanger.appendChild(levelCapStyle);
var linkCapChanger = document.createElement('a');
linkCapChanger.id = 'level_cap_control';
linkCapChanger.innerHTML = 'Level cap';
linkCapChanger.href = '#';
linkCapChanger.addEventListener('click', function () {
setFakeMaxLevel();
});
levelCapChanger.appendChild(linkCapChanger);
var signOut = document.getElementById('welcome_box_sign_out');
var cogList = signOut.parentNode.parentNode;
cogList.insertBefore(levelCapChanger, signOut.parentNode);
} | [
"function createLockLevelPopUp(){\n\t\t\t\t\t\t\tvar levelChoose=new lib.levelChooseBoard();\n\t\t\t\t\t\t\tlevelChoose.x=myStage/2-levelChoose.nominalBounds.width/2;\n\t\t\t\t\t\t\tlevelChoose.y=myStage/2-levelChoose.nominalBounds.height/2;\n\t\t\t\t\t\t\tstage.addChild(levelChoose);\n\t\t\t\t\t\t}",
"function setCurrLevel(btn) {\n if (btn.innerText === 'Easy') {\n gCurrLevel = 0;\n } else if (btn.innerText === 'Medium') {\n gCurrLevel = 1;\n } else if (btn.innerText === 'Hard') {\n gCurrLevel = 2;\n // CR: Unnecessary else statement.\n } else gCurrLevel;\n return gCurrLevel;\n}",
"createButton () {\n\n this.button = document.createElement('button')\n\n this.button.title = 'This model has multiple views ...'\n\n this.button.className = 'viewable-selector btn'\n\n this.button.onclick = () => {\n this.showPanel(true)\n }\n\n const span = document.createElement('span')\n span.className = 'fa fa-list-ul'\n this.button.appendChild(span)\n\n const label = document.createElement('label')\n this.button.appendChild(label)\n label.innerHTML = 'Views'\n \n this.viewer.container.appendChild(this.button)\n }",
"function __createIncDecButton(){\n\t\tvar incDecBtnImg = new CAAT.Foundation.SpriteImage().initialize( game._director.getImage('incre_decre_btn'), 1, 2);\n\t\tvar iniVelIncBtn = new CAAT.Foundation.Actor().\n\t\t\t\t\t\t\t\tsetId('iniVelInc').\n\t\t\t\t\t\t\t\tsetAsButton(incDecBtnImg.getRef(), 0, 0, 1, 1, function(button){\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t}).setLocation(375, 20);\n\t\tvar iniVelDecBtn = new CAAT.Foundation.Actor().\n\t\t\t\t\t\t\t\tsetId('iniVelDec').\n\t\t\t\t\t\t\t\tsetAsButton(incDecBtnImg.getRef(), 1, 1, 1, 1, function(button){\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t}).setLocation(374, 48);\n\t\t\t\t\t\t\t\t\n\t\t\t// if (\"ontouchstart\" in document.documentElement)\n\t\t\t// {\n \t\t\t\t\tdashBG.addChild(iniVelIncBtn);\n\t\t\t\t\tdashBG.addChild(iniVelDecBtn);\n\t\t\n\t\t//the increment and decrement buttons MouseDown functions are called when long press\n\t\t\t\t\tiniVelIncBtn.mouseDown = game.incDecMDown;\n\t\t\t\t\tiniVelIncBtn.mouseUp = game.incDecMUp;\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t//the increment and decrement buttons MouseDown functions are called when long press\n\t\t\t\t\tiniVelDecBtn.mouseDown = game.incDecMDown;\n\t\t\t\t\tiniVelDecBtn.mouseUp = game.incDecMUp;\n\t\t\t// }\n\t}",
"function addUplinkButton() {\r\n\tvar upBtn = document.createElement('button');\r\n\tupBtn.setAttribute('type', 'button');\r\n\tupBtn.setAttribute('class', 'btn btn-default btn-sm');\r\n\r\n\tvar upBtnIcn = document.createElement('i');\r\n\tupBtnIcn.setAttribute('class', 'fa fa-level-up');\r\n\tupBtnIcn.setAttribute('aria-hidden', 'true');\r\n\r\n\tupBtn.appendChild(upBtnIcn);\r\n\r\n\tdocument.getElementById('kapitel-btn').innerHTML = \"\";\r\n\tdocument.getElementById('kapitel-btn').appendChild(upBtn);\r\n}",
"function makeCrabButton() {\n\n // Create the clickable object\n crabButton = new Clickable();\n \n crabButton.text = \"\";\n\n crabButton.image = images[22]; \n\n // gives the button a transparent background and changes the stroke to 0 \n crabButton.color = \"#00000000\";\n crabButton.strokeWeight = 0; \n\n //set width + height to image size\n crabButton.width = 280; \n crabButton.height = 120;\n\n // placing the button on the page \n crabButton.locate( width * (1/16) - crabButton.width * (1/16), height * (26/32) - crabButton.height * (26/32));\n\n // // Clickable callback functions, defined below\n crabButton.onPress = crabButtonPressed;\n crabButton.onHover = beginButtonHover;\n crabButton.onOutside = animalButtonOnOutside;\n}",
"function setLevelAttributes(level){\n\tif(level >= 8){\n\t\twaitTime = 500;\n\t\tfallingTime = 95;\n\t}\n\telse{\n\t\twaitTime = 1000 - ((level - 1) * 70);\n\t\tfallingTime = 200 - ((level - 1) * 15);\n\t}\n\tif(level >= 9){\n\t\tgetNewWords(10);\n\t}\n\telse{\n\t\tgetNewWords(level + 1);\n\t}\n\tfor(var x = 0; x < wordsArray.length; x++){\n\t\twordsArray[x] = wordsArray[x].toUpperCase();\n\t}\n\tfor(var i = 0; i < wordsArray.length; i++){\n\t\twordExistsInArray[i] = true;\n\t\tlistCountersArray[i] = 1;\n\t}\n\tsetLetterPicker();\n\tinitializeGame();\n\tinitializeList();\n\tcalculatePossible();\n\tdropAblock();\n}",
"function addButton(size) {\r\n\r\n}",
"static set miniButtonRight(value) {}",
"static set miniButtonMid(value) {}",
"function makeCoralImportanceButton() {\n\n // Create the clickable object\n coralImportanceButton = new Clickable();\n \n coralImportanceButton.text = \"Why are coral reefs important?\";\n coralImportanceButton.textColor = \"#365673\"; \n coralImportanceButton.textSize = 25; \n\n coralImportanceButton.color = \"#8FD9CB\";\n\n // set width + height to image size\n coralImportanceButton.width = 420;\n coralImportanceButton.height = 62;\n\n // places the button \n coralImportanceButton.locate( width * (1/32) , height * (7/8));\n\n // // Clickable callback functions, defined below\n coralImportanceButton.onPress = coralImportanceButtonPressed;\n coralImportanceButton.onHover = beginButtonHover;\n coralImportanceButton.onOutside = beginButtonOnOutside;\n}",
"levelControl() {\n\t\tvar levelBefore = this.level;\n\t\tthis.level = Math.floor((parseInt(this.score) - 100) / 100) + 1;\n\n\t\tif (this.level < levelBefore) {\n\t\t\tthis.level = levelBefore;\n\t\t}\n\n\t\tif (this.level > 3) {\n\t\t\tthis.level = 3;\n\t\t}\n\n\n\t\tvar numberOfMonsterBefore = this.numberOfMonster;\n\t\tthis.numberOfMonster = this.level;\n\t\tthis.speed = 2 * this.level;\n\t\tif (this.numberOfMonster > numberOfMonsterBefore) {\n\t\t\tthis.initListMonster();\n\t\t}\n\t}",
"function estimateBtnClone() {\n btnMenu.on('click',function(){\n var btn = $('.h-estimate').clone();\n if($(this).hasClass('active')){\n btn.prependTo('.menu > ul');\n }\n else{\n btn = '';\n $('.menu ul .h-estimate').remove();\n }\n });\n }",
"function create_zoom_button() {\n var right_controls\n var size_button\n var tooltip_showing = false\n var button\n var icon_path\n\n /**\n * set_zoom_button_mode\n * Sets the zoom button to an appropriate mode for the current zoom state.\n */\n function set_zoom_button_mode() {\n var l\n\n if(zoom_should_be_on()) {\n icon_path.setAttribute(\"d\",\n \"m 8,11 0,14 20,0 0,-14 -20,0 z m 2,4 16,0 0,6 -16,0 0,-6 z\"\n )\n l = \"Normal (\" + zoom_shortcut_key + \")\"\n } else {\n icon_path.setAttribute(\"d\",\n \"m 4,11 0,14 3,0 0,-2 -1,0 0,-10 1,0 0,-2 -3,0 z\\\n m 4,0 0,14 20,0 0,-14 -20,0 z\\\n m 21,0 0,2 1,0 0,10 -1,0 0,2 3,0 0,-14 -3,0 z\\\n m -19,2 16,0 0,10 -16,0 0,-10 z\"\n )\n l = \"Widescreen (\" + zoom_shortcut_key + \")\"\n }\n\n button.setAttribute(\"aria-label\", l)\n button.setAttribute(\"title\", l)\n }\n \n /**\n * create_zoom_button_icon\n * Adds the icon to the zoom button during initial creation of the button.\n */\n function create_zoom_button_icon() {\n // Create icon SVG element\n var s = document.createElementNS(\"http://www.w3.org/2000/svg\", \"svg\")\n s.setAttribute(\"height\", \"100%\")\n s.setAttribute(\"version\", \"1.1\")\n s.setAttribute(\"viewBox\", \"0 0 36 36\")\n s.setAttribute(\"width\", \"100%\")\n\n var p_id = \"zac-path-1\"\n\n // Apply shadow\n var sh = document.createElementNS(\"http://www.w3.org/2000/svg\", \"use\")\n sh.setAttribute(\"class\", \"ytp-svg-shadow\")\n sh.setAttribute(\"href\", \"#\" + p_id)\n\n // Create icon path\n var p = document.createElementNS(\"http://www.w3.org/2000/svg\", \"path\")\n p.setAttribute(\"id\", p_id)\n p.setAttribute(\"class\", \"ytp-svg-fill\")\n\n // Append path and shadow to SVG\n s.appendChild(sh)\n s.appendChild(p)\n\n // Append icon to button\n button.appendChild(s)\n\n icon_path = p\n }\n \n /**\n * show_zoom_button_tooltip\n * Shows the tooltip associated with the zoom button in a style mimicking that\n * of the other YouTube player buttons.\n * Parameters:\n * show if false, the tooltip will be hidden instead of shown\n */\n function show_zoom_button_tooltip(show=true) {\n // Position calculations\n var bbcr = button.getBoundingClientRect()\n var tt_horiz_cen = bbcr.left + bbcr.width/2 // tooltip horizontal centre\n\n var tt_top_offset = 57 // How far above the button should the tooltip be?\n\n // For some reason, the existing tooltips are at a different offset in full-screen.\n if(document.fullscreenElement) {\n tt_top_offset = 75\n }\n\n var tt_top = bbcr.top + bbcr.height/2 - tt_top_offset // tooltip top\n\n // YouTube has an existing tooltip DOM structure that it reuses for all of its\n // player tooltips, but it's easier and more reliable to just create our own,\n // using the same classes.\n\n // Try to get our existing tooltip from DOM from previous run\n var tt = document.getElementById(\"zac-tt\")\n\n var tt_text\n\n if(!tt) {\n // Create tool-tip DOM structure if not present.\n var mp = document.getElementsByClassName(\"html5-video-player\")[0]\n var tt_text_wrapper = document.createElement(\"div\")\n tt = document.createElement(\"div\")\n tt_text = document.createElement(\"span\")\n\n tt.setAttribute(\"class\", \"ytp-tooltip ytp-bottom\")\n tt.setAttribute(\"id\", \"zac-tt\")\n tt.style.setProperty(\"position\", \"fixed\")\n\n tt_text_wrapper.setAttribute(\"class\", \"ytp-tooltip-text-wrapper\")\n\n tt_text.setAttribute(\"class\", \"ytp-tooltip-text\")\n tt_text.setAttribute(\"id\", \"zac-tt-text\")\n\n tt.appendChild(tt_text_wrapper)\n tt_text_wrapper.appendChild(tt_text)\n mp.appendChild(tt)\n } else {\n // If DOM structure already present, get tooltip text.\n tt_text = document.getElementById(\"zac-tt-text\")\n }\n\n if(show) { // show\n tt.style.setProperty(\"top\", tt_top + \"px\")\n tt_text.innerHTML = button.getAttribute(\"aria-label\")\n tt.style.removeProperty(\"display\") // show the tooltip\n\n // Calculate horizontal position. Tooltip must be showing before\n // its width can be queried.\n var tt_width = tt.getBoundingClientRect().width\n tt.style.setProperty(\"left\", tt_horiz_cen - tt_width / 2 + \"px\")\n debug_log(\"tt_width = \" + tt_width)\n debug_log(\"tt_horiz_cen = \" + tt_horiz_cen)\n debug_log(\"tt left position = \" + (tt_horiz_cen - tt_width / 2))\n\n // Remove button title, else the browser may (will) display it as a\n // tooltip, in addition to ours.\n button.removeAttribute(\"title\")\n } else { // hide\n tt.style.setProperty(\"display\", \"none\")\n tt_text.innerHTML = \"\"\n button.setAttribute(\"title\", button.getAttribute(\"aria-label\"))\n }\n\n tooltip_showing = show\n\n // All of that just for a tooltip that matches the others. And it's\n // still not perfect. Sheesh.\n }\n \n /**\n * update\n * Ensures the zoom button reflects the current state.\n */\n function update() { \n set_zoom_button_mode()\n show_zoom_button_tooltip(tooltip_showing)\n }\n \n var button_object\n \n function add_button() {\n right_controls = document.getElementsByClassName(\"ytp-right-controls\")[0]\n size_button = document.getElementsByClassName(\"ytp-size-button\") [0]\n \n if(right_controls && size_button) {\n debug_log(\"Adding zoom and crop toggle button.\")\n \n // Remove existing button if present (sometimes it persists even after a page reload)\n var existing_button = document.getElementById(\"zac-zoom-button\")\n if(existing_button) {\n debug_log(\"Destroying old zoom and crop toggle button.\")\n right_controls.removeChild(existing_button)\n }\n \n // Create button\n button = document.createElement(\"button\")\n button.setAttribute(\"class\", \"ytp-button\")\n button.setAttribute(\"id\", \"zac-zoom-button\")\n\n create_zoom_button_icon()\n set_zoom_button_mode()\n\n // Add button to controls\n right_controls.insertBefore(button, size_button)\n\n // Set event handlers\n button.addEventListener(\"click\", toggle_manual_enab)\n button.addEventListener(\"mouseover\", function(){show_zoom_button_tooltip()})\n button.addEventListener(\"mouseout\", function(){show_zoom_button_tooltip(false)})\n button.addEventListener(\"focus\", function(){show_zoom_button_tooltip()})\n button.addEventListener(\"blur\", function(){show_zoom_button_tooltip(false)})\n\n button_object = { \n update : update\n }\n\n } else {\n // Keep trying until we have somewhere to put the button.\n debug_log(\"Can't add zoom and crop toggle button yet. Retrying in 200ms.\")\n setTimeout(add_button, 200)\n }\n }\n \n add_button()\n return button_object\n}",
"function set_zoom_button_mode() {\n var l\n\n if(zoom_should_be_on()) {\n icon_path.setAttribute(\"d\",\n \"m 8,11 0,14 20,0 0,-14 -20,0 z m 2,4 16,0 0,6 -16,0 0,-6 z\"\n )\n l = \"Normal (\" + zoom_shortcut_key + \")\"\n } else {\n icon_path.setAttribute(\"d\",\n \"m 4,11 0,14 3,0 0,-2 -1,0 0,-10 1,0 0,-2 -3,0 z\\\n m 4,0 0,14 20,0 0,-14 -20,0 z\\\n m 21,0 0,2 1,0 0,10 -1,0 0,2 3,0 0,-14 -3,0 z\\\n m -19,2 16,0 0,10 -16,0 0,-10 z\"\n )\n l = \"Widescreen (\" + zoom_shortcut_key + \")\"\n }\n\n button.setAttribute(\"aria-label\", l)\n button.setAttribute(\"title\", l)\n }",
"function changeLevel() {\n const inputFieldLvlNr = document.getElementById('lvl_nr_input_field');\n const lvl_nr_input = parseInt(inputFieldLvlNr.value);\n if (lvl_nr_input >= 1 && lvl_nr_input <= nLevels) {\n lvlNumber = lvl_nr_input;\n toggleLevelBox();\n createGrid();\n loadLevel();\n resetGame();\n } else alert(`Puzzle number should be between 1 and ${nLevels}.`);\n}",
"function makeOctopusButton() {\n\n // Create the clickable object\n octopusButton = new Clickable();\n \n octopusButton.text = \"\";\n\n octopusButton.image = images[21]; \n\n // makes the image transparent\n octopusButton.color = \"#00000000\";\n octopusButton.strokeWeight = 0; \n\n // set width + height to image size\n octopusButton.width = 290; \n octopusButton.height = 160;\n\n // places the button \n octopusButton.locate( width * (13/16) - octopusButton.width * (13/16), height * (1/2) - octopusButton.height * (1/2));\n\n // Clickable callback functions, defined below\n octopusButton.onPress = octopusButtonPressed;\n octopusButton.onHover = beginButtonHover;\n octopusButton.onOutside = animalButtonOnOutside;\n}",
"createUI() {\n var title = panelTitle;\n this.panel = new PanelClass(this.viewer, title);\n var button1 = new Autodesk.Viewing.UI.Button(panelTitle);\n\n button1.onClick = (e) => {\n if (!this.panel.isVisible()) {\n this.panel.setVisible(true);\n } else {\n this.panel.setVisible(false);\n }\n };\n\n button1.addClass('fa');\n button1.addClass('fa-child');\n button1.addClass('fa-2x');\n button1.setToolTip(onMouseOver);\n\n this.subToolbar = this.viewer.toolbar.getControl(\"spinalcom-sample\");\n if (!this.subToolbar) {\n this.subToolbar = new Autodesk.Viewing.UI.ControlGroup('spinalcom-sample');\n this.viewer.toolbar.addControl(this.subToolbar);\n }\n this.subToolbar.addControl(button1);\n this.initialize();\n }",
"function _btnWeight() {\n //Working\n console.log(\"doing something\");\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
adds a log object to the queue, oldest logs are removed and saved to file after queue size exceeds 1000 | function queueLog(log) {
logCache.add(log);
while (logCache.length() > 1000) {
const oldestLog = logCache.remove();
logger.log(oldestLog.severity, oldestLog);
}
} | [
"function FileQueue() {\n size = 0;\n}",
"function maintainLogSize() {\n while ($scope.logs.length > MAX_LOG_SIZE) {\n $scope.logs.shift();\n }\n }",
"function add(request) {\n request.queueTime = (new Date()).getTime();\n\n queue.add(request).save();\n\n if (settings.get('developer')) {\n utils.log('Queue', queue);\n }\n }",
"enqueue(msg) {\n if (this.msgs.length >= maxQueuedMsgCount) {\n throw Error(\"Too many messages queued for the client\");\n }\n this.msgs.push(msg);\n }",
"function queueFile(file) {\n if (! fileAlreadyQueued(file)) {\n allFiles.push(file);\n displayFile(file);\n }\n}",
"enque(object) {\n this.queArr.push(object);\n this.length++;\n return true;\n }",
"function addToQueue(ticket) {\n MongoClient.connect(mongodb_url, function(err, db) {\n if (err) {\n console.log('Error: ' + err);\n }\n else {\n db.collection('grocery_queue').insert(ticket, function(err, doc) {\n if (err) {\n console.log('Error inserting to db');\n }\n console.log('Inserted: ' + doc + ' to queue');\n });\n }\n });\n}",
"function onQueue(data) {\n\tif (\"Error\" in data) {\n\t\tonError(data.Error);\n\t} else if (\"Value\" in data) {\n\t\tqueueSize = data.Value.length;\n\t\t$(\"#current-queue>tbody\").empty();\n\t\tfor (i = currentTrack; i < data.Value.length; i++) {\n\t\t\twriteTrackRow(data.Value[i], i + 1);\n\t\t}\n\t\tfor (i = 0; i < currentTrack; i++) {\n\t\t\twriteTrackRow(data.Value[i], i + 1);\n\t\t}\n\t}\n}",
"function writeIt() {\n if (index < LOG.length) {\n fs.appendFile('log.txt', LOG[index++] + \"\\n\", writeIt);\n }\n }",
"saveChunk() {\n console.log(\"Saving Chunk for \" + this.name + \" @ \" + this.path + \"/fullLog.json\");\n\n // Load the Full Log.\n let fullLogRaw = fs.readFileSync(this.path + \"/fullLog.json\");\n let fullLog = JSON.parse(fullLogRaw);\n\n // Push the Current Chunk.\n fullLog.push(this.currentChunk);\n\n // Clear the Current Chunk.\n this.currentChunk = [];\n let logJSON = JSON.stringify(fullLog, null, 2);\n\n // Write the New Full Log.\n fs.writeFileSync(this.path + \"/fullLog.json\", logJSON);\n this.currentChunkIndex++;\n }",
"insertInQueue(msg,onComplete){\r\n assert.equal(typeof msg,'object','msg must be an object');\r\n assert.equal(typeof onComplete,'function','onComplete must be a function');\r\n let th = this;\r\n console.log(MODULE_NAME + ': insert new msg');\r\n this.queueMgr.insertInQueue(\r\n FATUS_QUEUE_NAME,\r\n msg,\r\n function onDone(e,v){\r\n th.addWorker();\r\n onComplete(e,v);\r\n }\r\n );\r\n }",
"function batchUpload() {\n var queueName = dijit.byId('vl-queue-name').getValue();\n currentType = dijit.byId('vl-record-type').getValue();\n\n var handleProcessSpool = function() {\n if( \n vlUploadQueueImportNoMatch.checked || \n vlUploadQueueAutoOverlayExact.checked || \n vlUploadQueueAutoOverlay1Match.checked) {\n\n vlImportRecordQueue(\n currentType, \n currentQueueId, \n function() {\n retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);\n }\n );\n } else {\n retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);\n }\n }\n\n var handleUploadMARC = function(key) {\n dojo.style(dojo.byId('vl-upload-status-processing'), 'display', 'block');\n processSpool(key, currentQueueId, currentType, handleProcessSpool);\n };\n\n var handleCreateQueue = function(queue) {\n currentQueueId = queue.id();\n uploadMARC(handleUploadMARC);\n };\n \n if(vlUploadQueueSelector.getValue() && !queueName) {\n currentQueueId = vlUploadQueueSelector.getValue();\n uploadMARC(handleUploadMARC);\n } else {\n createQueue(queueName, currentType, handleCreateQueue, vlUploadQueueHoldingsImportProfile.attr('value'));\n }\n}",
"function Queue() {\r\n var array = new Array();\r\n\r\n /**\r\n * Check inf the given data already exist in the queue\r\n * @param {type} data input data\r\n * @returns {Boolean} result\r\n */\r\n this.isDuplicate = function(data) {\r\n return array.indexOf(data) > -1 ? true : false;\r\n };\r\n /**\r\n * Put the specific object into the queue and return the queue size\r\n * @param {type} data\r\n * @returns {Number}\r\n */\r\n this.enqueue = function enqueue(data) {\r\n if (!this.isDuplicate(data)) {\r\n array.push(data);\r\n }\r\n return array.length;\r\n };\r\n /**\r\n * Remove and return the first object in queue\r\n * @returns {Object}\r\n */\r\n this.dequeue = function dequeue() {\r\n return array.shift();\r\n };\r\n /**\r\n * Get the queue size\r\n * @returns {Number}\r\n */\r\n this.size = function() {\r\n return array.length;\r\n };\r\n /**\r\n * check if the queue iis empty\r\n * @returns {Boolean}\r\n */\r\n this.isEmpty = function() {\r\n return array.length === 0;\r\n };\r\n this.toString = function() {\r\n return ('Queue: ' + array).green;\r\n };\r\n}",
"enqueue(track) {\n this.queue.push(track);\n void this.processQueue();\n }",
"consumeLogs () {\n try {\n this.tail = new Tail(this.logPath)\n } catch (err) {\n console.log('Error while opening log file.', err)\n return\n }\n\n console.log(`Ready to consume new logs from ${this.logPath} file.`)\n\n this.tail.on('line', (line) => {\n console.log('New log:', line)\n this.update(line)\n })\n\n this.tail.on('error', (error) => {\n console.log('Error during log parsing', error)\n })\n\n // Summary of most hit section, runs every 10 seconds\n setInterval(() => {\n this.summarizeTraffic()\n }, this.SUMMARY_INTERVAL * 1000)\n }",
"enqueue(item) {\n if (this.canEnqueue()) {\n this.queueControl.push(item);\n return this.queueControl;\n } \n throw new Error('QUEUE_OVERFLOW');\n }",
"setLogCapacity(capacity) {\n this.config.capacity = capacity;\n }",
"function accumData(postData) {\n documents.push(postData)\n if(documents.length == 10000){\n // send array of JSON objects to solr server\n console.log('sending')\n sendData(documents)\n documents = []\n }\n}",
"function ArrayQueue() {}",
"addToQueue(events) {\n const eventsArray = [].concat(events);\n eventsArray.map((event) => {\n this._eventQueue.push(event);\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Toggle display of eventgrid | function toggleEvents() {
events.style.display = events.style.display == "none" ? "" : "none";
} | [
"function CalendarToggle() {\n\tif (this.visible) {\n\t\tthis.Hide();\n\t} else {\n\t\tthis.Show();\n\t}\n}",
"showGrid(){\n this.Grid = true;\n this.Line = false\n \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 toggleToCompBoard(evt) {\n gameBoard1.style.display = \"none\";\n gameBoard2.style.display = \"\";\n compHeader.style.display = \"\";\n playerHeader.style.display = \"none\";\n}",
"toggleAll() {\n if (this.display_mode === 'hidden') this.showAll();\n else if (this.display_mode === 'shown') this.hideAll();\n }",
"function toggleGameHistory(){\n if(toggle==='hide'){\n setToggle('show')\n }else{\n setToggle('hide')\n }\n }",
"function _toggleVisibility() {\n\n\t\tvisible = !visible;\n\n\t\tif (true === visible) {\n\t\t\tpanel.show();\n\t\t\t$(\"#phpviewlog-preview-icon\").addClass(\"active\");\n\t\t\tWorkspaceManager.recomputeLayout();\n\t\t} else {\n\t\t\tpanel.hide();\n\t\t\t$(\"#phpviewlog-preview-icon\").removeClass(\"active\");\n\t\t}\n\t}",
"toggleColumn(e) {\n const t = !this.columnIsVisible(e), r = hp(this.columns, (i) => i.can_be_hidden ? i.key === e ? t : this.visibleColumns.includes(i.key) : !0);\n let n = ws(r, (i) => i.key).sort();\n ii(n, this.defaultVisibleToggleableColumns) && (n = []), this.visibleColumns = n.length === 0 ? this.defaultVisibleToggleableColumns : n, this.updateQuery(\"columns\", n, null, !1);\n }",
"function toggle_display(idname)\n{\n\tobj = fetch_object(idname);\n\tif (obj)\n\t{\n\t\tif (obj.style.display == \"none\")\n\t\t{\n\t\t\tobj.style.display = \"\";\n\t\t}\n\t\telse\n\t\t{\n\t\t\tobj.style.display = \"none\";\n\t\t}\n\t}\n\treturn false;\n}",
"function showhideTieBreakers(event) {\n const checked = event.target.checked;\n\tshow_tiebreakers = checked;\n if (show_tiebreakers) reconcile_ranks();\n\tshowhideRankScoreColumns();\n}",
"toggleDepartedColumn(){\n \t$('.departed-bucket').toggle();\n \t$('.chat-bucket').toggle();\n\t}",
"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}",
"show() {\n\t\tthis.element.style.visibility = '';\n\t}",
"_onDisplaySelected( event) {\n const selectedDisplay = event.detail.display;\n console.debug( `dia-show › on-display-selected: ${selectedDisplay}`);\n this.moveToDisplay( selectedDisplay);\n if( event.cancellable) { event.stopPropagation(); }\n }",
"toggleColFilter(state) {\n state.showColFilter = !state.showColFilter;\n }",
"function __showBigGrid(grid, obj, oldWidth, oldHeight) {\n\n var hideArray = [];\n var blockArray = obj.caller.blockArray;\n\n for (var i = 0; i < blockArray.length; i++) {\n if (obj.id != blockArray[i].id)\n hideArray[i] = blockArray[i].id;\n }\n\n var screenWidth = screen.width - 60;\n var screenHeight = screen.height;\n\n for (var i = 0; i < hideArray.length; i++) {\n if (hideArray[i] != \"\") {\n if (!SHOW_BIG_GRID_FLG) {\n if (Ext.getCmp(hideArray[i]) && Ext.getCmp(hideArray[i]).isVisible()) {\n newVisiableArray.push(hideArray[i]);\n Ext.getCmp(hideArray[i]).hide();\n }\n } else {\n for (var k = 0; k < newVisiableArray.length; k++) {\n if (newVisiableArray[k] == hideArray[i]) {\n Ext.getCmp(hideArray[i]).show();\n }\n }\n }\n }\n }\n\n var CM = grid.getColumnModel();\n var CM_COUNT = CM.getColumnCount();\n for (var j = 0; j < CM_COUNT; j++) {\n var OLD_WIDTH = CM.getColumnWidth(j);\n if (CM.getDataIndex(j) && CM.getDataIndex(j) != \"\") {\n if (!SHOW_BIG_GRID_FLG) {\n grid.getView().forceFit = true;\n CM.setColumnWidth(j, OLD_WIDTH);\n }\n else {\n\n grid.getView().forceFit = false;\n CM.setColumnWidth(j, OLD_WIDTH);\n }\n }\n }\n\n if (SHOW_BIG_GRID_FLG) {\n grid.setWidth(oldWidth);\n grid.setHeight(oldHeight);\n Ext.getCmp(obj.caller.id).setWidth(oldWidth + 20)\n }\n else {\n grid.setWidth(screenWidth);\n grid.setHeight(screenHeight - 400);\n\n Ext.getCmp(obj.caller.id).setWidth(screenWidth)\n }\n\n if (!SHOW_BIG_GRID_FLG) {\n SHOW_BIG_GRID_FLG = true;\n } else {\n SHOW_BIG_GRID_FLG = false;\n }\n\n var spans = document.getElementsByTagName(\"button\");\n for (var i = 0; i < spans.length; i++) {\n if (spans[i].innerHTML == \"放大显示\") {\n spans[i].innerHTML = \"缩小显示\";\n } else if (spans[i].innerHTML == \"缩小显示\") {\n spans[i].innerHTML = \"放大显示\";\n }\n }\n return;\n /////下面是完美的代码\n\n\n\n\n\n\n SHOW_BIG_GRID_FLG_DO = true;\n var divs = document.getElementsByTagName(\"div\");\n var spans = document.getElementsByTagName(\"button\");\n var screenWidth = screen.width - 60;\n var screenHeight = screen.height - 400;\n var widthDiff = screenWidth - oldWidth;\n\n for (var i = 0; i < divs.length; i++) {\n if (!SHOW_BIG_GRID_FLG) {\n var oldKey = (oldWidth + \"\").substring(0, 1);\n if (divs[i].style && divs[i].style.width) {\n var tempWidth = divs[i].style.width + \"\";\n tempWidth = tempWidth.replace(\"px\", \"\");\n var widthNum = parseInt(tempWidth, 10);\n if (widthNum <= oldWidth && (oldWidth - 50) <= widthNum && tempWidth.indexOf(oldKey) == 0) {\n widthNum += widthDiff;\n divs[i].style.width = widthNum + \"px\";\n }\n }\n } else {\n if (divs[i].style && divs[i].style.width) {\n var tempWidth = divs[i].style.width + \"\";\n tempWidth = tempWidth.replace(\"px\", \"\");\n var widthNum = parseInt(tempWidth, 10);\n widthNum = widthNum - widthDiff;\n if (widthNum <= oldWidth && (oldWidth - 50) <= widthNum) {\n divs[i].style.width = widthNum + \"px\";\n }\n }\n }\n }\n\n if (!SHOW_BIG_GRID_FLG) {\n grid.setHeight(screenHeight);\n } else {\n grid.setHeight(oldHeight);\n }\n\n for (var i = 0; i < spans.length; i++) {\n if (spans[i].innerHTML == \"放大显示\") {\n spans[i].innerHTML = \"缩小显示\";\n } else if (spans[i].innerHTML == \"缩小显示\") {\n spans[i].innerHTML = \"放大显示\";\n }\n }\n\n if (hideArray) {\n for (var i = 0; i < hideArray.length; i++) {\n if (hideArray[i] != \"\") {\n if (Ext.getCmp(hideArray[i])) {\n if (!SHOW_BIG_GRID_FLG) {\n Ext.getCmp(hideArray[i]).hide();\n } else {\n Ext.getCmp(hideArray[i]).show();\n }\n }\n }\n }\n }\n\n var slefFrom = WhiteShell.FormAssembly.businessForm;\n if (newHideArray && slefFrom != null && (!slefFrom.isOriginate() && slefFrom.getViewState() != \"republish\")) {\n if (isFirstShowBigFlg) {\n for (var i = 0; i < newHideArray.length; i++) {\n if (newHideArray[i] != \"\") {\n if (Ext.getCmp(newHideArray[i])) {\n if (!SHOW_BIG_GRID_FLG) {\n if (Ext.getCmp(newHideArray[i]).isVisible()) {\n Ext.getCmp(newHideArray[i]).hide();\n newVisiableArray.push(newHideArray[i]);\n }\n } else {\n Ext.getCmp(newHideArray[i]).show();\n }\n }\n }\n }\n isFirstShowBigFlg = false;\n } else {\n for (var i = 0; i < newVisiableArray.length; i++) {\n if (!SHOW_BIG_GRID_FLG) {\n Ext.getCmp(newVisiableArray[i]).hide();\n } else {\n Ext.getCmp(newVisiableArray[i]).show();\n }\n }\n }\n }\n\n if (!SHOW_BIG_GRID_FLG) {\n SHOW_BIG_GRID_FLG = true;\n } else {\n SHOW_BIG_GRID_FLG = false;\n }\n SHOW_BIG_GRID_FLG_DO = false;\n}",
"function toggleInvitationsSection() {\n var string = 'invitationsSection';\n var value = getStyle(string, 'display');\n hideNewListSection();\n hideInviteMemberSection();\n if(value == 'none') {\n\tshowInvitationsSection();\n } else {\n\thideInvitationsSection();\n }\n}",
"function toggleView() {\n id(\"admin-sight\").classList.toggle(\"hidden\")\n id(\"tool-app\").classList.toggle(\"hidden\");\n id(\"tool-app\").classList.toggle(\"flex\");\n }",
"function showingHiddingCanvas(mode){\r\n\t\r\n\t let x = document.getElementById(\"display-mode\");\r\n\t x.style.display = mode;\r\n\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
================================================================================== Confirmar cuadro de texto ==================================================================================== | function con() {
var txt;
if (confirm("precione el boton deceado")) {
txt = "seguir ";
} else {
txt = "cancelar";
}
document.getElementById("confirmar").innerHTML = txt;
} | [
"function alertSecurity() {\n var txt;\n if (confirm(\"Are you sure to notify Security?\")) {\n alert(\"Already notified Security.\");\n } else {\n alert(\"Canceled to notify Security!\");\n }\n }",
"function tiposAlerta() {\n // La alerta alert, solo mostrara el texto designado y un boton de ok, solo podra continuar si le da click\n\n alert(\"Mensaje de alerta \\nAlerta tipo ´alert´\");\n\n // La alerta prompt es usada para que el usuario ingrese datos antes de ingresar a la pagina, al dar click en ok, lo que escriba se retorna , si le da en cancel, nom no tendra ningun valor\n let nom = prompt(\"Introduzca su nombre por favor\", \"Prueb tipo PlaceHolder\");\n\n let text1 = document.getElementById(\"parr1\");\n text1.innerHTML = nom;\n\n // La alerta de confirmacion, la variable que se le asigna el confirm, sera true o false, dependa de lo que el usuario digite, pero si o si regresa un valor, a diferencia que el prompt\n let resultado = confirm(\"Acepta los terminos de esta pagina, al declarar que es mayor de edad? xd\");\n\n let text2 = document.getElementById(\"parr2\");\n text2.innerHTML = resultado;\n // text2.append(\" me agreggue\");\n}",
"function confirmar() {\n if ($('#v_estado').val() === \"\") {\n alert('Seleccione un pedido.!');\n } else {\n if ($('#v_estado').val() === 'PENDIENTE') {\n var opcion = confirm('Desea confirmar el pedido.??');\n if (opcion === true) {\n\n }\n } else {\n if ($('#v_estado').val() === 'CONFIRMADO') {\n alert('El pedido ya fue confirmado..');\n }\n }\n }\n\n\n}",
"function pesquisar() {\n\tvar texto = txtChave.value;\n\n\tvar obj = localStorage.getItem(txtChave.value);\n\n\tif (obj != null) {\n\t\ttexto = \" \" + texto;\n\t\tpesquisa = \" \" + pesquisa;\n\n\t\tif (texto.substr(1, 1) == nomeDoBotao) {\n\t\t\tvar pesquisa = document.getElementById('txtValor').value = obj;\n\t\t\tswal(\"Palavra:\" + texto, \" Descricao: \" + pesquisa, \"success\");\n\t\t} else {\n\t\t\tswal(\"\", 'Essa palavra não começa com: ' + nomeDoBotao, \"info\");\n\t\t}\n\t\ttxtValor.focus();\n\t} else {\n\t\tswal(\"\", \"A palavra\" + texto + \" não existe ou o campo está vazio VERIFIQUE.\", \"info\");\n\t\tresetarCampos();\n\t}\n}",
"function confirmTranslation() {\n\n $log.debug(\"Confirming translation\");\n\n // Force a save.\n $scope.values.saved = \"\";\n onChange($scope.item.format, \"confirmTranslation\");\n\n // Locally change the from_default to indicate that we no longer should show the warning etc.\n // The server should have received the update already, so in a refresh from_default will\n // also be set to false.\n $scope.item.from_default = false;\n }",
"function mensajeVacio(){\n return \"Campos obligatorios\";\n }",
"function mensaje_advertencia(titulo, mensaje){\n swal({ title: titulo, text: mensaje, type: \"error\", confirmButtonText: \"Aceptar\" });\n }",
"static async textEquals(text) {\n const alertDialog = await browser.switchTo().alert();\n expect(await alertDialog.getText()).toEqual(text.toString());\n }",
"function ConfirmAction() \n{\n if (confirm('Are you sure you want to do this!? ')) {\n return true;\n } else {\n return false;\n }\n}",
"function showMessageOk() {\n var alert = $mdDialog.alert()\n .title('Alerta guardada')\n .htmlContent('La alerta ha sido guardada de forma correcta.')\n .ariaLabel('save alert')\n .ok('OK');\n\n $mdDialog.show(alert);\n $state.reload();\n }",
"function confirmNote(){\n\tvar notes = document.getElementById('NotesVacID').value;\n\tif (notes !== '')\n\t\treturn notes;\n\t\treturn window.confirm(\"Your Notes are Empty, Confirm?\");\n}",
"function Xconfirm(/* String */text, /* Callback function */action, /* String */title) {\n\tif (!$.isFunction(action)) return confirm(text);\n\tif (title === undefined) title = \"\";\n\n\tXdialog(text).dialog({\n\t\tmodal: true,\n\t\ttitle: title,\n\t\tbuttons: {\n\t\t\t\"Yes\": function() {\n\t\t\t\t$(this).dialog('close');\n\t\t\t\taction();\n\t\t\t},\n\t\t\t\"No\": function() {\n\t\t\t\t$(this).dialog('close');\n\t\t\t}\n\t\t}\n\t});\n\treturn false;\n}",
"function confirme_suppression_compte(objet,id)\r\n{\r\nif (confirm(\"Souhaitez vous supprimer cet identifiant : \"+objet))\r\n\twindow.location=\"comptes_del.php?id=\"+id;\r\n}",
"function confirmerSuppression() {\n let n = new Noty({\n text: 'Confirmer la demande de suppression ',\n layout: 'center', theme: 'sunset', modal: true, type: 'info',\n animation: {\n open: 'animated lightSpeedIn',\n close: 'animated lightSpeedOut'\n },\n buttons: [\n Noty.button('Oui', 'btn btn-sm btn-success marge ', function () {\n supprimer();\n n.close();\n }),\n Noty.button('Non', 'btn btn-sm btn-danger', function () { n.close(); })\n ]\n }).show();\n}",
"function confirmDelete()\n{\n\tif (document.forms[0].txtPageSection.value == 3)\n\t{\n\t\tvar answer = confirm(\"Do you really want to delete this testiminial?\");\n\t\tif (answer)\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t}\n}",
"function ceoCornerTextAlter(){\n\t\t\n\t\t$('.page-ceo-corner .resource-subscribe-block form label').text(Drupal.t(\"Enter your email address to subscribe to this blog and recieve notifications of new posts by email. \"));\n\t}",
"function showQuestion(){\n var lstrMessage = '';\n lstrMessageID = showQuestion.arguments[0];\n lobjField = showQuestion.arguments[1];\n lstrCaleeFunction = funcname(arguments.caller.callee);\n //Array to store Place Holder Replacement\n var larrMessage = new Array() ;\n var insertPosition ;\n var counter = 0 ;\n\n larrMessage = showQuestion.arguments[2];\n \n lstrMessage = getErrorMsg(lstrMessageID);\n \n if(larrMessage != null &&\n larrMessage.length > 0 ){\n\n while((insertPosition = lstrMessage.indexOf('#')) > -1){\n\n if(larrMessage[counter] == null ){\n larrMessage[counter] = \"\";\n }\n lstrMessage = lstrMessage.substring(0,insertPosition) +\n larrMessage[counter] +\n lstrMessage.substring(insertPosition+1,lstrMessage.length);\n counter++;\n }\n }\n\n //lstrFinalMsg = lstrMessageID + ' : ' + lstrMessage;\n lstrFinalMsg = lstrMessage;\n\n if(lobjField!=null){\n lobjField.focus();\n }\n var cnfUser = confirm(lstrFinalMsg);\n if( !cnfUser ) {\n isErrFlg = true;\n }\n if(cnfUser && lstrCaleeFunction == 'onLoad'){\n \tdisableButtons('2');\n }\n //End ADD BY SACHIN\n return cnfUser;\n}",
"function modificarTres() {\n\tvar hora = document.getElementById(\"modHora3\").value;\n\tvar fecha = document.getElementById(\"fecha3\").value;\n\tvar mensaje = \"\";\n\tvar errores = \"\";\n\t\n\tif(hora == \"0\"){\n\t\terrores += \"No ha seleccionado una hora\";\n\t}\n\tif(fecha == \"\"){\n\t\terrores += \"No ha seleccionado una fecha\";\n\t\treturn false;\n\t}\n\n\tif(errores != \"\") {\n\t\talert(errores);\n\t\treturn false;\n\t} else {\n\t\tmensaje += \"¿Está usted seguro de que quiere modificar la reserva? \\n\";\n\t\tmensaje += \"Hora: \" + hora + \"\\n\";\n\t\tmensaje += \"Fecha: \" + fecha + \"\\n\";\n\n\t\treturn confirm(mensaje);\n\t}\n}",
"function adminConfirmation(){\n\tvar x = confirm(\"Are you sure you want to delete this user's account?\");\n\tif (x){\n return true;\n\t}else{\n\t return false;\n\t}\n}//end of confirmation"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function: reduceArguments() Global helper function for converting any of the above method calls into their apporiate form with/without a tenantspecific collection. | function reduceArguments() {
var collection;
var args = _.toArray(arguments);
var tenant = null;
//For tenants, find specific collection and remove the first argument
if (arguments.length > 0 && _.isString(arguments[0])) {
tenant = arguments[0];
collection = Platos._db.collection(tenant + Platos._options.separator + this._meta.collection);
args = _.rest(arguments);
} else {
collection = Platos._db.collection(this._meta.collection);
}
return { collection: collection, args: args, tenant: tenant };
} | [
"function flatten () {\n var flattened = [];\n slice.call(arguments, 0).forEach(function (arg) {\n if (arg != null) {\n if (Array.isArray(arg)) {\n flattened.push.apply(flattened, flatten.apply(this, arg));\n } else if (typeof arg == \"object\") {\n Object.keys(arg).forEach(function (key) {\n (Array.isArray(arg[key]) ? arg[key] : [ arg[key] ]).forEach(function (value) {\n flattened.push('--' + key);\n if (typeof value != 'boolean') flattened.push(value);\n });\n });\n } else {\n flattened.push(arg);\n }\n }\n });\n return flattened;\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}",
"function union(){\n //let arg = [].slice.call(arguments);\n let uniq = [];\n let arr = [];\n //solving it with CONCAT!!\n for(let i=0; i<arguments.length; i++){\n \t//CONACAT RETURNS A NEW ARR, which REFERENCE has to be saved in this case using the same arr var.\n arr = arr.concat(arguments[i]);\n }\n //solving it with PUSH!!\n // for (let i=0; i<arguments.length; i++){\n // for (let j=0; j<arguments[i].length; j++){\n // //console.log(\"arg[i][j] is \" + arg[i][j]);\n // uniq.push(arguments[i][j]);\n // }\n // }\n for (let j=0; j<arr.length; j++){\n if (!uniq.includes(arr[j])) uniq.push(arr[j]);\n }\n \n return uniq;\n}",
"function sumArgs() {\r\n return [].reduce.call(arguments, function(a, b) {\r\n return a + b;\r\n });\r\n}",
"function filterDuplicateQueryParams(req, res, next) {\n\n for (var key in req.query) {\n if (Array.isArray(req.query[key])) {\n req.query[key] = req.query[key][0];\n }\n }\n\n next();\n}",
"composeEntryCollectionLinkFields(collectionLinkFields, entry) {\n return collectionLinkFields.reduce((acc, fieldname) => {\n\n const key = fieldname + '___NODE';\n const newAcc = {\n ...acc,\n [key]: entry[fieldname]._id,\n };\n return newAcc;\n }, {});\n }",
"processAudienceFilters(values) {\n const oldTerms = this.props.filters[c.TYPE_AUDIENCE] || [];\n const newTerms = values[c.TYPE_AUDIENCE] || [];\n const tree = this.props.audienceOptions;\n\n let selected = newTerms;\n\n // Return if audiences are the same.\n if (oldTerms.length === newTerms.length) {\n return values;\n }\n\n // Which audience changed?\n const altered = xor(oldTerms, newTerms).pop();\n // Was audience added or removed?\n const op = oldTerms.length < newTerms.length ? 'add' : 'remove';\n // Does audience have children?\n const top = tree.filter(t => t.key === altered).pop();\n // If this is a parent apply same operation to children\n if (top) {\n const related = top.children.map(child => child.key);\n selected = op === 'add'\n ? uniq([].concat(newTerms, related))\n : difference(newTerms, related);\n }\n // If this is a child apply same operation to the parent based on all children\n else {\n // Find parent\n const related = tree.filter(\n node => node.children.filter(child => child.key === altered).length > 0\n ).pop();\n\n // If removing a child\n if (op === 'remove') {\n // Remove the parent\n selected = difference(newTerms, [related.key]);\n }\n // If adding a child and all children are selected\n else if (difference(related.children.map(child => child.key), newTerms).length === 0) {\n // Add the parent\n selected = uniq([].concat(newTerms, related.key));\n }\n }\n\n return {\n ...values,\n [c.TYPE_AUDIENCE]: selected,\n };\n }",
"function foo () {\n return fargs(arguments);\n }",
"getAllArgsToInterpolateSubmobject() {\n let mobjectHierarchies = [];\n for (let mobjectCopy of this.getCopiesForInterpolation()) {\n let hierarchy = mobjectCopy.getMobjectHierarchy();\n let hierarchyMembersWithPoints = hierarchy.filter(\n submob => submob.points().length > 0\n );\n mobjectHierarchies.push(hierarchyMembersWithPoints);\n }\n let argsList = [];\n for (let i = 0; i < mobjectHierarchies[0].length; i++) {\n argsList.push(mobjectHierarchies.map(h => h[i]));\n }\n return argsList;\n }",
"function sumEvenArguments(){\n\treturn [].slice.call(arguments).filter(i=>{\n\t\treturn (!(i%2));\n\t}).reduce((acc,next)=>{\n\t\treturn acc+next;\n\t});\n}",
"function getAllCommonParameters() {\n\treturn getCommonParameters()+\" AND ${parameters['totalArea']}\";\n}",
"function aggregateScopeLineItemCollection(lineItems, collection) {\n if(angular.isArray(lineItems)) {\n angular.forEach(lineItems, function(item) {\n collection.push(item);\n });\n } else {\n if(lineItems !== undefined) {\n collection.push(lineItems);\n }\n }\n }",
"function joinArrays(){\n var newArr = [...arguments];\n\tvar ret = [];\n\tnewArr.forEach(el => ret.push(...el));\n\treturn ret;\n}",
"static getAllTenants() {\n return HttpClient.get(`${IDENTITY_GATEWAY_ENDPOINT}tenants/all`).map(toTenantModel);\n }",
"_unionOfArrays(anomaliesById, filterType, selectedFilters) {\n //handle dimensions separately, since they are nested\n let addedIds = [];\n if (filterType === 'dimensionFilterMap' && isPresent(anomaliesById.searchFilters[filterType])) {\n selectedFilters.forEach(filter => {\n const [type, dimension] = filter.split('::');\n addedIds = [...addedIds, ...anomaliesById.searchFilters.dimensionFilterMap[type][dimension]];\n });\n } else if (filterType === 'statusFilterMap' && isPresent(anomaliesById.searchFilters[filterType])){\n const translatedFilters = selectedFilters.map(f => {\n // get the right object\n const mapping = anomalyResponseObjNew.filter(e => (e.name === f));\n // map the name to status\n return mapping.length > 0 ? mapping[0].status : f;\n });\n translatedFilters.forEach(filter => {\n addedIds = [...addedIds, ...anomaliesById.searchFilters[filterType][filter]];\n });\n } else {\n if (isPresent(anomaliesById.searchFilters[filterType])) {\n selectedFilters.forEach(filter => {\n // If there are no anomalies from the time range with these filters, then the result will be null, so we handle that here\n // It can happen for functionFilterMap only, because we are using subscription groups to map to alert names (function filters)\n const anomalyIdsInResponse = anomaliesById.searchFilters[filterType][filter];\n addedIds = anomalyIdsInResponse ? [...addedIds, ...anomaliesById.searchFilters[filterType][filter]] : addedIds;\n });\n }\n }\n return addedIds;\n }",
"visitFunction_argument_analytic(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"splitQueries(allQueries) {\n return allQueries.reduce((acc, val) => {\n // apiQuery : [Object] || graphqlQuery : {data: Object}\n if (Object.keys(val).includes('data')) {\n // it's a graphql query\n acc.graphqlApiQueries.push(val);\n } else {\n // it's an api query\n acc.apiQueries.push(val);\n }\n return acc;\n }, { apiQueries: [], graphqlApiQueries: [] });\n }",
"function TKR_formatContextQueryArgs() {\n let args = '';\n let colspec = _ctxDefaultColspec;\n const colSpecElem = TKR_getColspecElement();\n if (colSpecElem) {\n colspec = colSpecElem.value;\n }\n\n if (_ctxHotlistID != '') args += '&hotlist_id=' + _ctxHotlistID;\n if (_ctxCan != 2) args += '&can=' + _ctxCan;\n args += '&q=' + encodeURIComponent(_ctxQuery);\n if (_ctxSortspec != '') args += '&sort=' + _ctxSortspec;\n if (_ctxGroupBy != '') args += '&groupby=' + _ctxGroupBy;\n if (colspec != _ctxDefaultColspec) args += '&colspec=' + colspec;\n if (_ctxStart != 0) args += '&start=' + _ctxStart;\n if (_ctxNum != _ctxResultsPerPage) args += '&num=' + _ctxNum;\n if (!colSpecElem) args += '&mode=grid';\n return args;\n}",
"function packRestArguments(pattern, args) {\n if (pattern.all) {\n return [args];\n } else if (pattern.rest) {\n var firstArgs = _.head(args, pattern.args.length);\n var restArgs = _.tail(args, pattern.args.length);\n firstArgs.push(restArgs);\n return firstArgs;\n } else {\n return args;\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the Celebration state. | celebrate (state, status) {
state.celebrating = status
} | [
"function setConnectionState (state) {\n console.log('Connection state:', state)\n switch (state) {\n case Connection.DISCONNECTED:\n case Connection.CONNECTING:\n statusIcon.style.backgroundColor = 'yellow'\n break\n case Connection.CONNECTED:\n statusIcon.style.backgroundColor = 'green'\n break\n default:\n statusIcon.style.backgroundColor = 'red'\n break\n }\n statusText.innerText = state\n}",
"function setAtmState(newState) {\n atmMachine = Object.create(newState);\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 setControlState(powerState) {\n\tvar color = \"grey\";\n\tif (powerState)\n\t\tcolor = \"blue\";\n\tsetColor(\"manual\", color);\n\tsetColor(\"autopilot\", color);\n\tsetColor(\"left\", color);\n\tsetColor(\"right\", color);\n\tsetColor(\"up\", color);\n\tsetColor(\"down\", color);\n\tsetColor(\"center\", color);\n\tsetColor(\"stop\", color);\n\tsetColor(\"brake\", color);\n}",
"function setFrontBrake(isOn) {\n bicycle.frontBrake = true;\n}",
"changeState (state) {\n assert ('The state must be an instance of ModifierState', state instanceof ModifierState);\n\n if (!!this._currentState) {\n // Notify the current state we are exiting.\n this._currentState.willExitState ();\n this._currentState.modifier = null;\n }\n\n // Update the current state.\n this._currentState = state;\n\n if (!!this._currentState) {\n // Notify the new state we have entered.\n this._currentState.modifier = this;\n this._currentState.didEnterState ();\n }\n }",
"function setGpsState(state) {\n // Make sure the state changes\n if(Dworek.state.geoState == state)\n return;\n\n // Set the state\n Dworek.state.geoState = state;\n\n // Update the status labels\n updateStatusLabels();\n}",
"setStateOfCell(i,j){\n this.field[i][j].setState(true);\n this.field[i][j].draw();\n }",
"setInFrontier() {\n this.inFocus = false\n this.inFrontier = true\n }",
"setAnimationFlag(attributeName, state) {\n const arg = this.args[attributeName];\n\n if (arg && arg.anime !== state) {\n arg.anime = state;\n this.emit('state.change.animation', {\n animation: arg.anim,\n name: arg.name,\n instance: this,\n });\n return true;\n }\n\n return false;\n }",
"SET_ACTIVE_CHAR(state, char) {\n state.activeChar = char;\n }",
"set open(state) {\n this.skeleton.open = state;\n }",
"function changestate(){\n let stateplot=d3.select('#state_selected').node().value;\n buildplot(stateplot)}",
"function changeStatus() {\t\n\t\tseatNum = this.querySelector(\".seat-number\").innerHTML;\n\t\t\n\t\tif (this.className === \"empty\") {\n\t\t\t//if this seat is empty do dis\n\t\t\t\n\t\t\tgetForm();\n\n\t\t\tthis.setAttribute(\"class\", \"full\");\n\t\t\tseatImage = this.querySelector(\".chair-image\");\n\t\t\tseatImage.setAttribute(\"src\", \"images/chair-full.jpg\");\n\n\t\t} else {\n\t\t\t// if full uncheck :(\n\n\t\t\tthis.setAttribute(\"class\", \"empty\");\n\t\t\tseatImage = this.querySelector(\".chair-image\");\n\t\t\tseatImage.setAttribute(\"src\", \"images/chair-empty.jpg\");\n\n\t\t}\n\t}",
"function setConnectionState(opp, state) {\r\n var elDis;\r\n var elWat;\r\n var elCon;\r\n //console.log(\"setConnectionState\", opp, state);\r\n if (opp == \"rho\") {\r\n elDis = document.getElementById(\"rho-disconnected\");\r\n elWat = document.getElementById(\"rho-waiting\");\r\n elCon = document.getElementById(\"rho-connected\");\r\n }\r\n if (opp == \"lho\") {\r\n elDis = document.getElementById(\"lho-disconnected\");\r\n elWat = document.getElementById(\"lho-waiting\");\r\n elCon = document.getElementById(\"lho-connected\");\r\n }\r\n //console.log(elDis.classList, elWat.classList, elCon.classList);\r\n elDis.classList.remove(\"dot-red\");\r\n elCon.classList.remove(\"dot-green\");\r\n elWat.classList.remove(\"dot-yellow\");\r\n elDis.classList.add(\"dot-transparent\");\r\n elCon.classList.add(\"dot-transparent\");\r\n elWat.classList.add(\"dot-transparent\");\r\n //console.log(elDis.classList, elWat.classList, elCon.classList);\r\n if (state == \"disconnected\") {\r\n elDis.classList.add(\"dot-red\");\r\n elDis.classList.remove(\"dot-transparent\");\r\n }\r\n if (state == \"waiting\") {\r\n elWat.classList.add(\"dot-yellow\");\r\n elWat.classList.remove(\"dot-transparent\");\r\n }\r\n if (state == \"connected\") {\r\n elCon.classList.add(\"dot-green\");\r\n elCon.classList.remove(\"dot-transparent\");\r\n }\r\n //console.log(elDis.classList, elWat.classList, elCon.classList);\r\n}",
"function setCheckboxState(name, newState) {\r\n\tforms = document.forms;\r\n\tfor (f = 0; f < forms.length; f++) {\r\n\t\telements = forms[f].elements;\r\n\t\tfor (e = 0; e < elements.length; e++) {\r\n\t\t\tif (elements[e].name == name) {\r\n\t\t\t\telements[e].checked = newState;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}",
"ecoOn() {\n this._ecoMode(\"eco_on\");\n }",
"training() {\n const trainingOpponentSelection = TRAINING_SELECTION;\n\n this.setState({\n mode: Modes.ShipSelection,\n trainingOpponentSelection,\n trainingOpponentCommander: 0,\n trainingCp: this._selectionToCp(trainingOpponentSelection),\n });\n }",
"function setRegion() {\n\n\tvar oneRegion = isSingleRegion();\n\tif (oneRegion == false) {\n\t\t$(\"#tv-region-number\").html(\"...to the Machine!\");\n\t\t$(\"#tv-region-number\").css(\"background-color\", \"red\")\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
When part of the global board is tapped | function globalTapped() {
if(freeze || victory) return;
if(!boardData[this.board].isActive()) return;
select(this.board);
render();
} | [
"function handle_click(){\n // which tile?\n var tile = $(this);\n\n // don't do anything if just clicked or already matched\n if (tile.hasClass('active') || tile.hasClass('matched')) {\n // we're done\n return false;\n }\n\n // keep track of number of clicks\n num_clicks++;\n\n //activate tile\n activate_tile(tile);\n // maybe more here?\n\n if (is_two_selected() && is_current_selection_a_match()) {\n // implement\n }\n alert('clicked!');\n}",
"function activateSimonBoard(){\n $('.simon')\n .on('click', '[data-tile]', registerClick)\n\n .on('mousedown', '[data-tile]', function(){\n $(this).addClass('active');\n playSound($(this).data('tile'));\n })\n\n .on('mouseup', '[data-tile]', function(){\n $(this).removeClass('active');\n });\n\n $('[data-tile]').addClass('hoverable');\n }",
"_onTap(x,y){\n console.log('tap!', x, y)\n //save screen coordinates normalized to -1..1 (0,0 is at center and 1,1 is at top right)\n this._tapEventData = [\n x / window.innerWidth,\n y / window.innerHeight\n ]\n }",
"tileClicked (x, y, value) {\n console.log(this.props.players)\n console.log(\"clicked \", x,y);\n //sent the event to all players\n //TODO: should be done with events\n this.props.players.forEach(player => player.tileClicked({x,y, value}));\n }",
"__handleClick(evt) {\n // get x from ID of clicked cell\n const x = +evt.target.id[0]\n \n // get next spot in column (if none, ignore click)\n const y = this.__findSpotForCol( x );\n if (y === null) {\n return;\n }\n \n // place piece in board and add to HTML table\n this.placePiece(x, y);\n \n // check for win\n if (this.__checkForWin( x, y )) {\n return this.__endGame(`Player ${this.currPlayer} won!`);\n }\n \n // check for tie\n if ( this.__innerBoard.every(row => row[ this.height-1 ]) ) {\n return this.__endGame('Tie!');\n }\n\n // switch currPlayer\n this.switchCurrentPlayer()\n }",
"viewWasClicked (view) {\n\t\t\n\t}",
"autoPositionBoats() {\n this.HTMLElement.autoPositionButton.addEventListener('click', () => {\n if (!this.gameEvent.isStart()) {\n this.grid1.reset();\n this.grid1.installBoatAuto();\n this.grid1.validPositionAuto();\n }\n else\n GameEvent.infoGame('La partie a commencé');\n })\n }",
"function yellowClick() {\n\tyellowLight();\n\tuserPlay.push(3);\n\tuserMovement();\t\n}",
"function gridClickListener(event) {\n const ctx = canvas.getContext('2d');\n\n let [row, col] = translateClickPosition(event);\n\n console.log(\"clicked [\",row ,\"][\",col, \"]\");\n\n // start the timer once a grid cell is clicked (if it hasn't been started already)\n if (!timer) setTimer();\n\n if (event.ctrlKey) {\n // mark a cell with a question mark\n minesweeper.toggleQuestion(row, col);\n } else if (event.shiftKey) {\n // flag a cell\n minesweeper.toggleFlag(row, col);\n } else {\n // cell was left clicked, reveal the cell\n minesweeper.revealCell(row, col);\n }\n\n // check if game is won or lost\n if (minesweeper.isGameWon()) {\n renderGameWon(ctx);\n } else if (minesweeper.isGameLost()) {\n renderGameLost(ctx);\n } else {\n // game is not over, so render the grid state\n renderGrid(ctx);\n mineCounter.innerText = minesweeper.remainingFlags().toString(10).padStart(3, \"0\");\n }\n\n}",
"function handleMouseDownEvent(){\n board.selectAll(\".void, .wall, .start, .end\").on(\"mousemove\", handleMouseMoveEvent);\n}",
"clickListener(e) {\n if (this.selectedMapCube !== null && this.selectedMapCube != this.selectedCube) {\n this.enhancedCubes = [];\n this.scaffoldingCubesCords = null;\n this.selectedCube = this.selectedMapCube;\n let directions = this.ref.methods.getDirections(this.selectedMapCube);\n // this.ref.updateRoom(this.selectedMapCube, directions);\n this.ref.room.navigateToRoom(this.selectedMapCube, directions, true);\n this.repaintMapCube(ref.cubes, \"\", [], null, false, this.selectedMapCube);\n //this.repaintMapCube(hoverCubeArr, this.selectedMapCube.label);\n }\n }",
"function mousePressed() {\n if (state === `title`) {\n state = `game`;\n } else if (state === `game`) {\n checkCircleClick();\n }\n}",
"function onActivatedSurface(tuples, eventName, $event, range, nativeEvent) {\n var i;\n for (i = 0; i < tuples.length; i++) {\n if (tuples[i][0].isActive()) {\n tuples[i][1]($event, range, nativeEvent);\n }\n }\n }",
"function elementClickedHandler() {\n\n showToolbar(this);\n\n }",
"markerClick() {\n store.setActiveSection(store.currentFileSha, this.section);\n }",
"function registerClick(e) {\n var desiredResponse = copy.shift();\n var actualResponse = $(e.target).data('tile');\n active = (desiredResponse === actualResponse);\n checkLose();\n }",
"function triggerCol(col) {\n col = floor(col);\n\n for (let r = 0; r < rows; r++) {\n if (grid[r][col]) {\n chirps[r][currentBank].play();\n }\n }\n}",
"function lvCockpitsItemInvoked(e) {\n e.detail.itemPromise.done(function (item) {\n DataExplorer.drawTile(item.data);\n });\n }",
"function handleClickCard (item){\n // move to \"ground\" screen\n props.navigation.navigate(\"Ground\", {data: item});\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create device with texture format(s) required feature(s). If the device creation fails, then skip the test for that format(s). | async selectDeviceForTextureFormatOrSkipTestCase(formats) {
if (!Array.isArray(formats)) {
formats = [formats];
}
const features = new Set();
for (const format of formats) {
if (format !== undefined) {
features.add(kTextureFormatInfo[format].feature);
}
}
await this.selectDeviceOrSkipTestCase(Array.from(features));
} | [
"function createDevice(src){\n\tvar devPath = \"Device_\" + deviceCtr;\n\tidsArray = [];\n\tidsArray = getalldevicepath(idsArray);\n\tif(idsArray.length == 0){\n\t\tcreateConfigName(); \n\t}\n\tvar str ='';\n\tif(idsArray.indexOf(devPath) == -1){\n\t\tvar imageObj = new Image();\n\t\tvar srcN = ($(src).attr('src')).split(\"img\");\n\t\timageObj.src = dir+\"/img\"+srcN[1];\n\t\tvar id = $(src).attr('id');\n\t\tvar model = $(src).attr('model');\n\t\tvar manufac = $(src).attr('manufacturer');\n\t\tvar ostyp = $(src).attr('ostype');\n\t\tvar prdfmly = $(src).attr('productfamily');\n\t\tvar ipadd = $(src).attr('ipAdd');\n\t\tvar prot = $(src).attr('proto');\n\t\tvar hostnme = $(src).attr('hostname');\n\t\tvar devtype = $(src).attr('devtype');\n\t\tvar rTr=0;\n\t\tvar devices = getDevicesNodeJSON();\n\t\tfor(var a=0; a < devices.length; a++){\n\t\t\tif(devices[a].HostName == hostnme && hostnme != \"\" && devtype.toLowerCase() == \"dut\"){\n\t\t\t\treturn;\n\t\t\t}else if(devices[a].ManagementIp == ipadd && ipadd != \"\" && devtype.toLowerCase() == \"testtool\"){\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tif(globalInfoType == \"JSON\"){\n\t\t\tsetJSONData();\n\t\t\tsetDeviceInformation(devPath,model,imageObj,manufac,ostyp,prdfmly,ipadd,prot,hostnme,devtype);\n\t\t\timgXPos+=70;\n \t\t\tidsArray.push(devPath);\n\t\t deviceCtr++;\n\t\t drawImage();\n\t\t}else{\n\t\t\tvar devices = devicesArr;\n\t\t\timageObj.onload = function() {\n\t\t\t\tsetDeviceInformation(devPath,model,imageObj,manufac,ostyp,prdfmly,ipadd,prot,hostnme);\n\t\t\t\timgXPos+=70;\n\t\t\t\tidsArray.push(devPath);\n\t\t\t\tdeviceCtr++;\n\t\t\t\tdrawImage();\n\t\t\t};\n\t\t}\n\t\tsetTimeout(function(){\n var ctrDck=0;\n for(var a=0; a < dynamicGreenRouletteArr.length; a++){\n var dkArr = dynamicGreenRouletteArr[a];\n if(dkArr.pageCanvas == pageCanvas){\n if(dkArr.model == model && dkArr.manufac == manufac && dkArr.ostyp == ostyp && dkArr.prdfmly == prdfmly && dkArr.ipadd==ipadd && dkArr.prot == prot && dkArr.hostnme == hostnme && dkArr.devtype == devtype){\n ctrDck++;\n a =dynamicGreenRouletteArr.length;\n }else if(dkArr.model == model && manufac == undefined && ostyp == undefined && prdfmly == undefined && ipadd== undefined && prot == undefined && hostnme && hostnme == undefined){\n ctrDck++;\n a =dynamicGreenRouletteArr.length;\n }\n }\n }\n if(ctrDck == 0){\n dynamicGreenRouletteArr.push({\"pageCanvas\":pageCanvas,\"devPath\":devPath,\"model\":model,\"imageObj\":imageObj,\"manufac\":manufac,\"ostyp\":ostyp,\"prdfmly\":prdfmly,\"ipadd\":ipadd,\"prot\":prot,\"hostnme\":hostnme,\"devtype\":devtype});\n }else{\n return;\n }\n\t\t\t$(\"#dockContainer\").show();\n\t\t\tvar text = createDeviceTooltip(devPath);\n\t\t\tstr += '<li>';\n\t\t\tstr += '<div class=\"divTooltipDock\">'+text+'</div>';\n\t\t\tstr += '<a href=\"#\" title=\"'+devPath+'\"><img id=\"'+devPath+hostnme+pageCanvas+'\" alt=\"'+devPath+' icon\" src=\"'+imageObj.src+'\" devpath=\"'+devPath+'\" class=\"dockImg\" width=\"62px\" hostname=\"'+hostnme+'\" proto=\"'+prot+'\" devtype=\"'+devtype+'\" ipAdd=\"'+ipadd+'\" productFamily=\"'+prdfmly+'\" ostype=\"'+ostyp+'\" manufacturer=\"'+manufac+'\" did=\"device\" model=\"'+model+'\"/></a>';\n\t\t\tstr += '</li>';\n\t\t\t$(\"#osxDocUL\").append(str);\n \n if(globalDeviceType != \"Mobile\"){\n $(\"#\"+devPath+hostnme+pageCanvas).click(function(e){\n\t\t\t\t\tcreatedev = this;\n\t\t \tvar srcN = getMiniModelImage($(this).attr('model'));\n\t\t\t\t\tsrcN = ($(srcN).attr('src')).split(\"img\")[1];\n\t\t\t\t\t$(\"#configContent\"+pageCanvas).css(\"cursor\",\"url(\"+dir+\"/img/\"+srcN+\") 10 18,auto\");\n clickIcon(this);\n });\n }else{\n $.mobile.document.on( \"taphold\",\"#\"+devPath+hostnme+pageCanvas, function(e){\n //$(\"#\"+devPath+hostnme).dblclick(function(e){\n createdev = this;\n \tclickIcon(this);\n\t\t });\n }\n\t\t\tvar el = $(\"#dockWrapper\");\n var w = el.width() + 40;\n var dvded = -Math.abs(w / 2);\n var css = {\"position\": 'absolute', \"left\": \"50%\",\"width\": w+\"px\",\"margin-left\":dvded};\n $(\"#dockContainer\").css(css);\n\t\t\t\n\t\t},100);\t\t\n\t\taddEvent2History(\"Created a device.\");\n\t}else{\n\t\tdeviceCtr++;\n\t\tcreateConfigName();\n\t\tcreateDevice(src);\n\t}\n}",
"_setupFramebuffers(opts) {\n const {\n textures,\n framebuffers,\n maxMinFramebuffers,\n minFramebuffers,\n maxFramebuffers,\n meanTextures,\n equations\n } = this.state;\n const {\n weights\n } = opts;\n const {\n numCol,\n numRow\n } = opts;\n const framebufferSize = {\n width: numCol,\n height: numRow\n };\n\n for (const id in weights) {\n const {\n needMin,\n needMax,\n combineMaxMin,\n operation\n } = weights[id];\n textures[id] = weights[id].aggregationTexture || textures[id] || Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_11__[\"getFloatTexture\"])(this.gl, {\n id: `${id}-texture`,\n width: numCol,\n height: numRow\n });\n textures[id].resize(framebufferSize);\n let texture = textures[id];\n\n if (operation === _aggregation_operation_utils__WEBPACK_IMPORTED_MODULE_5__[\"AGGREGATION_OPERATION\"].MEAN) {\n // For MEAN, we first aggregatet into a temp texture\n meanTextures[id] = meanTextures[id] || Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_11__[\"getFloatTexture\"])(this.gl, {\n id: `${id}-mean-texture`,\n width: numCol,\n height: numRow\n });\n meanTextures[id].resize(framebufferSize);\n texture = meanTextures[id];\n }\n\n if (framebuffers[id]) {\n framebuffers[id].attach({\n [_luma_gl_constants__WEBPACK_IMPORTED_MODULE_0__[\"default\"].COLOR_ATTACHMENT0]: texture\n });\n } else {\n framebuffers[id] = Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_11__[\"getFramebuffer\"])(this.gl, {\n id: `${id}-fb`,\n width: numCol,\n height: numRow,\n texture\n });\n }\n\n framebuffers[id].resize(framebufferSize);\n equations[id] = _gpu_grid_aggregator_constants__WEBPACK_IMPORTED_MODULE_4__[\"EQUATION_MAP\"][operation] || _gpu_grid_aggregator_constants__WEBPACK_IMPORTED_MODULE_4__[\"EQUATION_MAP\"].SUM; // For min/max framebuffers will use default size 1X1\n\n if (needMin || needMax) {\n if (needMin && needMax && combineMaxMin) {\n if (!maxMinFramebuffers[id]) {\n texture = weights[id].maxMinTexture || this._getMinMaxTexture(`${id}-maxMinTexture`);\n maxMinFramebuffers[id] = Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_11__[\"getFramebuffer\"])(this.gl, {\n id: `${id}-maxMinFb`,\n texture\n });\n }\n } else {\n if (needMin) {\n if (!minFramebuffers[id]) {\n texture = weights[id].minTexture || this._getMinMaxTexture(`${id}-minTexture`);\n minFramebuffers[id] = Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_11__[\"getFramebuffer\"])(this.gl, {\n id: `${id}-minFb`,\n texture\n });\n }\n }\n\n if (needMax) {\n if (!maxFramebuffers[id]) {\n texture = weights[id].maxTexture || this._getMinMaxTexture(`${id}-maxTexture`);\n maxFramebuffers[id] = Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_11__[\"getFramebuffer\"])(this.gl, {\n id: `${id}-maxFb`,\n texture\n });\n }\n }\n }\n }\n }\n }",
"function createDevice(data) {\n var device = new models[\"Device\"](),\n deviceData = networkInfo.device[0];\n\n $.each(deviceData, function(key, value) {\n if (key !== \"value\") {\n device.set(key, value);\n }\n });\n\n return device;\n}",
"_setupFramebuffers(opts) {\n const {\n textures,\n framebuffers,\n maxMinFramebuffers,\n minFramebuffers,\n maxFramebuffers,\n meanTextures,\n equations\n } = this.state;\n const {weights} = opts;\n const {numCol, numRow} = opts;\n const framebufferSize = {width: numCol, height: numRow};\n for (const id in weights) {\n const {needMin, needMax, combineMaxMin, operation} = weights[id];\n textures[id] =\n weights[id].aggregationTexture ||\n textures[id] ||\n Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_9__[\"getFloatTexture\"])(this.gl, {id: `${id}-texture`, width: numCol, height: numRow});\n textures[id].resize(framebufferSize);\n let texture = textures[id];\n if (operation === _aggregation_operation_utils__WEBPACK_IMPORTED_MODULE_3__[\"AGGREGATION_OPERATION\"].MEAN) {\n // For MEAN, we first aggregatet into a temp texture\n meanTextures[id] =\n meanTextures[id] ||\n Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_9__[\"getFloatTexture\"])(this.gl, {id: `${id}-mean-texture`, width: numCol, height: numRow});\n meanTextures[id].resize(framebufferSize);\n texture = meanTextures[id];\n }\n if (framebuffers[id]) {\n framebuffers[id].attach({[_luma_gl_constants__WEBPACK_IMPORTED_MODULE_0___default.a.COLOR_ATTACHMENT0]: texture});\n } else {\n framebuffers[id] = Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_9__[\"getFramebuffer\"])(this.gl, {\n id: `${id}-fb`,\n width: numCol,\n height: numRow,\n texture\n });\n }\n framebuffers[id].resize(framebufferSize);\n equations[id] = _gpu_grid_aggregator_constants__WEBPACK_IMPORTED_MODULE_2__[\"EQUATION_MAP\"][operation] || _gpu_grid_aggregator_constants__WEBPACK_IMPORTED_MODULE_2__[\"EQUATION_MAP\"].SUM;\n // For min/max framebuffers will use default size 1X1\n if (needMin || needMax) {\n if (needMin && needMax && combineMaxMin) {\n if (!maxMinFramebuffers[id]) {\n texture = weights[id].maxMinTexture || this._getMinMaxTexture(`${id}-maxMinTexture`);\n maxMinFramebuffers[id] = Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_9__[\"getFramebuffer\"])(this.gl, {id: `${id}-maxMinFb`, texture});\n }\n } else {\n if (needMin) {\n if (!minFramebuffers[id]) {\n texture = weights[id].minTexture || this._getMinMaxTexture(`${id}-minTexture`);\n minFramebuffers[id] = Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_9__[\"getFramebuffer\"])(this.gl, {\n id: `${id}-minFb`,\n texture\n });\n }\n }\n if (needMax) {\n if (!maxFramebuffers[id]) {\n texture = weights[id].maxTexture || this._getMinMaxTexture(`${id}-maxTexture`);\n maxFramebuffers[id] = Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_9__[\"getFramebuffer\"])(this.gl, {\n id: `${id}-maxFb`,\n texture\n });\n }\n }\n }\n }\n }\n }",
"function create3DTarget(target) {\n let loader = new THREE.TextureLoader();\n let planetSize = .5;\n loader.load(`./assets/img/targets/${target.name}.jpg`, (texture) => {\n let geom = new THREE.SphereGeometry(planetSize, 30, 30);\n let mat = (target.name == 'Sun') ? new THREE.MeshBasicMaterial({map: texture}) : new THREE.MeshLambertMaterial({map: texture});\n let planet = new THREE.Mesh(geom, mat);\n planet.name = target.name; planet.targetIndex = targets.indexOf(target);\n // Positioning\n let targetCartesian = Math.cartesian(target.az, target.el, gridRadius);\n planet.position.x = -targetCartesian.x;\n planet.position.z = -targetCartesian.z;\n planet.position.y = targetCartesian.y;\n planet.lookAt(0, 0, 0); planet.rotateY(Math.radians(target.az));\n // Target specific features\n if (planet.name == 'Saturn') {\n loader.load(`./assets/img/targets/SaturnRing.png`, (texture) => {\n geom = new THREE.RingGeometry(planetSize * 1.116086235489221, planetSize * 2.326699834162521, 84, 1);\n for(var yi = 0; yi < geom.parameters.phiSegments; yi++) {\n var u0 = yi / geom.parameters.phiSegments;\n var u1=(yi + 1) / geom.parameters.phiSegments;\n for(var xi = 0; xi < geom.parameters.thetaSegments; xi++) {\n \t\tvar fi = 2 * (xi + geom.parameters.thetaSegments * yi);\n var v0 = xi / geom.parameters.thetaSegments;\n var v1 = (xi + 1) / geom.parameters.thetaSegments;\n geom.faceVertexUvs[0][fi][0].x = u0; geom.faceVertexUvs[0][fi][0].y = v0;\n geom.faceVertexUvs[0][fi][1].x = u1; geom.faceVertexUvs[0][fi][1].y = v0;\n geom.faceVertexUvs[0][fi][2].x = u0; geom.faceVertexUvs[0][fi][2].y = v1;\n fi++;\n geom.faceVertexUvs[0][fi][0].x = u1; geom.faceVertexUvs[0][fi][0].y = v0;\n geom.faceVertexUvs[0][fi][1].x = u1; geom.faceVertexUvs[0][fi][1].y = v1;\n geom.faceVertexUvs[0][fi][2].x = u0; geom.faceVertexUvs[0][fi][2].y = v1;\n }\n }\n mat = new THREE.MeshLambertMaterial( { map: texture, side: THREE.DoubleSide, transparent: true } );\n let ring = new THREE.Mesh(geom, mat);\n ring.rotateX(27);\n planet.add(ring);\n });\n } else if (target.name == 'Sun') {\n const light = new THREE.PointLight('#d4caba', 1, 500, 0 );\n let lightCartesian = Math.cartesian(target.az, target.el, gridRadius - .5);\n light.position.x = -lightCartesian.x;\n light.position.y = lightCartesian.y;\n light.position.z = -lightCartesian.z;\n scene.add(light);\n }\n // planet.add(new THREE.AxesHelper(5));\n scene.add(planet);\n });\n}",
"function createTextureArray(gl, array) {\n var dtype = array.dtype\n var shape = array.shape.slice()\n var maxSize = gl.getParameter(gl.MAX_TEXTURE_SIZE)\n if(shape[0] < 0 || shape[0] > maxSize || shape[1] < 0 || shape[1] > maxSize) {\n throw new Error('gl-texture2d: Invalid texture size')\n }\n var packed = isPacked(shape, array.stride.slice())\n var type = 0\n if(dtype === 'float32') {\n type = gl.FLOAT\n } else if(dtype === 'float64') {\n type = gl.FLOAT\n packed = false\n dtype = 'float32'\n } else if(dtype === 'uint8') {\n type = gl.UNSIGNED_BYTE\n } else {\n type = gl.UNSIGNED_BYTE\n packed = false\n dtype = 'uint8'\n }\n var format = 0\n if(shape.length === 2) {\n format = gl.LUMINANCE\n shape = [shape[0], shape[1], 1]\n array = ndarray(array.data, shape, [array.stride[0], array.stride[1], 1], array.offset)\n } else if(shape.length === 3) {\n if(shape[2] === 1) {\n format = gl.ALPHA\n } else if(shape[2] === 2) {\n format = gl.LUMINANCE_ALPHA\n } else if(shape[2] === 3) {\n format = gl.RGB\n } else if(shape[2] === 4) {\n format = gl.RGBA\n } else {\n throw new Error('gl-texture2d: Invalid shape for pixel coords')\n }\n } else {\n throw new Error('gl-texture2d: Invalid shape for texture')\n }\n if(type === gl.FLOAT && !gl.getExtension('OES_texture_float')) {\n type = gl.UNSIGNED_BYTE\n packed = false\n }\n var buffer, buf_store\n var size = array.size\n if(!packed) {\n var stride = [shape[2], shape[2]*shape[0], 1]\n buf_store = pool.malloc(size, dtype)\n var buf_array = ndarray(buf_store, shape, stride, 0)\n if((dtype === 'float32' || dtype === 'float64') && type === gl.UNSIGNED_BYTE) {\n convertFloatToUint8(buf_array, array)\n } else {\n ops.assign(buf_array, array)\n }\n buffer = buf_store.subarray(0, size)\n } else if (array.offset === 0 && array.data.length === size) {\n buffer = array.data\n } else {\n buffer = array.data.subarray(array.offset, array.offset + size)\n }\n var tex = initTexture(gl)\n gl.texImage2D(gl.TEXTURE_2D, 0, format, shape[0], shape[1], 0, format, type, buffer)\n if(!packed) {\n pool.free(buf_store)\n }\n return new Texture2D(gl, tex, shape[0], shape[1], format, type)\n }",
"function createInterface(src){\n\tvar devPath = \"Device_\"+deviceCtr;\n if(idsArray.indexOf(devPath) == -1){\n var imageObj = new Image();\n var srcN = ($(src).attr('src')).split(\"img\");\n imageObj.src = dir+\"/img\"+srcN[1];\n var id = $(src).attr('id');\n var model = $(src).attr('model');\n\t\tif(globalInfoType == \"JSON\"){\n\t var devices = getDevicesNodeJSON();\n\t }else{\n \t var devices =devicesArr;\n\t }\n imageObj.onload = function() {\n setDeviceInformation(devPath,model,imageObj);\n imgXPos+=50;\n // if(devices.length == 9){\n // imgYPos+=50;\n // imgXPos=152;\n // }else if(devices.length == 18){\n // imgYPos+=50;\n // imgXPos=152;\n //}\n idsArray.push(devPath);\n deviceCtr++;\n drawImage();\n };\n }else{\n deviceCtr++;\n createInterface(src);\n }\n}",
"function createBatch(msg,batchFormat){\n if(batchFormat.length < 3){\n msg.channel.send(\"Invalid format. Please enter a create command of the following format:\\n !create | batch_name | [item1,item2] | type\\n Valid types: ah, bazaar\");\n }\n else if (batchFormat[3] !== \"ah\" && batchFormat[3] !== \"bazaar\"){\n msg.channel.send(\"Invalid batch type.\");\n }\n else{\n let newBatch = {\n name: batchFormat[1],\n items: JSON.parse(batchFormat[2]),\n track: true,\n type: batchFormat[3]\n };\n batches.push(newBatch); \n msg.channel.send(\"Batch successfully created.\\n\" + JSON.stringify(newBatch,null,2));\n updateBatchFile();\n }\n}",
"updateTexture() {\n let width = 1;\n let height = 1;\n let depth = 1;\n if(this.props.activations){\n this.activations = this.props.activations\n const [b, w, h, c] = this.props.activationShape;\n\n width = w;//sqrtW;\n height = h;//sqrtW;\n depth = c;\n } else{\n this.activations = this.defatultActivations;\n }\n\n //this.activationTexture = new RawTexture(this.activations, width, height,\n // Engine.TEXTUREFORMAT_RED, this.scene, false, false,\n // Texture.BILINEAR_SAMPLINGMODE, Engine.TEXTURETYPE_FLOAT);\n\n let sz;\n let sizeMatches = false;\n if(this.activationTexture) {\n sz = this.activationTexture.getSize();\n sizeMatches = (sz.width === width && sz.height === height\n && this.lastDepth === depth);\n }\n if(!this.activationTexture || !sizeMatches) {\n if(this.activationTexture){\n this.activationTexture.dispose();\n }\n this.activationTexture = new RawTexture3D(this.activations, width, height,\n depth, Engine.TEXTUREFORMAT_RED, this.scene, false, false,\n Texture.NEAREST_SAMPLINGMODE, Engine.TEXTURETYPE_FLOAT);\n } else {\n this.activationTexture.update(this.activations);\n }\n\n this.shaderMaterial.setTexture('textureSampler', this.activationTexture);\n this.lastDepth = depth;\n }",
"static _create2DShape (typeofShape, width, depth, height, scene) {\n switch (typeofShape) {\n case 0:\n var faceUV = new Array(6)\n for (let i = 0; i < 6; i++) {\n faceUV[i] = new BABYLON.Vector4(0, 0, 0, 0)\n }\n faceUV[4] = new BABYLON.Vector4(0, 0, 1, 1)\n faceUV[5] = new BABYLON.Vector4(0, 0, 1, 1)\n \n var options = {\n width: width,\n height: height,\n depth: depth,\n faceUV: faceUV\n }\n\n return BABYLON.MeshBuilder.CreateBox('pin', options, scene)\n case 1:\n var faceUV2 = new Array(6)\n for (let i = 0; i < 6; i++) {\n faceUV2[i] = new BABYLON.Vector4(0, 0, 0, 0)\n }\n faceUV2[0] = new BABYLON.Vector4(0, 0, 1, 1)\n \n var options2 = {\n diameterTop: width,\n diameterBottom: depth,\n height: height,\n tessellation: 32,\n faceUV: faceUV2\n }\n\n return BABYLON.MeshBuilder.CreateCylinder('pin', options2, scene)\n }\n }",
"function construct_device(devices_data, device_type){\n var device_data = get_device_data(devices_data, device_type);\n var device_map = {};\n return construct_device_inner(devices_data, device_data, device_map, '/');\n}",
"function createDataTexture(gl, floatArray) {\n var width = floatArray.length / 4, // R,G,B,A\n height = 1,\n texture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, texture);\n gl.texImage2D(gl.TEXTURE_2D,\n 0, gl.RGBA, width, height, 0, gl.RGBA, gl.FLOAT, floatArray);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n return texture;\n }",
"function tryToLoadCustomTexture(textureTest) {\n for (let modelTest of eachModelTest()) {\n const model = modelTest.resource;\n\n for (let i = 0, l = model.textures.length; i < l; i++) {\n const modelTexture = model.textures[i];\n\n // If the texture failed to load, check if it matches the name.\n if (!modelTexture.ok && areSameFiles(modelTexture.fetchUrl, textureTest.name)) {\n model.textures[i] = textureTest.resource;\n\n console.log(`NOTE: loaded ${textureTest.name} as a custom texture for model: ${modelTest.name}`);\n }\n }\n }\n}",
"function parseTexture(gl, textureJSON) {\n checkParameter(\"parseTexture\", gl, \"gl\");\n checkParameter(\"parseTexture\", textureJSON, \"textureJSON\");\n var width = textureJSON[\"width\"];\n checkParameter(\"parseTexture\", width, \"textureJSON[width]\");\n var height = textureJSON[\"height\"];\n checkParameter(\"parseTexture\", height, \"textureJSON[height]\");\n var data = textureJSON[\"data\"];\n checkParameter(\"parseTexture\", data, \"textureJSON[data]\");\n var texture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, texture);\n gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);\n gl.activeTexture(gl.TEXTURE0);\n texture.image = new Image();\n texture.image.src = data;\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, texture.image);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_R, gl.REPEAT);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);\n}",
"render(program, renderParameters, textures){\n //renders the media source to the WebGL context using the pased program\n let overriddenElement;\n for (let i = 0; i < this.mediaSourceListeners.length; i++) {\n if (typeof this.mediaSourceListeners[i].render === 'function'){\n let result = this.mediaSourceListeners[i].render(this, renderParameters);\n if (result !== undefined) overriddenElement = result;\n }\n }\n\n this.gl.useProgram(program);\n let renderParametersKeys = Object.keys(renderParameters);\n let textureOffset = 1;\n for (let index in renderParametersKeys){\n let key = renderParametersKeys[index];\n let parameterLoctation = this.gl.getUniformLocation(program, key);\n if (parameterLoctation !== -1){\n if (typeof renderParameters[key] === \"number\"){\n this.gl.uniform1f(parameterLoctation, renderParameters[key]);\n }\n else if( Object.prototype.toString.call(renderParameters[key]) === '[object Array]'){\n let array = renderParameters[key];\n if(array.length === 1){\n this.gl.uniform1fv(parameterLoctation, array);\n } else if(array.length === 2){\n this.gl.uniform2fv(parameterLoctation, array);\n } else if(array.length === 3){\n this.gl.uniform3fv(parameterLoctation, array);\n } else if(array.length === 4){\n this.gl.uniform4fv(parameterLoctation, array);\n } else{\n console.debug(\"Shader parameter\", key, \"is too long and array:\", array);\n }\n }\n else{\n //Is a texture\n this.gl.activeTexture(this.gl.TEXTURE0 + textureOffset);\n this.gl.uniform1i(parameterLoctation, textureOffset);\n this.gl.bindTexture(this.gl.TEXTURE_2D, textures[textureOffset-1]);\n }\n }\n }\n \n this.gl.activeTexture(this.gl.TEXTURE0);\n let textureLocation = this.gl.getUniformLocation(program, \"u_image\");\n this.gl.uniform1i(textureLocation, 0);\n this.gl.bindTexture(this.gl.TEXTURE_2D, this.texture);\n if (overriddenElement !== undefined){\n this.gl.texImage2D(this.gl.TEXTURE_2D, 0, this.gl.RGBA, this.gl.RGBA, this.gl.UNSIGNED_BYTE, overriddenElement);\n } else {\n this.gl.texImage2D(this.gl.TEXTURE_2D, 0, this.gl.RGBA, this.gl.RGBA, this.gl.UNSIGNED_BYTE, this.element);\n }\n this.gl.drawArrays(this.gl.TRIANGLES, 0, 6);\n }",
"function setFlags() {\n\n var WEBGL_VERSION = 2\n var WASM_HAS_SIMD_SUPPORT = false\n var WASM_HAS_MULTITHREAD_SUPPORT = false\n var WEBGL_CPU_FORWARD = true\n var WEBGL_PACK = true\n var WEBGL_FORCE_F16_TEXTURES = false\n var WEBGL_RENDER_FLOAT32_CAPABLE = true\n var WEBGL_FLUSH_THRESHOLD = -1\n var CHECK_COMPUTATION_FOR_ERRORS = false\n\n wasmFeatureDetect.simd().then(simdSupported => {\n if (simdSupported) {\n // alert(\"simd supported\")\n WASM_HAS_SIMD_SUPPORT = true\n } else {\n // alert(\"no simd\")\n }\n });\n wasmFeatureDetect.threads().then(threadsSupported => {\n if (threadsSupported) {\n // alert(\"multi thread supported\")\n WASM_HAS_MULTITHREAD_SUPPORT = true;\n } else {\n // alert(\"no multi thread\")\n }\n });\n switch (getOS()) {\n case 'Mac OS':\n // alert('Mac detected')\n WEBGL_VERSION = 1\n break;\n case 'Linux':\n // alert('linux detected')\n break;\n case 'iOS':\n // alert('ios detected')\n WEBGL_VERSION = 1\n WEBGL_FORCE_F16_TEXTURES = true //use float 16s on mobile just incase \n WEBGL_RENDER_FLOAT32_CAPABLE = false\n break;\n case 'Android':\n WEBGL_FORCE_F16_TEXTURES = true\n WEBGL_RENDER_FLOAT32_CAPABLE = false\n line_width = 3\n radius = 4\n // alert('android detected')\n break;\n default:\n // alert('windows detected')\n break;\n\n }\n\n var flagConfig = {\n WEBGL_VERSION: WEBGL_VERSION,\n WASM_HAS_SIMD_SUPPORT: WASM_HAS_SIMD_SUPPORT,\n WASM_HAS_MULTITHREAD_SUPPORT: WASM_HAS_MULTITHREAD_SUPPORT,\n WEBGL_CPU_FORWARD: WEBGL_CPU_FORWARD,\n WEBGL_PACK: WEBGL_PACK,\n WEBGL_FORCE_F16_TEXTURES: WEBGL_FORCE_F16_TEXTURES,\n WEBGL_RENDER_FLOAT32_CAPABLE: WEBGL_RENDER_FLOAT32_CAPABLE,\n WEBGL_FLUSH_THRESHOLD: WEBGL_FLUSH_THRESHOLD,\n CHECK_COMPUTATION_FOR_ERRORS: CHECK_COMPUTATION_FOR_ERRORS,\n }\n\n setEnvFlags(flagConfig)\n\n}",
"function initFramebuffer() {\n // texture information in frame buffer\n DofDemo.rttTexture = new THREE.WebGLRenderTarget(DofDemo.windowWidth, \n DofDemo.windowHeight, {\n wrapS: THREE.RepeatWrapping,\n wrapT: THREE.RepeatWrapping,\n minFilter: THREE.LinearFilter,\n magFilter: THREE.NearestFilter,\n format: THREE.RGBAFormat\n });\n \n // depth information in frame buffer\n DofDemo.rttDepth = new THREE.WebGLRenderTarget(DofDemo.windowWidth, \n DofDemo.windowHeight, {\n wrapS: THREE.RepeatWrapping,\n wrapT: THREE.RepeatWrapping,\n minFilter: THREE.LinearFilter,\n magFilter: THREE.NearestFilter,\n format: THREE.RGBAFormat\n });\n}",
"function findImageDevice(type,manu,model){\n\tvar st = \"\";\n\ttype = type.toLowerCase();\n\tmanu = manu.toLowerCase();\n\tmodel = model.toLowerCase();\n\tif(type.toLowerCase() == \"dut\"){\n/*\t\tif(manu == \"cisco\"){\n\t\t\tvar mtch = model.match(/asr/g);\n\t\t\tif(mtch ==\"\" || mtch != \"asr\"){\n\t\t\t\tst = '/device/cisco_vivid_blue_40.png';\n\t\t\t}else{\t\t\t\t\t\t\t\n\t\t\t\tst= '/device/asr-1k-40px.png';\n\t\t\t}\n\t\t}else if(manu == \"ixia\"){\n\t\t\tst= '/testtool/ixia-40px.png';\n\t\t}*/\n\t}else if(type == \"testtool\"){\n\t\tif(manu == \"ixia\"){\n\t\t\tst= '/model_icons/ixia-40px.png';\n\t\t}\n\t}\n\treturn st;\n\t\t\n}",
"function tryToInjectCustomTextures(modelTest) {\n let model = modelTest.resource;\n let parser = modelTest.parser;\n\n for (let textureTest of eachTextureTest()) {\n for (let i = 0, l = model.textures.length; i < l; i++) {\n const texture = model.textures[i];\n\n texture.whenLoaded().then(() => {\n if (!texture.ok && areSameFiles(parser.textures[i].path, textureTest.name)) {\n model.textures[i] = textureTest.resource;\n\n console.log(`NOTE: loaded ${textureTest.name} as a custom texture for model: ${modelTest.name}`);\n }\n });\n }\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Submits SQL query from Form to Redshift Data API: | async function submitQuery() {
var credentials = await Auth.currentCredentials();
const redshiftDataClient = new RedshiftData({
region: state.clusterRegion,
credentials: Auth.essentialCredentials(credentials)
});
var params = {
ClusterIdentifier: state.clusterIdentifier,
Sql: state.sql,
Database: state.database,
//DbUser: state.dbUser,
SecretArn: state.secretArn,
StatementName: state.statementName,
WithEvent: state.withEvent,
};
console.log('Submitting query to Redshift...');
var response = await redshiftDataClient.executeStatement(params).promise();
console.log(`Submission accepted. Statement ID:`, response);
setTimeout(updateStatementHistory, 2000); // Seems we need to wait a second or two before calling the ListStatements() API, otherwise results don't show latest query:
} | [
"runSoqlQuery()\n {\n this.setSelectedMapping();\n this.setSelectedAction();\n this.callRetrieveRecordsUsingWrapperApex();\n }",
"function submitQuery() {\n \"use strict\";\n const results = document.getElementById(\"queryResults\");\n const query = getBaseURL() + \"data/?\" + getQueryParamString();\n\n fetch(query).then(function (response) {\n const contentType = response.headers.get(\"content-type\");\n if (contentType && contentType.indexOf(\"application/json\") !== -1) {\n return response.json();\n } else {\n return response.text();\n }\n }).then(function (data) {\n if (typeof data === \"string\") {\n results.textContent = data;\n } else {\n results.textContent = JSON.stringify(data, null, 4);\n }\n });\n}",
"function submitCustomQuery(text){\r\n\t\tvar endpoint=\"http://data.uni-muenster.de:8080/openrdf-sesame/repositories/bt\";\r\n\t\t//sent request over jsonp proxy (some endpoints are not cors enabled http://en.wikipedia.org/wiki/Same_origin_policy)\r\n\t\tvar queryUrl = \"http://jsonp.lodum.de/?endpoint=\" + endpoint;\r\n\t\tvar request = { accept : 'application/sparql-results+json' };\r\n\t\t//get sparql query from textarea\r\n\t\trequest.query=text;\r\n\t\tconsole.log('Start Ajax');\r\n\t\t//sent request\r\n\t\t$.ajax({\r\n\t\t\tdataType: \"jsonp\",\r\n\t\t\t//some sparql endpoints do only support \"sparql-results+json\" instead of simply \"json\"\r\n\t\t\tbeforeSend: function(xhrObj){xhrObj.setRequestHeader(\"Accept\",\"application/sparql-results+json\");},\r\n\t\t\tdata: request,\r\n\t\t\turl: queryUrl,\r\n\t\t\tsuccess: callbackFuncResults,\r\n\t\t\terror: function (request, status, error) {\r\n\t\t //alert(request.responseText);\r\n\t\t\t\t\t$('#loadingDiv').hide();\r\n\t\t\t\t\t$('#result_error').slideDown().delay(3000).slideUp();\r\n\t\t\t\t\t$(\"#error\").html(request.responseText);\r\n\t\t }\r\n\t\t});\r\n\t}",
"function query(input) {\n const _defaults = {\n params: []\n };\n const {sql, params, autorollback} = Object.assign(_defaults, input);\n \n return new Promise((resolve, reject) => {\n connection.query(sql, params, (err, resp) => {\n if(err && autorollback) {\n return resolve(rollback(err));\n }\n else if (err) {\n return reject(err);\n }\n resolve(resp);\n });\n });\n}",
"function insertRecordsIntoDE(rowData,accesstoken){\n var MCHeaders = {\n 'Content-Type': 'application/json',\n 'Authorization' : 'Bearer ' + accesstoken\n };\n //console.log('Row data From Inarguments'+JSON.stringify(rowData));\n performPostRequest(MCEndpoint,MCHost,MCHeaders, method, rowData, function(data) {\n //console.log(data);\n });\n}",
"async query(context, q) {\n return new Promise((resolve) => {\n axios({\n method: \"post\",\n url: `${process.env.VUE_APP_MAIN_URL}/${process.env.VUE_APP_GRAPHQL_URL}`,\n data: { query: `query { ${q} }` }\n }).then((res) => {\n resolve(res.data.data)\n }).catch((err) => {\n console.error(err.response)\n })\n })\n }",
"function executeQuery(query, closure) {\n sqlConnection.execute(query, (err, result) => {\n if (err) {\n logMessage(err);\n } else {\n logMessage(result);\n if (closure != null) { closure(); }\n };\n });\n }",
"reserve(attraction, account_id, num_people, res_time, res_date) {\n //console.log(\"RESERVINg\");\n let sql = \"INSERT INTO reservations(attractionRideName, numPeople, time, date, user) VALUES ($attraction, $num_people, $time, $date, $user)\";\n this.db.run(sql, {\n $attraction: attraction,\n $num_people: num_people,\n $time: res_time,\n $date: res_date,\n $user: account_id,\n }, (err) => {\n if(err) {\n throw(err);\n }\n });\n }",
"function ejecutarSQL(sql, OK, notOK){\n // conecta con la base de datos\n const client = new Client(connectionData)\n client.connect()\n // Envia la consulta\n client.query(sql)\n .then(response => { // si la consulta sale bien\n client.end()\t// Finaliza la conexcion\n OK(response.rows)\n })\n .catch(err => {\t// si algo sale mal\n client.end()\t// Finaliza la conexcion\n notOK(err)\n })\n}",
"function submitTagCloudQuery() {\r\n\t\r\n\t//TODO: Does not work because there are no stis:Publication anymore\r\n\t\r\n\tvar endpoint = \"http://data.uni-muenster.de:8080/openrdf-sesame/repositories/bt\";\r\n\t//sent request over jsonp proxy (some endpoints are not cors enabled http://en.wikipedia.org/wiki/Same_origin_policy)\r\n\tvar queryUrl = \"http://jsonp.lodum.de/?endpoint=\" + endpoint;\r\n\tvar request = {\r\n\t\taccept : 'application/sparql-results+json'\r\n\t};\r\n\t//get sparql query from textarea\r\n\trequest.query = \"prefix stis: <http://localhost/default#> prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> prefix gnd: <http://d-nb.info/standards/elementset/gnd#> select distinct ?personUri ?name ?count where{ ?personUri gnd:preferredNameForThePerson ?name{ select ?personUri (count(?personUri) as ?count) where{{ ?a a stis:Publication; <http://purl.org/dc/elements/1.1/creator> ?personUri. }} GROUP BY ?personUri ORDER BY DESC(?count) limit 10} } ORDER BY DESC(?count) limit 10\";\r\n\tconsole.log('Start Ajax');\r\n\t//sent request\r\n\t$.ajax({\r\n\t\tdataType : \"jsonp\",\r\n\t\t//some sparql endpoints do only support \"sparql-results+json\" instead of simply \"json\"\r\n\t\tbeforeSend : function(xhrObj) {\r\n\t\t\txhrObj.setRequestHeader(\"Accept\", \"application/sparql-results+json\");\r\n\t\t},\r\n\t\tdata : request,\r\n\t\turl : queryUrl,\r\n\t\tsuccess : callbackTag,\r\n\t\terror : function(request, status, error) {\r\n\t\t\t//alert(request.responseText);\r\n\t\t\t$(\"#error\").html(request.responseText);\r\n\t\t}\r\n\t});\r\n}",
"async function buildJql() {\n var project, status, inStatusFor;\n project = document.getElementById(\"project\").value;\n status = document.getElementById(\"statusSelect\").value;\n inStatusFor = document.getElementById(\"daysPast\").value\n return STATUS_URL.replace(/\\{project\\}/, project).replace(/\\{status\\}/g, status).replace(/\\{inStatusFor\\}/, inStatusFor)\n}",
"function convertObjectToSQLFunctionInputString(obj){\n var input_string = \"\";\n for (var key in obj) {\n if (key != \"submit\" && obj.hasOwnProperty(key)) {\n if (input_string != \"\") input_string += \",\";\n if (typeof obj[key] === \"string\"){\n input_string += \"'\" + obj[key] + \"'\";\n } else {\n input_string += obj[key];\n }\n }\n }\n return input_string;\n}",
"function saveSubmission (req) {\n //open DB connection\n const pool = db.connection.INSTANCE();\n \n var name = [req.body.email];\n var sql = \"INSERT INTO tokenswap(email) VALUES($1)\";\n //Save to DB and close connection\n pool.query(sql, name, (err, res) => {\n console.log(err, res);\n });\n return;\n}",
"async function addSchedule(ctx) {\n const { usernamect, availdate} = ctx.params;\n try {\n const sqlQuery = `INSERT INTO parttime_schedules VALUES ('${usernamect}', '${availdate}')`;\n await pool.query(sqlQuery);\n ctx.body = {\n 'username_caretaker': usernamect,\n 'availdate': availdate\n };\n } catch (e) {\n console.log(e);\n ctx.status = 403;\n }\n}",
"function call_create_query() {\n\t// list every node with class saveQuery:\n\tvar values = '';\n\tvar nodes = dojo.query(\".saveQuery\");\n\n\tfor( var x = 0; x < nodes.length; x++ ) {\n\t\tvar k, v;\n\n\t\tk = nodes[x].id;\n\t\tv = nodes[x].value;\n\t\tif( k == 'name' ) {\n\t\t\tv = encodeURIComponent(v); // make sure the name is encoded.\n\t\t}\n\t\tif( v[0] != '#' ) {\n\t\t\t// console.log(k, v);\n\t\t\tvalues += \"&{0}={1}\".format(k, v);\n\t\t}\n\t}\n\n\tvar xmlhttp = new XMLHttpRequest();\n\tvar url = '{0}?method=create{1}&random={3}'.format(getQuerypage(), values, randomString(5));\n\t// console.log(url);\n\txmlhttp.open('GET', url, false);\n\txmlhttp.send();\n\tif( xmlhttp.status == 200 ) {\n\t\talert('Saved');\n\t} else {\n\t\talert('Error creating:' + xmlhttp.responseText);\n\t}\n}",
"function sendData(postData){\n var clientServerOptions = {\n body: JSON.stringify(postData),\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n }\n }\n // on response from server, log response\n let response = request('POST', 'http://localhost:8983/solr/gettingstarted/update/json/docs?commit=true&overwrite=true', clientServerOptions);\n if (response.statusCode !== 200) {\n throw(response.body)\n } else {\n console.log('sent')\n }\n}",
"function add_records(){\n fetch('/add', {\n headers: { 'Content-Type': 'application/json'},\n method: 'POST',\n body: JSON.stringify(transactions)\n })\n}",
"function populateFormFromUrl() {\n const createSearchItems = Private(SearchItemsProvider);\n const {\n indexPattern,\n savedSearch,\n combinedQuery } = createSearchItems();\n\n if (indexPattern.id !== undefined) {\n timeBasedIndexCheck(indexPattern, true);\n $scope.ui.datafeed.indicesText = indexPattern.title;\n $scope.job.data_description.time_field = indexPattern.timeFieldName;\n\n if (savedSearch.id !== undefined) {\n $scope.ui.datafeed.queryText = JSON.stringify(combinedQuery);\n }\n }\n }",
"handle_index_table_form(){\n let $form = $(\"#custom-table-parameters\"),\n $form_submit_button = $form.find(\".button-primary\");\n\n $form.on(\"submit\",(e) => {\n e.preventDefault();\n //Disable button\n $form_submit_button.attr(\"disabled\",true);\n //Collect data\n let table_params = {},\n $dataTypes_input = $(\"[data-datatype]\").filter(\":checked\");\n if($dataTypes_input.length > 0){\n $.each($dataTypes_input, function (index,input) {\n let $input = $(input);\n if(typeof table_params[\"\"+$input.data(\"datatype\")+\"\"] === \"undefined\"){\n table_params[\"\"+$input.data(\"datatype\")+\"\"] = [];\n }\n table_params[$input.data(\"datatype\")].push($input.val());\n });\n/* for(let input of $dataTypes_input){\n let $input = $(input);\n if(typeof table_params[\"\"+$input.data(\"datatype\")+\"\"] === \"undefined\"){\n table_params[\"\"+$input.data(\"datatype\")+\"\"] = [];\n }\n table_params[$input.data(\"datatype\")].push($input.val());\n }*/\n }\n //Send ajax requests\n this.handle_index_table_creation(table_params);\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
============================================ multiword property must have quotes and we cant access the value with "dot" user."Birth Year" < wont work! user["Birth Year"] < use this insted | function function5()
{
var user = {
fname: "John",
lname: "Doe",
"Birth Year": 1997, // <-- multiword property
"Has Driver License": true, // <-- multiword property
plate: 'abc1234ds'
};
console.log(user.fname);
console.log(user.lname);
// because its a multiword property can't use "dot"
console.log(user["Birth Year"]);
console.log(user["Has Driver License"]);
console.log(user.plate);
console.log("---");
console.log(user["fname"]); // same as user.fname
console.log(user["lname"]); // same as user.lname
console.log("---");
console.log("Changing name and Birth Year");
user.fname = "Merry";
user["Birth Year"] = 2002;
console.log(user);
console.log("---");
} | [
"function agePerObj(ageObj){\n ageObj[\"age\"] = ageObj.firstName.length + ageObj.lastName.length;\n}",
"static filterApptUserData(user) {\n return {\n name: user.name,\n email: user.email,\n phone: user.phone,\n uid: user.uid,\n id: user.id,\n photo: user.photo,\n type: user.type,\n };\n }",
"get secondName() {\n return this.userInfo[\"secondName\"];\n }",
"get fieldValue(){}",
"function addFullNameProperty(obj) {\n var firstName = obj['firstName'];\n var lastName = obj['lastName'];\n\n if (firstName && lastName) {\n obj['fullName'] = firstName + ' ' + lastName;\n }\n\n return obj;\n}",
"function updateUser(){\n user.age ++\n user.name.charAt(0).toUpperCase()\n}",
"function getObjectCodenameProperty (data, property) {\n\tlet value = null;\n\n\tif (data.hasOwnProperty(property)) {\n\t\tvalue = { codename: data[property].toString() };\n\t}\n\n\treturn value; \n}",
"function describePerson (person){\r\n //return person.firstName +\" \"+ person.surname + \"is the \" + person.jobTitle;\r\n return `${person.firstName} ${person.surname} is the ${person.jobTitle}`\r\n}",
"_appendToken(dbUserData){\n let userInfo = {\n ...dbUserData._doc,\n token: dbUserData.generateJWToken()\n };\n delete userInfo[\"password\"];\n return userInfo;\n }",
"static filterRequestUserData(user) {\n return { // Needed info to properly render various user headers\n name: user.name,\n email: user.email,\n uid: user.uid,\n id: user.id,\n photo: user.photo,\n type: user.type,\n grade: user.grade,\n gender: user.gender, // We need this to render gender pronouns correctly\n hourlyCharge: (!!user.payments) ? user.payments.hourlyCharge : 0,\n location: user.location || window.app.location.name,\n payments: user.payments,\n proxy: user.proxy,\n };\n }",
"formatUser() {\n\t\tconst user = this.currentUser();\n\t\treturn `\nName (Client Email): ${user.name}\nKey (Client ID): ${user.key}\nAPI Key ID: ${user.api_key_id}\nAPI Secret: ${user.api_secret}\nPublic Key: ${user.public_key}\nPrivate Key: ${user.private_key}\nPublic Signing Key: ${user.public_signing_key}\nPrivate Signing Key: ${user.private_signing_key}\n`;\n\t}",
"function field(obj, pathString) {\n if (!obj || typeof pathString !== 'string') return '';\n function fn(obj, path) {\n var prop = path.shift();\n if (!(prop in obj) || obj[prop] == null) return '';\n if (path.length) {\n return fn(obj[prop], path);\n }\n return String(obj[prop]);\n }\n return fn(obj, pathString.split('.'));\n}",
"function formatName(person){\n\treturn person.fullName;\n}",
"get propertyName() {}",
"function populateDocumentWithObject (document, key, value) {\n const keys = Object.keys(value);\n const unprefixedKeys = keys.filter(k => k[0] !== '$');\n\n if (unprefixedKeys.length > 0 || !keys.length) {\n // Literal (possibly empty) object ( or empty object ) \n // Don't allow mixing '$'-prefixed with non-'$'-prefixed fields\n if (keys.length !== unprefixedKeys.length) {\n throw new Error(`unknown operator: ${unprefixedKeys[0]}`);\n }\n validateObject(value, key);\n insertIntoDocument(document, key, value);\n } else {\n Object.keys(value).forEach(function (k) {\n const v = value[k];\n if (k === '$eq') {\n populateDocumentWithKeyValue(document, key, v);\n } else if (k === '$all') {\n // every value for $all should be dealt with as separate $eq-s\n v.forEach(vx => populateDocumentWithKeyValue(document, key, vx));\n }\n });\n }\n}",
"toJSON() {\n return {\n firstName: this.firstName,\n lastName: this.lastName,\n age: this.#age\n }\n }",
"_yearsQuery() {\n const operation = operationKeys.GET_YEARS;\n\n return queryString.stringify({\n op: operation,\n data: JSON.stringify({\n catalogSource: 'Endeca',\n site: this.getDomain(operation),\n pipeDelimited: 1,\n }),\n }, { encode: false });\n }",
"function getTitleInfo(){\r\n var titleStr='';\r\n for (var i=0; i<obj['subfield'].length; i++){\r\n if (obj['subfield'][i][parserPrefix]['code']=='a') {\r\n titleStr = obj['subfield'][i]['_'];\r\n var exp = new RegExp(/ :$/); // if there is a colon, move to a logical place: no space\r\n titleStr = titleStr.replace(exp,': ');\r\n }\r\n else if (obj['subfield'][i][parserPrefix]['code']=='b') {\r\n titleStr += obj['subfield'][i]['_'];\r\n }\r\n }\r\n \r\n exp = new RegExp(/ \\/$/); // strip trailing ' /' from title\r\n titleStr = titleStr.replace(exp,'');\r\n book['title']=titleStr;\r\n if (debug) console.log(util.inspect(book, showHidden=true, depth=6, colorize=true));\r\n}",
"function lookUpProfile(firstName, prop){\n// Only change code below this line\n var countFN=0;\n var countProp=0;\n //test = contacts[2].firstName\n //return test;\n \n for(var i=0; i<contacts.length; i++){\n if((contacts[i].firstName === firstName) && (contacts[i].hasOwnProperty(prop)))\n {\n return contacts[i][prop];\n }\n }\n \n for(var j=0; j<contacts.length; j++){\n if(contacts[j].firstName !== firstName){\n countFN++;\n if(countFN===contacts.length){\n return \"No such contact\";\n }\n }\n }\n \n for(var k=0; k<contacts.length; k++){\n if(contacts[k].hasOwnProperty(prop)===false){\n countProp++;\n if(countProp===contacts.length){\n return \"No such property\";\n }\n }\n }\n \n// Only change code above this line\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sends messages to children about selected locale | postLocaleToChildren() {
const country = localStorage.getItem('country');
const dateTimeFormat = localStorage.getItem('dateTimeFormat');
const decimalSeparator = localStorage.getItem('decimalSeparator');
this.postMessageToChild(MessageType.locale, {
country,
dateTimeFormat,
decimalSeparator
});
} | [
"notifyChildAboutLocale(locale) {\n this.postMessageToChild(MessageType.locale, locale);\n }",
"postLanguageToChildren() {\n this.postMessageToChild(MessageType.language, this.translationManagementService.language);\n }",
"function onLocaleChange(e)\r\n{\r\n\tvar flashObj = getFlashObject();\r\n\t\r\n\t/* Change the active locale of the flash object. */\r\n\tif (flashObj && flashObj['changeLocale'])\r\n\t{\r\n\t\tflashObj.changeLocale(e.locale);\r\n\t}\r\n\t\r\n\t/* Remove the active-class from the all tabs, add it to the current language. */\r\n\t$(\"#locale a.active\").removeClass('active');\r\n\t$(\"#locale a.\" + e.locale).addClass('active');\r\n\t\r\n\t/* Change alert message if no flash. */\r\n\tif ($(\"#noflash-message div\"))\r\n\t{\r\n\t\t$(\"#noflash-message div\").addClass('hidden');\r\n\t\t$(\"#noflash-message div.\" + e.locale).removeClass('hidden');\r\n\t}\r\n\t\r\n\t/* Update the URL with the selected language. */\r\n\tif (window.history && window.history.pushState)\r\n\t{\r\n\t\twindow.history.pushState(\r\n\t\t{\r\n\t\t\tlocale: e.locale\r\n\t\t}, document.title, \"?locale=\" + e.locale);\r\n\t}\r\n\t\r\n /* Sets a cookie to remember the language use. */\r\n $.cookie(\"locale\", e.locale);\r\n}",
"function onLocaleLinkClick(e)\r\n{\r\n\te.preventDefault();\r\n\t$(document).trigger(\r\n\t{\r\n\t\ttype: \"changeLocaleEvent\",\r\n\t\tlocale: $(this).attr(\"title\").toLowerCase()\r\n\t});\r\n}",
"postThemeToChildren() {\n const theme = this.themeService.getCurrentTheme();\n this.postMessageToChild(MessageType.theme, theme);\n }",
"_updateLinkingToMasterLocale(locale) {\n // Rebuild the display for the changed locale and for the master display\n // because it could have been affected, too.\n const displaySize = SvgLayout._calcDisplaySize(this._containerHtmlElems);\n this._buildDisplay(locale, displaySize);\n this._buildDisplay(cred.locale.any, displaySize);\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 writeMessagesForChildGroups(parentId) {\n jQuery(\"[data-parent='\" + parentId + \"']\").each(function () {\n\n var currentGroup = jQuery(this);\n var id = currentGroup.attr(\"id\");\n var data = getValidationData(currentGroup, true);\n\n if (data) {\n var messageMap = data.messageMap;\n if (!messageMap) {\n messageMap = {};\n data.messageMap = messageMap;\n }\n }\n\n if (!(currentGroup.is(\"div[data-role='InputField']\"))) {\n writeMessagesForChildGroups(id);\n writeMessagesForGroup(id, data);\n displayHeaderMessageCount(id, data);\n }\n });\n}",
"function sendMessageToAll(message) {\n chrome.tabs.query({\n url: '*://' + config.domainTo + '/*'\n }, function(tabs) {\n if (tabs && tabs.length) {\n tabs.forEach(function(tab) {\n chrome.tabs.sendMessage(tab.id, message);\n });\n }\n });\n}",
"renderWelcomeMessage(language) {\n switch(language) {\n case 'en':\n this.setState({welcomeMessage: 'Welcome message from STORMRIDER'});\n break;\n case 'is':\n this.setState({welcomeMessage: 'Bulbulbul asfgwthyt sadasd STORMRIDER'});\n break;\n default:\n break;\n }\n }",
"function composeMessageToTenant(tenant) {\n router.navigate('#messages/' + tenant.Id());\n }",
"#initLocaleInputs() {\n this.localeInputs.forEach((localeInput) => {\n localeInput.addEventListener('change', (event) => {\n const locale = localeInput.value;\n\n this.#setLocale(locale);\n });\n });\n }",
"updateMessages(selection=undefined, attributes=[], fallback=undefined) {\n var locale = this;\n if (typeof selection === \"undefined\") {\n selection = d3.selection().attr(\"lang\", this.lang);\n }\n selection.selectAll(\"[data-message]\").each(function() {\n if (!selection.node().contains(this)) {\n return;\n }\n const msg = this.getAttribute(\"data-message\");\n const children = Array.from(this.children).map((c) => c.outerHTML);\n const replacement = locale.message(msg, children, fallback);\n if (replacement !== null) {\n locale.updateMessages(d3.select(this).html(replacement), attributes);\n }\n });\n attributes.forEach((attribute) => {\n selection.selectAll(`[data-message-${attribute}]`).each(function() {\n const msg = this.getAttribute(`data-message-${attribute}`);\n const replacement = locale.message(msg, null, fallback);\n if (replacement !== null) {\n d3.select(this).attr(attribute, replacement);\n }\n });\n });\n }",
"callChildMethod(){\n this.template.querySelector('c-bubble-event').childMethodCallingFromParent('Parent message passed');\n }",
"function getSelectedLocale() {\n return _selectedLocale;\n }",
"getChildContext() {\n return { translator };\n }",
"_onChatSelected({detail}) {\n // find all messages of selected chat\n const chatMessaged = this._messages.filter(m => m.sender === detail.id || m.toChat === detail.id);\n\n // set selected chat as activeChat of whole app\n this.activeChat = this._chats.find(c => c.id === detail.id);\n\n // if the chatBox if open for activeChat, scroll content to end\n if (this._componenets.chatBox.activeChat && this._componenets.chatBox.activeChat.id === this.activeChat.id) {\n this._componenets.chatBox.scrollToEnd();\n return;\n }\n\n // mark all messages as read and remove unread badge for selected chat\n this.activeChat.elm.markAllAsRead();\n // change the current chat of chatBox component\n this._componenets.chatBox.setActiveChat(this.activeChat);\n\n // send all messages of target chat to render in chatBox\n chatMessaged.map(msg => {\n this._componenets.chatBox.renderMessage(msg)\n })\n }",
"ShowCurrentItems(){\n MyUtility.getInstance().sendTo('telegram.0', {\n chatId : MyUtility.getInstance().getState('telegram.0.communicate.requestChatId'/*Chat ID of last received request*/).val,\n text: 'Bitte Raum wählen:',\n reply_markup: {\n keyboard:\n this._telegramArray.getTelegramArray(this._currentIDX)\n ,\n resize_keyboard: true,\n one_time_keyboard: true\n }\n });\n\n this.emit(\"onItemChange\",this);\n }",
"function getLocale () {\n return locale\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Spread size of grid... I know used once... ...but idea was to let it modify by user. Zoom in/out does the job. | function setSpreadSize(size) {
spreadSize = size;
grid = new THREE.GridHelper(spreadSize, spreadSize);
grid.position.x = spreadSize / 2;
grid.position.z = spreadSize / 2;
grid.name = "GRID";
scene.remove("GRID");
scene.add(grid);
localGrid = new THREE.GridHelper(spreadSize / 5, spreadSize);
localGrid.position.x = spreadSize / 2;
localGrid.position.z = spreadSize / 2;
localGrid.name = "LOCALGRID";
scene.remove("LOCALGRID");
scene.add(localGrid);
axes = new THREE.AxesHelper(spreadSize);
axes.position.set(0, 0.05, 0);
axes.name = "AXES";
scene.remove("AXES");
scene.add(axes);
} | [
"function changeGridSize() {\n value = sizeSlider.value;\n container.innerHTML = \"\";\n makeRows(value, value);\n displayGridSlider.innerHTML = value.toString() + \"x\" + value.toString();\n}",
"function newGrid (newSize) {\n $('.row').remove();\n createGrid(newSize);\n // $('.column').outerHeight(oldSize*oldPixel/newSize);\n // $('.column').outerWidth(oldSize*oldPixel/newSize);\n}",
"function changeGridSize(){\r\n let cellsToDelete = Array.prototype.slice.apply(document.querySelectorAll('.cell'))\r\n cellsToDelete.forEach((cell) => {gridContainer.removeChild(cell)})\r\n\r\n let gridValue = gridSize.value\r\n console.log(gridValue,\"GV\")\r\n createGrid(gridValue)\r\n}",
"gridCellSize() {\n return (gridCellSizePercent * canvasWidth) / 100;\n }",
"function setSizes() {\n if (!currentMap) return;\n\n const viewMaxWidth = canvasElement.width - dpi(40);\n const viewMaxHeight = canvasElement.height - dpi(40);\n const tileWidth = Math.floor(viewMaxWidth / currentMap.cols);\n const tileHeight = Math.floor(viewMaxHeight / currentMap.rows);\n\n tileSize = Math.min(tileWidth, tileHeight);\n viewWidth = tileSize * currentMap.cols;\n viewHeight = tileSize * currentMap.rows;\n viewX = (canvasElement.width - viewWidth) / 2;\n viewY = (canvasElement.height - viewHeight) / 2;\n}",
"function makeGrid() {\n\tlet cellSize = 0;\n\tif ($(window).width() < $(window).height()) {\n\t\tcellSize = $(window).width()*0.8*(1/(level + 0.5));\n\t} else {\n\t\tcellSize = $(window).height()*0.8*(1/(level + 0.5));\n\t}\n\tmakeRows(cellSize);\n\tfillRows(cellSize);\n}",
"function drawOnGrid(shapeFn, originalSizeAsScreenFraction, paddingAsShapeFraction) {\n\tconst smallestDim = min(width, height);\n\tconst largestDim = max(width, height);\n\n\tconst calcPaddedSize = (screenFraction) => screenFraction * (1 + paddingAsShapeFraction) * smallestDim;\n\tconst originalSizeWithPadding = calcPaddedSize(originalSizeAsScreenFraction)\n\tconst numThatFitFully = floor(smallestDim / originalSizeWithPadding);\n\tconst actualSizeWithPadding = smallestDim / numThatFitFully;\n\n\t//long axis: distribute any space on the long axis for an exact fit\n\tconst spareSpace = largestDim - numThatFitFully * actualSizeWithPadding;\n\tconst extraPadding = spareSpace / numThatFitFully;\n\n\tconst yStep = actualSizeWithPadding + (height <= width ? 0 : extraPadding);\n\tconst xStep = actualSizeWithPadding + (height >= width ? 0 : extraPadding);\n\n\tif (xStep < 30 || yStep < 30) {\n\t\tconsole.error(\"too small xStep or yStep\", {\n\t\t\txStep,\n\t\t\tyStep\n\t\t});\n\t\treturn;\n\t}\n\tconst correctiveScaling = actualSizeWithPadding / originalSizeWithPadding;\n\n\tfor (let y = yStep / 2; y <= height; y += yStep) {\n\t\tfor (let x = xStep / 2; x <= width; x += xStep) {\n\t\t\tpush();\n\t\t\ttranslate(x, y);\n\t\t\tif (dbg.isDebugging) {\n\t\t\t\trectMode(CENTER);\n\t\t\t\tsquare(0, 0, actualSizeWithPadding)\n\t\t\t}\n\t\t\tscale(correctiveScaling);\n\t\t\tshapeFn();\n\t\t\tpop();\n\t\t}\n\t}\n\n\tif (dbg.isDebugging) {\n\n\t\tdbg.debugObjRoundingValues({\n\t\t\txStep,\n\t\t\tyStep,\n\t\t\twidth,\n\t\t\theight,\n\t\t\tnumThatFitFully\n\t\t}, 100, height - 70, true);\n\t\tdbg.debugObjRoundingValues({\n\t\t\toriginalSizeAsScreenFraction,\n\t\t\t//originalSize,\n\t\t\toriginalSizeWithPadding,\n\t\t\tpaddingAsShapeFraction,\n\t\t}, 100, height - 40, true);\n\t}\n\n}",
"function updateCanvasScale() {\n cellSize = (window.innerWidth / 100) * gridCellSizePercent;\n cellsPerWidth = parseInt(window.innerWidth / cellSize);\n cellsPerHeight = parseInt((cellsPerWidth * 9) / 21);\n\n canvasWidth = window.innerWidth;\n canvasHeight = cellSize * cellsPerHeight;\n resizeCanvas(canvasWidth, canvasHeight);\n\n if (smallScreen != canvasWidth < minCanvasWidth) {\n smallScreen = canvasWidth < minCanvasWidth;\n if (!smallScreen) {\n ui.showUIByState();\n }\n }\n\n ui.hiscores.resize(false);\n}",
"function setDefaultGrid() {\n setGridSize(16);\n fillGrid(16);\n}",
"function gridify() {\n let numDivision = ceil(Math.sqrt(obj.numOfMols));\n let spacing = (width - obj.maxMolSize) / numDivision;\n\n molecules.forEach((molecule, index) => {\n\n let colPos = (index % numDivision) * spacing;\n let rowPos = floor(index / numDivision) * spacing;\n //console.log(`The col pos ${colPos} and the row pos ${rowPos}`);\n molecule.position.x = colPos + obj.maxMolSize;\n molecule.position.y = rowPos + obj.maxMolSize;\n\n });\n}",
"calculateLayoutSizes() {\n const gridItemsRenderData = this.grid.getItemsRenderData();\n this.layoutSizes =\n Object.keys(gridItemsRenderData)\n .reduce((acc, cur) => (Object.assign(Object.assign({}, acc), { [cur]: [gridItemsRenderData[cur].width, gridItemsRenderData[cur].height] })), {});\n }",
"rescaleTiles() {}",
"function reduceMiniSize() {\n var plotContainers = document.getElementsByClassName(\"svg-container\");\n\n var dim = getContainerDim(1, plotContainers);\n\n if (!miniReduced) {\n for (var i = 1; i < plotContainers.length; i++) {\n plotContainers[i].style.cssText = \"position: relative; width: \" + dim[0] * config.reductionFactor + \"px; height: \" + dim[1] + \"px;\";\n }\n }\n miniReduced = true;\n}",
"function resize() {\n\n var mapratio= parseInt(d3.select(tag_id).style('width'));\n\n if (width > 8*height) {\n mapratio = width /5;\n } else if (width > 6*height) {\n mapratio = width /4;\n } else if(width>4*height){\n mapratio = width /3;\n } else if(width> 2*height){\n mapratio = width/2;\n } else if(width >= height){\n mapratio = width;\n }\n\n projection.scale([mapratio]).translate([width/2,height/2]);\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 gScale(sx,sy,sz) {\r\n modelViewMatrix = mult(modelViewMatrix,scale(sx,sy,sz)) ;\r\n}",
"function setValueGrid(startRow, startCol, w, h, val) {\n for (var i = startRow; i < startRow + h; i++) {\n for (var j = startCol; j < startCol + w; j++) {\n grid[i][j] = val;\n }\n }\n}",
"function create8X8 () {\n for (i=0;i<64;i++){\n var newSquare = \"<li id=\"+parseInt(i)+\"></li>\";\n $(\".grid\").append(newSquare);\n }\n $tileArray = $(\"li\");\n row_length = Math.sqrt($tileArray.length); \n $tileArray.css(\"height\", \"10%\").css(\"width\", \"10%\");\n }",
"function sizeTable() {\n\t\tvar emulator = $('.emulator'),\n\t\t\t\ttable = emulator.find('.grid'),\n\t\t\t\tdimensions = disco.controller.getDimensions(),\n\t\t\t\txMax = dimensions.x,\n\t\t\t\tyMax = dimensions.y,\n\t\t\t\tstyles = [],\n\t\t\t\theight, width, cellWidth, cellHeight;\n\n\t\ttable.css({\n\t\t\t'height': '100%',\n\t\t\t'width': '100%',\n\t\t});\n\n\t\tif (xMax < yMax) {\n\t\t\ttable.css('width', table.outerHeight()/yMax);\n\t\t}\n\t\telse if (xMax > yMax) {\n\t\t\ttable.css('height', table.outerWidth()/xMax);\n\t\t}\n\n\t\t// height = emulator.height();\n\t\t// width = emulator.width();\n\n\t\t// // Determine the cell height to keep each cell square\n\t\t// cellWidth = width / dimensions.x;\n\t\t// cellHeight = height / dimensions.y;\n\t\t// if (cellWidth < cellHeight) {\n\t\t// \tcellHeight = cellWidth;\n\t\t// } else {\n\t\t// \tcellWidth = cellHeight;\n\t\t// }\n\n\t\t// // Set styles\n\t\t// $('#grid-dimensions').html('table.grid td { width: '+ cellWidth +'px; height: '+ cellHeight +'px }');\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
`ontouchstart` check works on most browsers `maxTouchPoints` works on IE10/11 and Surface | function isTouchDevice() {
return 'ontouchstart' in window || navigator.maxTouchPoints;
} | [
"get isTouch()\n {\n return \"ontouchstart\" in window;\n }",
"function isReallyTouch(e){//if is not IE || IE is detecting `touch` or `pen`\nreturn typeof e.pointerType==='undefined'||e.pointerType!='mouse';}",
"function deviceHasTouchScreen() {\n let hasTouchScreen = false;\n if (\"maxTouchPoints\" in navigator) {\n hasTouchScreen = navigator.maxTouchPoints > 0;\n } else if (\"msMaxTouchPoints\" in navigator) {\n hasTouchScreen = navigator.msMaxTouchPoints > 0;\n } else {\n var mQ = window.matchMedia && matchMedia(\"(pointer:coarse)\");\n if (mQ && mQ.media === \"(pointer:coarse)\") {\n hasTouchScreen = !!mQ.matches;\n } else if ('orientation' in window) {\n hasTouchScreen = true; // deprecated, but good fallback\n } else {\n // Only as a last resort, fall back to user agent sniffing\n var UA = navigator.userAgent;\n hasTouchScreen = (\n /\\b(BlackBerry|webOS|iPhone|IEMobile)\\b/i.test(UA) ||\n /\\b(Android|Windows Phone|iPad|iPod)\\b/i.test(UA)\n );\n }\n }\n return hasTouchScreen;\n }",
"function useTouch() {\n return isNativeApp() || $.browser.mobile || navigator.userAgent.match(/iPad/i) != null;\n}",
"function didTouchMove(touch) {\n return Math.abs(touch.screenX - touchStartX) > 10 || Math.abs(touch.screenY - touchStartY) > 10;\n }",
"function touchMove(event) {\n if (this.touchStartLocation &&\n (Math.abs(this.touchStartLocation[0] - event.touches[0].clientX) > 25 ||\n Math.abs(this.touchStartLocation[1] - event.touches[0].clientY) > 25)) {\n this.cancelTap();\n }\n }",
"function isStillTap(){\n var max = arrayMax(piezoTrack); piezoTrack = [];\n return (max==undefined || max>config.piezoTreshold);\n}",
"function is_retina_device() {\n return window.devicePixelRatio > 1;\n}",
"function bigEnoughForInteractiveFigures() {\r\n if (!(window.matchMedia('(max-width: 600px)').matches)) {\r\n gtag('event', 'min-sheets-width', { 'event_category': 'user', 'event_label': 'true', 'value': 1 });\r\n return true;\r\n }\r\n gtag('event', 'min-sheets-width', { 'event_category': 'user', 'event_label': 'false', 'value': 0 });\r\n console.log('Screen too small for interactive visuals');\r\n return false;\r\n}",
"function setupTouchEventTranslation(foregroundNode) {\n // Identifier of the touch point we are tracking; set to null when touch not in progress.\n var touchId = null;\n var touchStartX;\n var touchStartY;\n\n function createMouseEvent(touch, type) {\n var mouseEvent = document.createEvent(\"MouseEvent\");\n mouseEvent.initMouseEvent(type, true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, false, false, false, false, 0, null);\n // This flag prevents FastClick from trying to pre-emptively cancel the event\n mouseEvent.forwardedTouchEvent = true;\n return mouseEvent;\n }\n\n // Detect whether the touch was moved >10 device pixels between start and end; if the touch\n // moved we may infer that the user performed a scroll.\n //\n // Contra @ppk (http://www.quirksmode.org/mobile/viewports2.html), screenX and screenY *are*\n // useful here because we're in an iframe. clientX/Y and pageX/Y are relative to our page and\n // visual viewport, respectively, *but those both move in rough synchrony with the touch* (and\n // we can't detect the scroll itself because the iframe's page and visual viewport offsets\n // don't change! The *outer* page changes but we may not be allowed to measure that.)\n // Fortunately, screenX and screenY are relative to the device, which lets us know if the\n // viewport moved \"physically\" (bonus: measurements in device pixels correspond to actual\n // physical distances in the user's world, and don't change with zoom).\n function didTouchMove(touch) {\n return Math.abs(touch.screenX - touchStartX) > 10 || Math.abs(touch.screenY - touchStartY) > 10;\n }\n\n // listener for touchstart\n function touchStarted(e) {\n var touch = e.changedTouches[0];\n\n if (e.touches.length > 1 || touch.target !== foregroundNode) {\n return;\n }\n\n cancelClickFlag = false;\n touchStartX = touch.screenX;\n touchStartY = touch.screenY;\n\n // Remember which touch point--later touch events may or may not include this touch point\n // but we have to listen to them all to make sure we update dragging state correctly.\n touchId = touch.identifier;\n foregroundNode.dispatchEvent(createMouseEvent(touch, 'mousedown'));\n\n if (defaultPreventedFlag) {\n e.preventDefault();\n }\n e.stopPropagation();\n }\n\n // Listener for touchmove, touchend, and touchcancel:\n function touchChanged(e) {\n\n if (touchId === null) {\n return;\n }\n\n // Don't translate touch events to mouse events when there are more than two fingers\n // on the screen. This lets us to support pinch-zoom even if user started gesture only\n // with one finger and added second later.\n if (e.type === \"touchmove\" && e.touches.length > 1) {\n // User added a second finger, perhaps he wants to do pinch-zoom or pan rather than\n // trigger \"click\" action at the end.\n cancelClickFlag = true;\n // In theory this isn't 100% correct, but... it ensures that no handler will be able\n // to call .preventDefault() on this event (e.q. D3 does that for touch events), so we\n // will always native browser behavior like panning or pinch-zoom. This is reasonable\n // assumption that 2-finger gestures are always used for navigation.\n e.stopPropagation();\n return;\n }\n\n var i;\n var len;\n var touch;\n var target;\n var mouseMoveEvent;\n\n for (i = 0, len = e.changedTouches.length; i < len; i++) {\n touch = e.changedTouches[i];\n\n if (touch.identifier !== touchId) {\n continue;\n }\n\n if (len === 1) {\n e.stopPropagation();\n }\n\n // touch's target will always be the element that received the touchstart. But since\n // we're creating a pretend mousemove, let its target be the target the browser would\n // report for an actual mousemove/mouseup (Remember that the--expensive--hitTest() is not\n // called for mousemove, though; drag handlers should and do listen for mousemove on the\n // window). Note that clientX can be off the document, so report window in that case!\n target = document.elementFromPoint(touch.clientX, touch.clientY) || window;\n\n if (e.type === 'touchmove') {\n if (!cancelClickFlag) {\n // Cancel \"click\" event when finger has moved (> 10px at the moment).\n cancelClickFlag = didTouchMove(touch);\n }\n mouseMoveEvent = createMouseEvent(touch, 'mousemove');\n target.dispatchEvent(mouseMoveEvent);\n // mousemove events can be captured and replaced by synthetic events (see .passMouseMove\n // method). In such case 'defaultPreventedFlag' will be automatically set to correct\n // value. However when event isn't captured and replaced by synthetic one, we have to\n // check .defaultPrevented property manually.\n if (!mouseMoveEvent.replacedBySynthetic) {\n defaultPreventedFlag = mouseMoveEvent.defaultPrevented;\n }\n } else if (e.type === 'touchend') {\n target.dispatchEvent(createMouseEvent(touch, 'mouseup'));\n touchId = null;\n } else if (e.type === 'touchcancel') {\n // Do not dispatch click event on touchcancel.\n cancelClickFlag = true;\n target.dispatchEvent(createMouseEvent(touch, 'mouseup'));\n touchId = null;\n }\n\n // .preventDefault() on touchend will prevent the browser from generating a events like\n // mousedown, mouseup and click. It's necessary as we already translated touchstart\n // to mousedown and touchend to mouseup. Our hit testing intentionally ignores\n // browser-generated click events anyway, and generates its own when appropriate.\n if (e.type === 'touchend' || defaultPreventedFlag) {\n e.preventDefault();\n }\n\n return;\n }\n }\n\n addWindowEventListener('touchstart', touchStarted, true);\n ['touchmove', 'touchend', 'touchcancel'].forEach(function(eventType) {\n addWindowEventListener(eventType, touchChanged, true);\n });\n\n // TODO implement cancel semantics for atom dragging?\n // see http://alxgbsn.co.uk/2011/12/23/different-ways-to-trigger-touchcancel-in-mobile-browsers/\n // until then we have to observe touchcancel to stop in-progress drags.\n }",
"_onTap(x,y){\n console.log('tap!', x, y)\n //save screen coordinates normalized to -1..1 (0,0 is at center and 1,1 is at top right)\n this._tapEventData = [\n x / window.innerWidth,\n y / window.innerHeight\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 }",
"startup() {\r\n var el = this.canvas[0];\r\n el.addEventListener(\"touchstart\", e => this.handleStart(e), false);\r\n el.addEventListener(\"touchend\", e => this.handleEnd(e), false);\r\n el.addEventListener(\"touchmove\", e => this.handleMove(e), false);\r\n }",
"function gestureStart(e)\n{\n if (!gesture.on) {\n gesture.on = true;\n gesture.x2 = gesture.x1 = e.touches[0].clientX;\n gesture.y2 = gesture.y1 = e.touches[0].clientY;\n gesture.opacity = document.body.style.opacity;\n }\n gesture.touches = e.touches.length;\n}",
"function supportsPassiveEventListeners() {\n if (supportsPassiveEvents == null && typeof window !== 'undefined') {\n try {\n window.addEventListener('test', null, Object.defineProperty({}, 'passive', {\n get: function get() {\n return supportsPassiveEvents = true;\n }\n }));\n } finally {\n supportsPassiveEvents = supportsPassiveEvents || false;\n }\n }\n\n return supportsPassiveEvents;\n }",
"function removeTouchHandler(){if(isTouchDevice||isTouch){// normalScrollElements requires it off #2691\nif(options.autoScrolling){$body.removeEventListener(events.touchmove,touchMoveHandler,{passive:false});$body.removeEventListener(events.touchmove,preventBouncing,{passive:false});}var touchWrapper=options.touchWrapper;touchWrapper.removeEventListener(events.touchstart,touchStartHandler);touchWrapper.removeEventListener(events.touchmove,touchMoveHandler,{passive:false});}}",
"static swipeDetect(element, end = (swipedir) => { }, threshold = 100, restraint = 100, allowedTime = 300) {\n if (typeof element == \"string\") {\n element = App.$(element);\n }\n const touchsurface = element;\n let swipedir,\n dist,\n startX,\n startY,\n distX,\n distY,\n elapsedTime,\n startTime;\n\n touchsurface.addEventListener('touchstart', function (e) {\n var touchobj = e.changedTouches[0];\n swipedir = 'none';\n dist = 0;\n startX = touchobj.pageX;\n startY = touchobj.pageY;\n startTime = new Date().getTime();\n }, false);\n touchsurface.addEventListener('touchend', function (e) {\n var touchobj = e.changedTouches[0];\n distX = touchobj.pageX - startX;\n distY = touchobj.pageY - startY;\n elapsedTime = new Date().getTime() - startTime;\n if (elapsedTime <= allowedTime) {\n if (Math.abs(distX) >= threshold && Math.abs(distY) <= restraint) {\n swipedir = (distX < 0) ? 'e' : 'd';\n }\n else if (Math.abs(distY) >= threshold && Math.abs(distX) <= restraint) {\n swipedir = (distY < 0) ? 'c' : 'b';\n }\n }\n end(swipedir);\n }, false);\n }",
"detectSwipe(element, callback) {\n let touchsurface = element,\n swipedir,\n startX,\n startY,\n distX,\n distY,\n threshold = 150,\n restraint = 100,\n allowedTime = 300,\n elapsedTime,\n startTime,\n handleswipe = callback || (swipedir => {});\n\n // User begins to touch the screen\n touchsurface.addEventListener('touchstart', e => {\n let touchobj = e.changedTouches[0];\n swipedir = EventConstants.SWIPE_DIRECTION.NONE;\n startX = touchobj.pageX;\n startY = touchobj.pageY;\n startTime = new Date().getTime();\n }, false);\n\n // User is dragging across the screen\n touchsurface.addEventListener('touchmove', e => {}, false);\n\n // User stops touching the screen\n touchsurface.addEventListener('touchend', e => {\n let touchobj = e.changedTouches[0];\n\n distX = touchobj.pageX - startX;\n distY = touchobj.pageY - startY;\n elapsedTime = new Date().getTime() - startTime;\n\n if (elapsedTime <= allowedTime) {\n if (Math.abs(distX) >= threshold && Math.abs(distY) <= restraint) {\n swipedir = (distX < 0) ?\n EventConstants.SWIPE_DIRECTION.LEFT :\n EventConstants.SWIPE_DIRECTION.RIGHT;\n } else if (Math.abs(distY) >= threshold && Math.abs(distX) <= restraint) {\n swipedir = (distY < 0) ?\n EventConstants.SWIPE_DIRECTION.UP :\n EventConstants.SWIPE_DIRECTION.DOWN;\n }\n }\n\n handleswipe(swipedir);\n }, false);\n }",
"function touch_click2zoom()\r\n{\r\n clear_screensaver();\r\n\r\n clearTimeout(t);\r\n flying = false;\r\n flying_2 = false;\r\n\r\n if (touch_XS&&touch_YS)\r\n {\r\n ws = ws/sensitivity3;\r\n xp = touch_XS + (xp-touch_XS)/sensitivity3;\r\n yp = touch_YS + (yp-touch_YS)/sensitivity3;\r\n draw2();\r\n click2zoomnum --;\r\n if (click2zoomnum >= 0)\r\n {\r\n t = setTimeout('touch_click2zoom()',33);\r\n }\r\n }\r\n}",
"function chkMobile() {\r\n\treturn /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds listener to resizing of window object which calls for the active phrase to be evaluated for line breaks so that phrase remains responsive, while not splitting one word into multiples. If width of screen is lt or eq to 1024 px, the THEME button's text changes to a trigram | onScreenResize () {
window.addEventListener('resize', function () {
game.activePhrase.addLineBreak();
const modal = this.document.getElementById('modal-button');
this.innerWidth <= 1024 ? modal.innerHTML = "☰" : modal.textContent = "THEME";
}, false);
} | [
"function resizeText(pixels) {\r\n\r\n}",
"function handleWindowResize() {\r\n width = window.innerWidth;\r\n}",
"function listenWindowResize() {\n $(window).resize(_handleResize);\n }",
"onResize() {\n App.bus.trigger(TRIGGER_RESIZE, document.documentElement.clientWidth, document.documentElement.clientHeight);\n }",
"actOnWindowResize() {\n self = this;\n window.addEventListener('resize', function () {\n clearTimeout(self.id);\n self.id = setTimeout(() => { self.manageHexagons() }, 100);\n });\n }",
"function ResizeHandler() {\n setMaxWindowWidth((window.innerWidth - 800) / 2);\n setMaxWindowHeight((window.innerHeight - 700) / 2);\n }",
"function bigText() {\n if ($(window).width() < 768) {\n var productInfoWrapper = $(\".product-info-wrapper\");\n if (productInfoWrapper.length) {\n productInfoWrapper.find(\".name\").fitText();\n }\n }\n }",
"attachResizeListener () {\n const throttle = (type, name) => {\n let running = false\n const func = () => {\n if (running) {\n return\n }\n running = true\n requestAnimationFrame(() => {\n window.dispatchEvent(new CustomEvent(name))\n running = false\n })\n }\n window.addEventListener(type, func)\n }\n\n throttle('resize', 'optimizedResize')\n\n window.addEventListener('optimizedResize', () => {\n // if we're in tab mode and no tab content is visible, open the previously open tab\n if (window.innerWidth >= this.defaults.breakpoint && !this.currentTab && this.previousTab) {\n this.openTab(this.previousTab.contentElement)\n }\n })\n }",
"function onResize() {\n updateHeight()\n\n // change .footer-height text\n updateText()\n }",
"function resize()\r\n{\r\n var i;\r\n \r\n i = document.getElementById(\"vline\");\r\n if (i) i.height = (getInsideWindowHeight() - 100);\r\n\r\n i = document.getElementById(\"hline1\");\r\n if (i) i.width = getInsideWindowWidth();\r\n\r\n i = document.getElementById(\"hline2\");\r\n if (i) i.width = getInsideWindowWidth();\r\n}",
"function widenProgram() {\n let s = document.getElementsByClassName('wrap_xyqcvi')[0];\n s.style.setProperty(\"max-width\", \"none\", \"important\");\n\n clearInterval(widenprogram);\n}",
"function shrink() {\r\n document.querySelectorAll('.word').forEach((element) => {\r\n element.style.fontSize = '16px';\r\n });\r\n}",
"function ksfHelp_mainTourResize()\n{\n\tif(ksfHelp_mainTour.ended() == false)\n\t{\n\t\tvar browserWidth = $(window).width();\n\t\tvar currentStep = ksfHelp_mainTour.getCurrentStep();\n\t\tif(browserWidth <= LAYOUT_WIDTH_THRESHOLD)\n\t\t{\n\t\t\tif((currentStep % 2) == 0)\n\t\t\t{\n\t\t\t\tcurrentStep += 1;\t\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif((currentStep % 2) == 1)\n\t\t\t{\n\t\t\t\tcurrentStep -= 1;\n\t\t\t}\n\t\t}\n\t\tksfHelp_mainTour.setCurrentStep(currentStep);\n\t\tksfHelp_mainTour.goTo(currentStep);\n\t}\n}",
"function ShowExampleAppAutoResize(p_open) {\r\n if (!Begin(\"Example: Auto-resizing window\", p_open, ImGuiWindowFlags.AlwaysAutoResize)) {\r\n End();\r\n return;\r\n }\r\n /* static */ const lines = STATIC(\"lines#2447\", 10);\r\n Text(\"Window will resize every-frame to the size of its content.\\nNote that you probably don't want to query the window size to\\noutput your content because that would create a feedback loop.\");\r\n SliderInt(\"Number of lines\", (value = lines.value) => lines.value = value, 1, 20);\r\n for (let i = 0; i < lines.value; i++)\r\n Text(\" \".repeat(i * 4) + `This is line ${i}`); // Pad with space to extend size horizontally\r\n End();\r\n }",
"windowResizing(event) {\n let lookupSearchWidth = this.template.querySelector(\".lookup-search\");\n if (lookupSearchWidth != null) {\n lookupSearchWidth = lookupSearchWidth.offsetWidth + \"px\";\n this.template.querySelector(\".dropdown\").style.width = lookupSearchWidth;\n }\n }",
"function growBalloon(){\n let balloon = document.getElementById('balloon');\n let size = parseInt(balloon.style.fontSize.replace(\"px\", \"\"));\n\n console.log(size);\n\n if (size >= 55){\n balloon.innerHTML = \"💥\";\n document.body.removeEventListener('keyup', balloonController);\n } else {\n balloon.style.fontSize = (size * 1.1) + \"px\";\n }\n\n\n}",
"getWindowSize() {\n if (React.findDOMNode(this).offsetWidth <= this.windowSmall)\n return \"S\";\n else if (React.findDOMNode(this).offsetWidth >= this.windowLarge)\n return \"L\";\n return \"M\";\n }",
"function addResizeListener() {\n document.getElementById('large-btn').addEventListener('click', function(event){\n changeSize('large');\n });\n document.getElementById('normal-btn').addEventListener('click', function(event){\n changeSize('normal');\n });\n document.getElementById('small-btn').addEventListener('click', function(event){\n changeSize('small');\n });\n}",
"function resizeWindow () {\n\t\tparent.postMessage($('body').height(), '*');\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate many. Similar to the single gen method, only this accepts multiple IDs | static async genMany(
viewer: ?Viewer,
ids: Array<string>,
{ Planet }: DataLoaders
): Promise<?Array<PlanetInstance>> {
const data: Array<PlanetModel> | null = await dbPlanet
.scope("withIds")
.findAll({ where: { id: [ids] } })
// Only get pure JSON from fetch,
// Though unlikely, this prevents memory leak.
.map(response => response.toJSON());
// return imideately if failed to fetch
if (!data || !data.length) return null;
// We put each field in the dataloader cache
await data.forEach(result => Planet.prime(result.id, result));
// Return each id as an instance of this class
return await data.map(result => new PlanetInstance(result));
} | [
"function generateCardIDs() {\n //for each card add its id to cardids list\n cards.forEach(card => {\n cardIDs.push(card.cardID);\n });\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 }",
"gen_id(type){\n\n var str_prefix = \"\";\n var num_id = null;\n var arr_elems = null;\n switch (type) {\n case 'tool': str_prefix = \"t-\"; arr_elems= this.get_nodes('tool'); break;\n case 'data': str_prefix = \"d-\"; arr_elems= this.get_nodes('data'); break;\n case 'edge': str_prefix = \"e-\"; arr_elems= this.get_edges(); break;\n }\n\n var ids_taken = [];\n for (var i = 0; i < arr_elems.length; i++) {\n ids_taken.push(parseInt(arr_elems[i]._private.data.id.substring(2)));\n }\n\n var num_id = 1;\n while (num_id <= arr_elems.length) {\n if (ids_taken.indexOf(num_id) == -1) {\n break;\n }else {\n num_id++;\n }\n }\n\n var num_zeros = 3 - num_id/10;\n var str_zeros = \"\";\n for (var i = 0; i < num_zeros; i++) {\n str_zeros= str_zeros + \"0\";\n }\n return str_prefix+str_zeros+num_id;\n }",
"function makeid() {\n var text = \"\";\n var possible = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n\n for (var i = 0; i < 1000; i++) {\n text += possible.charAt(Math.floor(Math.random() * possible.length));\n return text;\n }\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 create(ids,names,gameid){\r\n var ng = new Game(gameid);\r\n if (ids.length < 12){\r\n var roles=[\"WW\",\"WW\",\"Seer\",\"Witch\",\"Hunter\",\"Cupid\"];\r\n for (i = 0; i < (ids.length - 6); i++) {\r\n roles.push(\"Villager\");\r\n }\r\n }else if((ids.length > 11 && ids.length < 18)){\r\n var roles=[\"WW\",\"WW\",\"WW\",\"Seer\",\"Witch\",\"Hunter\",\"Cupid\"];\r\n for (i = 0; i < (ids.length - 7); i++) {\r\n roles.push(\"Villager\");\r\n }\r\n }else if((ids.length > 17 )){\r\n var roles=[\"WW\",\"WW\",\"WW\", \"WW\",\"Seer\",\"Witch\",\"Hunter\",\"Cupid\"];\r\n for (i = 0; i < (ids.length - 8); i++) {\r\n roles.push(\"Villager\");\r\n }\r\n }\r\n shuffled=shuffle(roles);\r\n for (i = 0; i < (ids.length); i++){\r\n var np = new GamePlayer(ids[i], names[i], shuffled[i]);\r\n np.checkwitch();\r\n final_players.push(np)\r\n console.log(\"np.id display role \");\r\n ng.addplayer(np);\r\n ng.Roles.push(np.role);\r\n ////////\r\n }\r\n return ng;\r\n\r\n }",
"function buildCrewArray(crewIdNumbers, animals){\n for (let i = 0; i < animals.length; i++) {\n for ('astronautID' in )\n }\n}",
"function getGenre(ids){\n let genresArr = [];\n ids.forEach((e)=>{\n for (let i = 0; i<genresByID.length;i++){\n if (e === genresByID[i].id) {\n genresArr.push(genresByID[i].name)\n }\n }\n })\n return genresArr.join(' - ')\n}",
"function generateBooks(model, numberOfBooks){\n \tvar sampleLength = model.length;\n \t// a while-- would be possibly quicker\n \tfor(var i = sampleLength, max = numberOfBooks;i<=max;i++){\n \t\tmodel.push({\n \t\t\tid: i + 1,\n \t\t\tname: model[Math.floor(Math.random() * sampleLength)].name,\n \t\t\tauthor: model[Math.floor(Math.random() * sampleLength)].author,\n \t\t\tgenre: model[Math.floor(Math.random() * sampleLength)].genre,\n \t\t\tpublish_date: model[Math.floor(Math.random() * sampleLength)].publish_date\n \t\t});\n \t}\n \treturn model;\n }",
"function seedRestaurantData(){\n console.info(\"seeding restaurant db with 10 objects\");\n const seedData = [];\n for (let i=1; i<=10; i++){\n seedData.push(generateRestaurantData());\n }\n return Restaurant.insertMany(seedData);\n\n}",
"function generateForAlice() {\n generatePrimes(\"alice\");\n }",
"addPermissions(ids, permissions, region) {\n for (const id of ids) {\n const permission = permissions.find((val) => val.id === id);\n this.addPermission(permission || { id }, region);\n }\n }",
"createEntity() {\n // eslint-disable-next-line no-plusplus\n const getId = () => ++this.entityIdCounter;\n return GenericBuilder(getId, (id, componentTypes, options) => {\n this.entities.add(id);\n // sort to make sure hashing is the same for different created components.\n const instances = {};\n const constructors = [];\n componentTypes.forEach((component, i) => {\n const instance = this.addComponent(id, component, options[i], false);\n const constructor = instance.constructor;\n constructors.push(constructor);\n instances[constructor.hash] = instance;\n });\n this.addEntityToArchetype(id, constructors, instances);\n });\n }",
"constructor(itemCount = 1000) {\n this.generate(itemCount);\n }",
"function generateForBob() {\n generatePrimes(\"bob\");\n }",
"function createItems() {\n const arr = new Array(22)\n return arr.fill().map((item, i) => ({ id: `a${i}`, name: 'item' }))\n}",
"static async inserMultipleContext(req, res) {\n const contextDomain = new ContextDomain();\n contextDomain.inserMultipleContext(req, res);\n }",
"packEntities(options) {\n this.entities = [];\n let identityFn = null;\n if(this.metadata.generator === 'id') {\n identityFn = (a,b) => !_.isUndefined(a.id) && !_.isUndefined(b.id) && a.id === b.id;\n }\n // console.log(this);\n\n _.forOwn(this, (v,k) => {\n if(k !== 'entities') {\n // console.log(k, v);\n this[k] = Pson.map(v, e => this.insertToEntities(e, identityFn));\n }\n });\n\n // only regenerate if not exists\n _.forEach(this.entities, (e, i) => {\n if(!e.id) {\n e.id = e.className+'-'+i;\n }\n });\n \n this.entities = _.map(this.entities, e => Pson.map(e, (c, path) => {\n if(path === '') {\n return c; \n } else {\n return c.id;\n }\n }));\n \n _.forOwn(this, (v,k) => {\n if(k !== 'entities') {\n this[k] = Pson.map(v, e => e.id);\n }\n });\n // console.log('entities', this.entities);\n }",
"function multiEnableById(ids) {\r\n for (var i = 0; i < ids.length; i++) {\r\n var obj = getObj(ids[i]);\r\n if (obj != null) obj.disabled = false;\r\n }\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calls all of the envet listener with all of the arguments (which should be an array) | _callEventListeners(event, args = []) {
// Make args an array if it's not
const arrayArgs = Array.isArray(args) ? args : [args];
if (this._eventListeners[event]) {
for (const handler of this._eventListeners[event]) {
handler.apply(null, arrayArgs);
}
}
} | [
"_emit(event, args) {\n return Promise.all(this.listeners(event).map(listener => {\n if (typeof listener.listener === 'function'){\n this.removeListener(event, listener);\n }\n\n return (listener.listener || listener).apply(this, args);\n }));\n }",
"hear (...args) {\n return this.listen('hear', ...args)\n }",
"static bind(keys, classRef) {\n for (let key of keys) {\n if (listeners[key]) {\n listeners[key].push(classRef)\n } else {\n listeners[key] = [classRef]\n }\n }\n }",
"notifySenders () {\n let message = Object.assign({}, arguments);\n this.mb.broadcast(message);\n }",
"fire(name, ...args) {\n if (this._cb.hasOwnProperty(name)) {\n this._cb[name](...args);\n }\n }",
"InstallMultipleEventClasses() {\n\n }",
"assignCallbacks() {\n this.namespace.on('connection', (socket) => {\n this.onWhisper(socket);\n });\n }",
"function normalizeOnEventArgs(args) {\n if (typeof args[0] === 'object') {\n return args;\n }\n \n var selector = null;\n var eventMap = {};\n var callback = args[args.length - 1];\n var events = args[0].split(\" \");\n \n for (var i = 0; i < events.length; i++) {\n eventMap[events[i]] = callback;\n }\n \n // Selector is the optional second argument, callback is always last.\n if (args.length === 3) {\n selector = args[1];\n }\n \n return [ eventMap, selector ];\n }",
"callAllCallbacks() {\n this.callbackSets.forEach((set) => {\n this.callCallbackSet(set);\n });\n }",
"emit(args, scope) {\n constants_1.debug('Emitting \"%s%s\" as bail', this.name, scope ? `:${scope}` : '');\n return Array.from(this.getListeners(scope)).some(listener => listener(...args) === false);\n }",
"onPlayheadChanged () {\n this.isCompleted = false;\n this.playhead = arguments;\n\n this.notifySenders.apply(this, arguments);\n }",
"function listenerSetCallback(listeners) {\n var listenersAlive = _.map(listeners, function(listener) {\n if (listener.condition()) {\n listener.callback(angular.copy(directory[listeners.listName].options));\n return true;\n }\n });\n for (var i = listenersAlive.length - 1; i >= 0; i--) {\n if (!listenersAlive[i]) { listeners.splice(i,1); }\n }\n\n // if there are no listeners left then kill the watcher\n if (listeners.length === 0) { listeners.watcher(); }\n }",
"function inotifywaitArgs() {\n var listener,\n args = [\"-m\", \"-q\",\n options.recursive ? \"-r\" : \"\",\n \"--timefmt\",\n \"%d %b %Y %T %z\",\n \"--format\",\n \",{\\\"filename\\\": \\\"%w%f\\\", \\\"eventId\\\": \\\"%e\\\", \\\"timestamp\\\": \\\"%T\\\"}\"];\n\n if (!options.listeners.all_events) {\n for (listener in options.listeners) {\n if (options.listeners.hasOwnProperty(listener)) {\n listener = listener.replace(\"remove\", \"delete\");\n args.push(\"-e\", listener);\n }\n }\n }\n\n options.exclude.forEach(function (ex) { args.push(\"@\" + ex); });\n\n args.push.apply(args, options.target);\n\n return args;\n}",
"async registerListeners () {\n this.container.on(DockerEventEnum.STATUS_UPDATE, newStatus => this.updateStatus(newStatus));\n this.container.on(DockerEventEnum.CONSOLE_OUTPUT, data => this.onConsoleOutput(data));\n\n this.on(DockerEventEnum.STATUS_UPDATE, newStatus => {\n if (newStatus === ServerStatus.OFFLINE) {\n if (this.config.properties.deleteOnStop) {\n this.logger.info('Server stopped, deleting container...');\n this.remove()\n .catch(err => this.logger.error('Failed to delete the container!', { err }));\n } else if (this.config.properties.autoRestart) {\n this.logger.info('Restarting the server...');\n this.start();\n }\n }\n });\n }",
"function broadcast(...args) {\n // XXX(Kagami): Better to use `for...of` but it seems to generate\n // inefficient code in babel currently.\n [...connected.values()].forEach(transport => transport.send(...args));\n}",
"didUpdateArguments () {\n\n }",
"function listeners_(){this.listeners$bq6g=( {});}",
"listeners() {\n // Listeners\n this.templates.userChoices.querySelectorAll('button').forEach((button) => {\n button.addEventListener('click', (event) => {\n event.preventDefault();\n this.model.getWinner(Number(event.target.dataset.choice));\n this.render(this.$el, this.model.getData())();\n });\n });\n\n this.templates.restartApp.addEventListener('click', (event) => {\n event.preventDefault();\n this.model.restartApp();\n this.render(this.$el, this.model.getData())();\n });\n\n this.templates.switchToComputer.addEventListener('click', (event) => {\n event.preventDefault();\n this.model.getWinner();\n this.render(this.$el, this.model.getData())();\n });\n }",
"determineArguments(suppliedArgs, contract, accounts, callback) {\n const self = this;\n\n let args = suppliedArgs;\n if (!Array.isArray(args)) {\n args = [];\n let abi = contract.abiDefinition.find((abi) => abi.type === 'constructor');\n\n for (let input of abi.inputs) {\n let inputValue = suppliedArgs[input.name];\n if (!inputValue) {\n this.logger.error(__(\"{{inputName}} has not been defined for {{className}} constructor\", {inputName: input.name, className: contract.className}));\n }\n args.push(inputValue || \"\");\n }\n }\n\n function parseArg(arg, cb) {\n const match = arg.match(/\\$accounts\\[([0-9]+)]/);\n if (match) {\n if (!accounts[match[1]]) {\n return cb(__('No corresponding account at index %d', match[1]));\n }\n return cb(null, accounts[match[1]]);\n }\n let contractName = arg.substr(1);\n self.events.request('contracts:contract', contractName, (referedContract) => {\n // Because we're referring to a contract that is not being deployed (ie. an interface),\n // we still need to provide a valid address so that the ABI checker won't fail.\n cb(null, (referedContract.deployedAddress || ZERO_ADDRESS));\n });\n }\n\n function checkArgs(argus, cb) {\n async.map(argus, (arg, nextEachCb) => {\n if (arg[0] === \"$\") {\n return parseArg(arg, nextEachCb);\n }\n\n if (Array.isArray(arg)) {\n return checkArgs(arg, nextEachCb);\n }\n\n self.events.request('ens:isENSName', arg, (isENSName) => {\n if (isENSName) {\n return self.events.request(\"ens:resolve\", arg, (err, address) => {\n if (err) {\n return nextEachCb(err);\n }\n nextEachCb(err, address);\n });\n }\n\n nextEachCb(null, arg);\n });\n }, cb);\n }\n\n checkArgs(args, callback);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deleting a Graphics by ID | function deleteGraphics(req, res) {
const { knex } = req.app.locals
const { GraphicsID } = req.params
knex('graphics')
.where('GraphicsID', GraphicsID)
.del()
.then(response => {
if (response) {
res.status(200).json(`Graphics with ID ${GraphicsID} is deleted`)
} else {
res.status(404).json(`Graphics with ID ${GraphicsID} is not found`)
}
})
.catch(error => res.status(500).json(error))
} | [
"function gui_removeArea(id) {\n\tif (props[id]) {\n\t\t//shall we leave the last one?\n\t\tvar pprops = props[id].parentNode;\n\t\tpprops.removeChild(props[id]);\n\t\tvar lastid = pprops.lastChild.aid;\n\t\tprops[id] = null;\n\t\ttry {\n\t\t\tgui_row_select(lastid, true);\n\t\t\tmyimgmap.currentid = lastid;\n\t\t}\n\t\tcatch (err) {\n\t\t\t//alert('noparent');\n\t\t}\n\t}\n}",
"function deleteCard(id) {\n if (id === editId) {\n closeEditor()\n }\n cards.get(id).removeEvents(id)\n cards.get(id).node.remove()\n cards.delete(id)\n markDirty()\n }",
"function deleteLine() {\n gMeme.lines.splice(gMeme.selectedLineIdx, 1)\n if (gMeme.selectedLineIdx >= gMeme.lines.length) {\n gMeme.selectedLineIdx = gMeme.lines.length - 1\n }\n drawImgText(elImgText)\n}",
"function deleteTictactoe(id) {\n console.log(\"delete Tictactoe: \" + id);\n return axios\n .delete(\"/api/tictactoe/\" + id)\n .then((res) => loadTictactoes())\n .catch((err) => console.log(err));\n }",
"delete(){\n\t\tif (removeFromReferenceCount(this.index) === 0){\n\t\t\tthis.gl.deleteTexture(this.texture);\n\t\t}\n }",
"function deleteTempImage(){\n game.remove(tempImage);\n}",
"function OnkeyDown(event){\n var activeObject = PhotoCollage.getActiveObject();\n if (event.keyCode === 46) {\n \tPhotoCollage.remove(activeObject);\n }\n}",
"function removeAmChart(id) {\n var tmp_am = getAmChart(id);\n if(tmp_am){\n tmp_am.clear();\n }\n}",
"function deleteVassalOnClick(e){\r\n // Remove the element\r\n g_vassals.splice(parseInt(e.currentTarget.parentNode.id.split('vassal_')[1]), 1);\r\n\r\n setVassals();\r\n setVassalTable();\r\n}",
"function deleteMarker(id){\n\t\n\tmarkersDictionary[id].setMap(null);\n\tmarkersDictionary[id] = undefined;\n\tdelete markersDictionary[id];\n}",
"async handleDeleteGif(id) {\n\t\t// send email and gif id through api gateway where lambda will delete from database\n\t\tawait axios\n\t\t\t.post('https://6t35dobcna.execute-api.us-east-1.amazonaws.com/dev/api-lambda-dynamo-delete-gif', {\n\t\t\t\temail: localStorage.getItem('userEmail'),\n\t\t\t\tgif: id\n\t\t\t})\n\t\t\t.then((res) => {\n\t\t\t\tconsole.log('Gif Deleted From Account!');\n\t\t\t})\n\t\t\t.catch((err) => {\n\t\t\t\tconsole.log(err);\n\t\t\t});\n\n\t\t// refresh page to see update\n\t\twindow.location.reload(false);\n\t}",
"removeHitObject() {\n const pos = this.findObj(this.lastUpdated);\n if (pos >= 0) {\n const sprite = this.hitObjectSpriteList.filter(item => item.id === 'CIRCLE_' + this.lastUpdated);\n if (sprite.length > 0) {\n this.hitObjectStage.removeChild(sprite[0]);\n sprite[0].destroy();\n }\n this.hitObjects.splice(pos, 1);\n this.hitObjectSpriteList.splice(pos, 1);\n }\n }",
"function deletePlatform(){\r\n var platforms = svgdoc.getElementById(\"platforms\");\r\n \r\n for (var i = 0; i < platforms.childNodes.length; i++) {\r\n var platform = platforms.childNodes.item(i);\r\n\r\n if(platform.getAttribute(\"delete\") == \"true\") {\r\n platforms.removeChild(platform);\r\n }\r\n }\r\n}",
"function removeMyGifos(gifId) {\n\tconst newGifosArray = arrMyGifos.filter((item) => item !== gifId);\n\tarrMyGifos = [...newGifosArray];\n\tlocalStorage.setItem(\"MyGifs\", JSON.stringify(arrMyGifos));\n\tdisplayMisGifosSection();\n}",
"function deleteDevSub(imgId){\n\tif(globalInfoType == \"JSON\"){\n \t\tvar devices = getDevicesNodeJSON();\n\t\tfor(var a=0; a<devices.length;a++){\n\t\t\tif(devices[a].Status == \"Reserved\" && devices[a].ObjectPath == imgId){\n\t\t\t\tdevices[a].UpdateFlag = \"delete\";\n\t\t\t\tdeleteLinkFromDev(devices[a].ObjectPath);\n\t\t\t\tdevices.splice(a,1);\n\t\t\t\taddEvent2History(\"Device deleted\");\n\t\t\t\ta = devices.length;\n\t\t\t}else if(devices[a].ObjectPath == imgId && devices[a].Status != \"Reserved\"){\n\t\t\t\tdeleteLinkFromDev(devices[a].ObjectPath);\n\t\t\t\tdevices.splice(a,1);\n\t\t\t\taddEvent2History(\"Device deleted\");\n\t\t\t\ta = devices.length;\n\t\t\t}\n\t\t}\n \t}\n\tdrawImage();\n}",
"delete() {\n\t\t// Remove all edge relate to vertex\n\t\tthis.vertexMgmt.edgeMgmt.removeAllEdgeConnectToVertex(this)\n\n\t\t// Remove from DOM\n\t\td3.select(`#${this.id}`).remove()\n\t\t// Remove from data container\n\t\t_.remove(this.dataContainer.vertex, (e) => {\n\t\t\treturn e.id === this.id\n\t\t})\n\t}",
"function remove_marker(id) {\n\n\t console.log('removing marker', id);\n\n\t // add marker\n\t delete(troops[id]);\n\t delete(paths[id]);\n\n\t\tgoogle.maps.event.addListener(troops[id], 'click', function() {\n\t\t\tconsole.log('removed marker', id);\n\t\t});\n\n\t}",
"function deleteBurger(id) {\n fetch(`${URL}/${id}`, {\n method: \"DELETE\"\n })//end of fetch\n const deletedBurger = document.querySelector(`div[data-id=\"${id}\"]`)\n menu.removeChild(deletedBurger)\n }//end of delete burger",
"function deleteSpecificLink(){\n\tvar linkArray = new Array();\n\t$('.linkiddelete').each(function(){\n\t\tif($(this).is(':checked')){\n\t\t\tlinkArray.push($(this).attr('did'));\n\t\t}\n\t});\n\tif(linkArray.length == 0){\n\t\talerts(\"Please select one entry.\");\n\t\treturn;\n\t}\n\tfor(var t=0; t<linkArray.length; t++){\n\t\tvar pathArr = linkArray[t].split(\"::\");\n\t\tvar port= getPortObject2(pathArr[0]);\n\t\tvar port2= getPortObject2(pathArr[1]);\n\t\tport.PORTMAP = [];\n\t\tport2.PORTMAP = [];\n\t}\n\tdrawImage();\n\t$('#deleteLinkPopUp').empty();\n\tcloseDialog(\"deleteLinkPopUp\");\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
generate a kbit true random prime using Maurer's algorithm, and put it into ans. The bigInt ans must be large enough to hold it. | function randTruePrime_(ans,k) {
var c,m,pm,dd,j,r,B,divisible,z,zz,recSize;
if (primes.length==0)
primes=findPrimes(30000); //check for divisibility by primes <=30000
if (pows.length==0) {
pows=new Array(512);
for (j=0;j<512;j++) {
pows[j]=Math.pow(2,j/511.-1.);
}
}
//c and m should be tuned for a particular machine and value of k, to maximize speed
c=0.1; //c=0.1 in HAC
m=20; //generate this k-bit number by first recursively generating a number that has between k/2 and k-m bits
var recLimit=20; //stop recursion when k <=recLimit. Must have recLimit >= 2
if (s_i2.length!=ans.length) {
s_i2=dup(ans);
s_R =dup(ans);
s_n1=dup(ans);
s_r2=dup(ans);
s_d =dup(ans);
s_x1=dup(ans);
s_x2=dup(ans);
s_b =dup(ans);
s_n =dup(ans);
s_i =dup(ans);
s_rm=dup(ans);
s_q =dup(ans);
s_a =dup(ans);
s_aa=dup(ans);
}
if (k <= recLimit) { //generate small random primes by trial division up to its square root
pm=(1<<((k+2)>>1))-1; //pm is binary number with all ones, just over sqrt(2^k)
copyInt_(ans,0);
for (dd=1;dd;) {
dd=0;
ans[0]= 1 | (1<<(k-1)) | Math.floor(trueRandom()*(1<<k)); //random, k-bit, odd integer, with msb 1
for (j=1;(j<primes.length) && ((primes[j]&pm)==primes[j]);j++) { //trial division by all primes 3...sqrt(2^k)
if (0==(ans[0]%primes[j])) {
dd=1;
break;
}
}
}
carry_(ans);
return;
}
B=c*k*k; //try small primes up to B (or all the primes[] array if the largest is less than B).
if (k>2*m) //generate this k-bit number by first recursively generating a number that has between k/2 and k-m bits
for (r=1; k-k*r<=m; )
r=pows[Math.floor(trueRandom()*512)]; //r=Math.pow(2,Math.random()-1);
else
r=.5;
//simulation suggests the more complex algorithm using r=.333 is only slightly faster.
recSize=Math.floor(r*k)+1;
randTruePrime_(s_q,recSize);
copyInt_(s_i2,0);
s_i2[Math.floor((k-2)/bpe)] |= (1<<((k-2)%bpe)); //s_i2=2^(k-2)
divide_(s_i2,s_q,s_i,s_rm); //s_i=floor((2^(k-1))/(2q))
z=bitSize(s_i);
for (;;) {
for (;;) { //generate z-bit numbers until one falls in the range [0,s_i-1]
randBigInt_(s_R,z,0);
if (greater(s_i,s_R))
break;
} //now s_R is in the range [0,s_i-1]
addInt_(s_R,1); //now s_R is in the range [1,s_i]
add_(s_R,s_i); //now s_R is in the range [s_i+1,2*s_i]
copy_(s_n,s_q);
mult_(s_n,s_R);
multInt_(s_n,2);
addInt_(s_n,1); //s_n=2*s_R*s_q+1
copy_(s_r2,s_R);
multInt_(s_r2,2); //s_r2=2*s_R
//check s_n for divisibility by small primes up to B
for (divisible=0,j=0; (j<primes.length) && (primes[j]<B); j++)
if (modInt(s_n,primes[j])==0 && !equalsInt(s_n,primes[j])) {
divisible=1;
break;
}
if (!divisible) //if it passes small primes check, then try a single Miller-Rabin base 2
if (!millerRabinInt(s_n,2)) //this line represents 75% of the total runtime for randTruePrime_
divisible=1;
if (!divisible) { //if it passes that test, continue checking s_n
addInt_(s_n,-3);
for (j=s_n.length-1;(s_n[j]==0) && (j>0); j--); //strip leading zeros
for (zz=0,w=s_n[j]; w; (w>>=1),zz++);
zz+=bpe*j; //zz=number of bits in s_n, ignoring leading zeros
for (;;) { //generate z-bit numbers until one falls in the range [0,s_n-1]
randBigInt_(s_a,zz,0);
if (greater(s_n,s_a))
break;
} //now s_a is in the range [0,s_n-1]
addInt_(s_n,3); //now s_a is in the range [0,s_n-4]
addInt_(s_a,2); //now s_a is in the range [2,s_n-2]
copy_(s_b,s_a);
copy_(s_n1,s_n);
addInt_(s_n1,-1);
powMod_(s_b,s_n1,s_n); //s_b=s_a^(s_n-1) modulo s_n
addInt_(s_b,-1);
if (isZero(s_b)) {
copy_(s_b,s_a);
powMod_(s_b,s_r2,s_n);
addInt_(s_b,-1);
copy_(s_aa,s_n);
copy_(s_d,s_b);
GCD_(s_d,s_n); //if s_b and s_n are relatively prime, then s_n is a prime
if (equalsInt(s_d,1)) {
copy_(ans,s_aa);
return; //if we've made it this far, then s_n is absolutely guaranteed to be prime
}
}
}
}
} | [
"function randTruePrime(k) {\r\n var ans=int2bigInt(0,k,0);\r\n randTruePrime_(ans,k);\r\n return trim(ans,1);\r\n }",
"function randProbPrimeRounds(k,n) {\r\n var ans, i, divisible, B;\r\n B=30000; //B is largest prime to use in trial division\r\n ans=int2bigInt(0,k,0);\r\n\r\n //optimization: try larger and smaller B to find the best limit.\r\n\r\n if (primes.length==0)\r\n primes=findPrimes(30000); //check for divisibility by primes <=30000\r\n\r\n if (rpprb.length!=ans.length)\r\n rpprb=dup(ans);\r\n\r\n for (;;) { //keep trying random values for ans until one appears to be prime\r\n //optimization: pick a random number times L=2*3*5*...*p, plus a\r\n // random element of the list of all numbers in [0,L) not divisible by any prime up to p.\r\n // This can reduce the amount of random number generation.\r\n\r\n randBigInt_(ans,k,0); //ans = a random odd number to check\r\n ans[0] |= 1;\r\n divisible=0;\r\n\r\n //check ans for divisibility by small primes up to B\r\n for (i=0; (i<primes.length) && (primes[i]<=B); i++)\r\n if (modInt(ans,primes[i])==0 && !equalsInt(ans,primes[i])) {\r\n divisible=1;\r\n break;\r\n }\r\n\r\n //optimization: change millerRabin so the base can be bigger than the number being checked, then eliminate the while here.\r\n\r\n //do n rounds of Miller Rabin, with random bases less than ans\r\n for (i=0; i<n && !divisible; i++) {\r\n randBigInt_(rpprb,k,0);\r\n while(!greater(ans,rpprb)) //pick a random rpprb that's < ans\r\n randBigInt_(rpprb,k,0);\r\n if (!millerRabin(ans,rpprb))\r\n divisible=1;\r\n }\r\n\r\n if(!divisible)\r\n return ans;\r\n }\r\n }",
"function randProbPrime(k) {\r\n if (k>=600) return randProbPrimeRounds(k,2); //numbers from HAC table 4.3\r\n if (k>=550) return randProbPrimeRounds(k,4);\r\n if (k>=500) return randProbPrimeRounds(k,5);\r\n if (k>=400) return randProbPrimeRounds(k,6);\r\n if (k>=350) return randProbPrimeRounds(k,7);\r\n if (k>=300) return randProbPrimeRounds(k,9);\r\n if (k>=250) return randProbPrimeRounds(k,12); //numbers from HAC table 4.4\r\n if (k>=200) return randProbPrimeRounds(k,15);\r\n if (k>=150) return randProbPrimeRounds(k,18);\r\n if (k>=100) return randProbPrimeRounds(k,27);\r\n return randProbPrimeRounds(k,40); //number from HAC remark 4.26 (only an estimate)\r\n }",
"function randomInteger(k) {\n return Math.ceil((Math.random() * k ));\n}",
"function numPrimorial(n){\n // need an edge case of n = 1\n if (n === 1) {\n console.log(2);\n return 2;\n }\n //find 'n' prime numbers\n let limit = n * n;\n let primes = [];\n let allNums = [];\n // need a loop to gather all the numbers that only divide by themselves and 1\n for (let i = 2; i <= limit; i++) {\n // console.log(allNums[i]);\n if (!allNums [i]) {\n primes.push(i);\n // use the << operator to round up.\n for (let j = i << 1; j <= limit; j += i)\n {\n allNums[j] = true;\n }\n // console.log(allNums);\n }\n }\n console.log(primes);\n // multiply the 'n' primes together\n let answer = 1;\n for (let p = 0; p < n; p++) {\n answer *= primes[p];\n }\n console.log(answer);\n return answer;\n}",
"function get10001Prime(){\n while(primes.length < 10001){\n primeTest(currentNumber);\n currentNumber++;\n }\n}",
"function randBigInt_(b,n,s) {\r\n var i,a;\r\n for (i=0;i<b.length;i++)\r\n b[i]=0;\r\n a=Math.floor((n-1)/bpe)+1; //# array elements to hold the BigInt\r\n for (i=0;i<a;i++) {\r\n b[i]=Math.floor(trueRandom()*(1<<(bpe-1)));\r\n }\r\n b[a-1] &= (2<<((n-1)%bpe))-1;\r\n if (s==1)\r\n b[a-1] |= (1<<((n-1)%bpe));\r\n }",
"function generateForBob() {\n generatePrimes(\"bob\");\n }",
"function k_random_ints(k, min, max){\n var ints = [];\n for(var i = 0; i < k; ++i){\n ints.push(Math.floor(Math.random() * (max - min)) + min);\n }\n return ints;\n}",
"function getSubPrimes(p, idx, k){\n\tdebug.log(5, \"!! getSubPrimes():\");\n\tdebug.log(7, arguments);\n\tgetPrimes(p, idx+2);\n\t\n\tvar sum = 0;\n\tvar mp = get_mp(p, 0, idx, Math.floor(p[idx]/k));\n\tvar i = mp - Math.floor(k/2) < 0 ? 0 : mp - Math.floor(k/2);\n\tfor (var j=i; j<i+k; j++){ sum += p[j];}\n\tdebug.log(6, \"i: \"+i+\", p[\"+idx+\"]: \"+p[idx]+\", sum: \"+sum);\n\tdebug.log(8, \"getSubPrimes(): p[\"+i+\"] (\"+p[i]+\") * \"+k+\n\t\t\" (\"+p[i]*k+\") < p[\"+idx+\"] (\"+p[idx]);\n\tdebug.log(8, \"getSubPrimes(): p[\"+(i+k-1)+\"] (\"+p[i+k-1]+\") * \"+k+\n\t\t\" (\"+p[i+k-1]*k+\") > p[\"+idx+\"] (\"+p[idx]);\n\n\tif (sum < p[idx]){\n\t\twhile (sum < p[idx] && i<=mp){\n\t\t\ti++;\n\t\t\tsum += p[i+k-1]-p[i-1];\n\t\t\tdebug.log(6, \"new i: \"+i+\", new sum: \"+sum);\n\t\t}\n\t} else if (sum > p[idx]){\n\t\twhile(sum > p[idx] && i>0 && i+k>mp){\n\t\t\ti--;\n\t\t\tsum -= p[i+k]-p[i];\n\t\t\tdebug.log(6, \"new i: \"+i+\", new sum: \"+sum);\n\t\t}\n\t}\n\n\tif (sum === p[idx]){return i;}\n\treturn -1; // else\n\n\twhile (p[i+k-1]*k < p[idx]) {i++;}\n\tdebug.log(4, \"getSubPrimes(): p[\"+(i+k-1)+\"] (\"+p[i+k-1]+\") * \"+k+\n\t\t\" (\"+p[i+k-1]*k+\") > p[\"+idx+\"] (\"+p[idx]);\n\twhile (p[i]*k < p[idx]){\n\t\tif (sum === 0){\n\t\t\tfor (var j=i; j<i+k; j++){ sum += p[j];}\n\t\t} else{\n\t\t\tsum += p[i+k]-p[i];\n\t\t}\n\t\tdebug.log(4, \"sum: \"+sum+\", i: \"+i);\n\t\tif (sum === p[idx]){\n\t\t\treturn i;\n\t\t}\n\t\ti++;\n\t}\n\treturn -1;\n}",
"function prim(nr) {\n let prim = true;\n for (let i = 2; i <= nr / 2; i++) {\n if (nr % i === 0) {\n prim = false;\n break;\n } else prim = true;\n }\n return prim;\n}",
"function getPermutation(n, k) {\n return getFactorial(n) / getFactorial(n - k);\n }",
"function primeTime (num){\n\tvar SqrRtNum = Math.sqrt(num);\n\tvar primeNum = true;\n\tfor(var i=2 ; i<SqrRtNum ; i++){\n\t\tif(num%i === 0){\n\t\t\tprimeNum = false;\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn primeNum;\n\n}",
"function generateForAlice() {\n generatePrimes(\"alice\");\n }",
"primeAnagramPalindrom() {\n //Evaluating Prime Numbers\n\n for (var i = 0; i <= 1000; i++) { // create variable count and assign value 0 to it\n var count = 0\n\n for (var j = 0; j <= i; j++) {\n if (i % j == 0) {\n count++;\n }\n }\n if (count == 2 && i > 10)\n {\n this.palindrom(i);\n }\n }\n\n }",
"function candies(n, m) {\n let divisible = Math.floor(m / n);\n return divisible * n;\n}",
"function getPrimes(num) {\n var a = [...Array(num + 1).keys()]; // =[0,1,...,num]\n a[1] = 0; // 1 is not prime\n var rt = Math.sqrt(num); // calculate only once\n for (i = 2; i <= rt; i++) {\n for (var j = i * i; j <= num; j += i) a[j] = 0;\n }\n return a.filter(Number); // kick out the zeroes\n}",
"function memoizeFactorial(n){\r\n\r\n}",
"function setNumber() {\n\tsecretNumber = Math.ceil(Math.random() * 99);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Unregisters an NFC tag to a child. | async function unregisterNfcByUsername(req, res) {
try {
// 1. Check if the child exists
const child = await getChildByUsername(req.params.username)
if (!child) { // child not found by given username
return res.status(400).send(msgChildNotFoundUsername(req.params.username))
}
// 2. Unregisters an NFC tag to a child.
await httpClient.delete(`${ACCOUNT_URL_BASE}/v1/children/${child.id}/nfc`, req.body)
res.status(204).send()
} catch (err) {
if (err.response && err.response.status) {
return res.status(err.response.status).send(err.response.data)
}
errorHandler(500, res, req)
}
} | [
"function removeTag(tag) {\n tag.parentNode.removeChild(tag);\n}",
"function getChildByNfcTag(tag) {\n return new Promise((resolve, reject) => {\n httpClient\n .get(`${ACCOUNT_URL_BASE}/v1/children/nfc/${tag}`)\n .then((result) => {\n if (result.data) {\n return resolve(result.data)\n }\n resolve(undefined)\n })\n .catch(err => {\n if (err.response && err.response.status === 404) {\n resolve(undefined)\n }\n reject(err)\n })\n })\n}",
"remove() {\n const ownerElement = this.node.ownerElement\n if(ownerElement) {\n ownerElement.removeAttribute(this.name)\n }\n }",
"async function registerNfcByUsername(req, res) {\n try {\n // 1. Check if the child exists\n const child = await getChildByUsername(req.params.username)\n if (!child) { // child not found by given username\n return res.status(400).send(msgChildNotFoundUsername(req.params.username))\n }\n\n // 2. Registers an NFC tag to a child.\n await httpClient.post(`${ACCOUNT_URL_BASE}/v1/children/${child.id}/nfc`, req.body)\n res.status(204).send()\n } catch (err) {\n if (err.response && err.response.status) {\n return res.status(err.response.status).send(err.response.data)\n }\n errorHandler(500, res, req)\n }\n}",
"function pushdeRegister()\n{\n\t//kony.print(\"************ JS unregisterFromAPNS() called *********\");\n\tkony.application.showLoadingScreen(\"sknLoading\",\"Deregistering from push notification..\",constants.LOADING_SCREEN_POSITION_FULL_SCREEN, true, true,null);\n\t\tkony.push.deRegister({});\n\t\taudiencePushSubs=false;\n\t\teditAudience2();\n\t\t\n}",
"disconnectedCallback() {\n super.disconnectedCallback();\n document.removeEventListener('incoming-custom-event', this.handleIncoming)\n }",
"__unregisterInterfaceAttribute__( interfaceAttr ){\n delete VIRTUAL_BUTTONS_STATE[ interfaceAttr ];\n return true;\n }",
"destroy()\n {\n this.parentGroup.removeSprite(this);\n }",
"function removeFriendElement(uid) {\n document.getElementById(\"user\" + uid).remove();\n\n friendCount--;\n if(friendCount == 0){\n deployFriendListEmptyNotification();\n }\n }",
"removeTags(tagName) {\n (0, utils_1.removeIf)(this.blockTags, (tag) => tag.tag === tagName);\n }",
"removeTagIndexForBinding(binding) {\n for (const [, bindings] of this.bindingsIndexedByTag) {\n bindings.delete(binding);\n }\n }",
"release() {\n if (Stack.onresolve) {\n Stack.onresolve(this.id)\n }\n\n delete stacks[this.id]\n ids.release(this.id)\n\n if (this.close) {\n this.close()\n }\n }",
"onAttrRemove (attrName, entName) {\n if (this.entityAttrsUse.length <= 0) return // microdata list already empty\n if (!attrName || !entName) {\n console.warn('Unable to remove from microdata list, attribute or entity name is empty:', attrName, entName)\n return\n }\n const name = entName + '.' + attrName\n this.$q.notify({ type: 'info', message: this.$t('Exclude from microdata') + ': ' + name })\n\n this.entityAttrsUse = this.entityAttrsUse.filter(ean => ean !== name)\n this.refreshEntityTreeTickle = !this.refreshEntityTreeTickle\n }",
"function postUnflagQuote( queryObj, response, sessionObj, onFinish )\n{\n _changeFlagQuote( dataAPI.unflagQuote, queryObj, response, sessionObj, onFinish );\n}",
"function doHumanDetectFaceUnregister(serviceId, sessionKey) {\r\n\r\n dConnect.removeEventListener({\r\n profile: 'humandetection',\r\n attribute: 'onfacedetection',\r\n params: {\r\n serviceId: serviceId\r\n }\r\n }).catch(e => {\r\n alert(e.errorMessage);\r\n });\r\n}",
"function removePostcode(postcode){\n\tvar element = document.getElementById(postcode);\n element.parentNode.removeChild(element);\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 }",
"handleChipDelete(item) {\n const tags = [...this.state.tags];\n const index = tags.indexOf(item);\n tags.splice(index, 1);\n this.setState({ tags: tags });\n }",
"reset() {\n this.tag = this.default;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
diamond 3 random formula with result | function diamond3() {
return Math.floor(Math.random() * 11 + 1);
} | [
"function diamond4() {\n return Math.floor(Math.random() * 11 + 1);\n }",
"function inning(){\n return (Math.floor(Math.random()*3));\n\n}",
"function randomSquare3() {\n selected3 = squares[randomNum()]\n }",
"static generateRandomAngle() {\n return Math.random() * Math.PI * 2;\n }",
"function generateRefractors(){\n refractorSet.clear();\n let refractorRows = Math.floor(1.5 + simHeight / 300);\n let refractorCols = Math.floor(1.5 + simWidth / 300);\n\n let rowSpace = simHeight / (refractorRows);\n let colSpace = simWidth / (refractorCols);\n\n let triangleRadius = Math.min(rowSpace / 2 - (7 + simHeight / 50), colSpace / 2 - (7 + simWidth / 50));\n\n for(let i = 0; i < refractorCols; i ++)\n {\n for(let j = 0; j < refractorRows; j ++)\n {\n if(i != 0 || refractorRows % 2 == 0 || j != Math.floor(refractorRows / 2)){\n let center = new Vector(colSpace / 2 + colSpace * i, rowSpace / 2 + rowSpace * j);\n let ang = Math.random() * Math.PI * 2;\n let p1 = addVectors(angleMagVector(ang, triangleRadius), center);\n ang += Math.PI / 3 + Math.random() * Math.PI * .4;\n let p2 = addVectors(angleMagVector(ang, triangleRadius), center);\n ang += Math.PI / 3 + Math.random() * Math.PI * .4;\n let p3 = addVectors(angleMagVector(ang, triangleRadius), center);\n\n refractorSet.add(new SimVector(p1, subVectors(p2, p1)));\n refractorSet.add(new SimVector(p2, subVectors(p3, p2)));\n refractorSet.add(new SimVector(p3, subVectors(p1, p3)));\n }\n }\n }\n}",
"static cauchyRand() {\n return Math.tan(Math.PI * (Math.random() - 0.5));\n }",
"generateDistTrav()\r\n {\r\n var distance = Math.floor((Math.random() * 2) + 1)\r\n console.log(distance + \"m\")\r\n }",
"function generateThreeCorrectSlotsOfThree() {\r\n currentBlock = blockValues[i];\r\n firstCorrect = randomNumberNeg9Through9();\r\n while ((currentBlock + firstCorrect) < -9 || (currentBlock + firstCorrect) > 9) {\r\n firstCorrect = randomNumberNeg9Through9();\r\n }\r\n slotValues[j] = firstCorrect;\r\n document.getElementById(slotIds[j].toString()).textContent = slotValues[j];\r\n j++;\r\n secondCorrect = randomNumberNeg9Through9();\r\n while ((currentBlock+firstCorrect+secondCorrect) < 0 || (currentBlock+firstCorrect+secondCorrect) > 9) {\r\n secondCorrect = randomNumberNeg9Through9();\r\n }\r\n slotValues[j] = secondCorrect;\r\n document.getElementById(slotIds[j].toString()).textContent = slotValues[j];\r\n j++;\r\n thirdCorrect = randomNumberNeg9Through9();\r\n while ((currentBlock+firstCorrect+secondCorrect+thirdCorrect) < 0 || (currentBlock+firstCorrect+secondCorrect+thirdCorrect) > 9) {\r\n thirdCorrect = randomNumberNeg9Through9();\r\n }\r\n slotValues[j] = thirdCorrect;\r\n document.getElementById(slotIds[j].toString()).textContent = slotValues[j];\r\n j++;\r\n nextBlock = currentBlock + firstCorrect + secondCorrect + thirdCorrect;\r\n}",
"function complicatedMath(n1,n2,n3,n4){\n return (n1+n2) % (n3-n4)\n}",
"function gethand(x)\n\t\t\t{\n\t\t\t\tvar x = parseInt((Math.random()*3))\n\t\t\t\tif (x == 0 )\n\t\t\t\t\t{\n\t\t\t\t\t\tx = hands[0];\n\n\t\t\t\t\t}\n\t\t\t\telse if(x == 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tx = hands[1];\n\t\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tx = hands[2];\n\t\t\t\t\t}\n\t\t\t\treturn x;\n\t\t\t\t\n\t\t\t}",
"function createMinusLevelFour() {\n var rangeB = range(1, 10);\n var numberA = 10;\n var numberB = rangeB[Math.floor(Math.random() * rangeB.length)];\n\n var numberDiff = numberA - numberB;\n\n var plusEquation = [numberA, numberB, numberDiff];\n return plusEquation;\n}",
"function generateBotChoice () {\n return Math.floor(Math.random() * 3) + 1\n }",
"function threeRandomRules(){\n\trules = [\n\t\trandomRule(\"F\",{symbol:\"A\",forceInclude:true},{symbol:\"\",forceInclude:false},true),\n\t\trandomRule(\"A\",{symbol:\"B\",forceInclude:true},{symbol:\"\",forceInclude:false},true),\n\t\trandomRule(\"B\",{symbol:\"A\",forceInclude:false},{symbol:\"B\",forceInclude:false},true)\n\t]\n\tdisplayCurrents()\n}",
"function generateTwoCorrectSlotsOfThree() {\r\n currentBlock = blockValues[i];\r\n routeNumberOutofThree = randomNumber1Through3();\r\n incorrectSlotValue1 = randomNumberNeg9Through9();\r\n if (routeNumberOutofThree === 1) {\r\n firstCorrect = randomNumberNeg9Through9();\r\n while ((currentBlock + firstCorrect) < -9 || (currentBlock + firstCorrect) > 9) {\r\n firstCorrect = randomNumberNeg9Through9();\r\n }\r\n slotValues[j] = firstCorrect;\r\n document.getElementById(slotIds[j].toString()).textContent = slotValues[j];\r\n j++;\r\n secondCorrect = randomNumberNeg9Through9();\r\n while ((currentBlock+firstCorrect+secondCorrect) < 0 || (currentBlock+firstCorrect+secondCorrect) > 9) {\r\n secondCorrect = randomNumberNeg9Through9();\r\n }\r\n slotValues[j] = secondCorrect;\r\n document.getElementById(slotIds[j].toString()).textContent = slotValues[j];\r\n j++;\r\n nextBlock = currentBlock + firstCorrect +secondCorrect;\r\n slotValues[j] = incorrectSlotValue1;\r\n document.getElementById(slotIds[j].toString()).textContent = slotValues[j];\r\n j++;\r\n } else if (routeNumberOutofThree === 2) {\r\n firstCorrect = randomNumberNeg9Through9();\r\n while ((currentBlock + firstCorrect) < -9 || (currentBlock + firstCorrect) > 9) {\r\n firstCorrect = randomNumberNeg9Through9();\r\n }\r\n slotValues[j] = firstCorrect;\r\n document.getElementById(slotIds[j].toString()).textContent = slotValues[j];\r\n j++;\r\n slotValues[j] = incorrectSlotValue1;\r\n document.getElementById(slotIds[j].toString()).textContent = slotValues[j];\r\n j++;\r\n secondCorrect = randomNumberNeg9Through9();\r\n while ((currentBlock+firstCorrect+secondCorrect) < 0 || (currentBlock+firstCorrect+secondCorrect) > 9) {\r\n secondCorrect = randomNumberNeg9Through9();\r\n }\r\n slotValues[j] = secondCorrect;\r\n document.getElementById(slotIds[j].toString()).textContent = slotValues[j];\r\n j++;\r\n nextBlock = currentBlock + firstCorrect +secondCorrect;\r\n } else if (routeNumberOutofThree === 3) {\r\n slotValues[j] = incorrectSlotValue1;\r\n document.getElementById(slotIds[j].toString()).textContent = slotValues[j];\r\n j++;\r\n secondCorrect = randomNumberNeg9Through9();\r\n firstCorrect = randomNumberNeg9Through9();\r\n while ((currentBlock + firstCorrect) < -9 || (currentBlock + firstCorrect) > 9) {\r\n firstCorrect = randomNumberNeg9Through9();\r\n }\r\n slotValues[j] = firstCorrect;\r\n document.getElementById(slotIds[j].toString()).textContent = slotValues[j];\r\n j++;\r\n while ((currentBlock+firstCorrect+secondCorrect) < 0 || (currentBlock+firstCorrect+secondCorrect) > 9) {\r\n secondCorrect = randomNumberNeg9Through9();\r\n }\r\n slotValues[j] = secondCorrect;\r\n document.getElementById(slotIds[j].toString()).textContent = slotValues[j];\r\n j++;\r\n nextBlock = currentBlock + firstCorrect +secondCorrect;\r\n }\r\n}",
"function randomShape(){\n\treturn Math.floor(Math.random()*50);\n}",
"function createMinusLevelSix() {\n var rangeA = range(2, 19);\n var rangeB = range(1, 10);\n\n var numberDiff = -100; //initialize numberDiff,and make it less than 1.\n\n while (numberDiff < 1) {\n numberA = rangeA[Math.floor(Math.random() * rangeA.length)];\n numberB = rangeB[Math.floor(Math.random() * rangeB.length)];\n\n numberDiff = numberA - numberB;\n }\n\n var plusEquation = [numberA, numberB, numberDiff];\n return plusEquation;\n}",
"function createPlusLevelSix() {\n var rangeAB = range(1, 11);\n var numberA = rangeAB[Math.floor(Math.random() * rangeAB.length)];\n var numberB = rangeAB[Math.floor(Math.random() * rangeAB.length)];\n\n var numberSum = numberA + numberB;\n \n var plusEquation = [numberA, numberB, numberSum];\n return plusEquation;\n}",
"function getPazymiuVidurkis3(x1 = 0, x2 = 0, x3 = 0, x4 = 0, x5 = 0) {\n var vidurkis = (x1 + x2 + x3 + x4 + x5) / 5;\n return vidurkis;\n}",
"function crystals(min,max){return Math.floor(Math.random()*(max-min))+min;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Listen if the photographer's medias are sort(), if so then render() again the component | listenSort() {
document.getElementById("sortMedias").addEventListener('change', () => {
this.render();
this.listenNewLikes();
})
} | [
"static refreshList(sortBy = null) {\n if (typeof sortBy == \"string\") {\n Settings.current.sortBy = sortBy;\n }\n if (this.songListElement) {\n let sortFunc = (a, b) => { return 0; };\n try {\n switch (Settings.current.sortBy) {\n case \"title\":\n sortFunc = (a, b) => {\n if (a.details.title.toLowerCase() > b.details.title.toLowerCase()) {\n return 1;\n }\n if (a.details.title.toLowerCase() < b.details.title.toLowerCase()) {\n return -1;\n }\n return 0;\n };\n break;\n case \"length\":\n sortFunc = (a, b) => {\n if (typeof a.details.songLength == \"number\" && typeof b.details.songLength == \"number\" && a.details.songLength > b.details.songLength) {\n return 1;\n }\n if (typeof a.details.songLength == \"number\" && typeof b.details.songLength == \"number\" && a.details.songLength < b.details.songLength) {\n return -1;\n }\n return 0;\n };\n break;\n case \"artist\": // Fall-through\n default:\n sortFunc = (a, b) => {\n if (a.details.artist.toLowerCase() > b.details.artist.toLowerCase()) {\n return 1;\n }\n if (a.details.artist.toLowerCase() < b.details.artist.toLowerCase()) {\n return -1;\n }\n return 0;\n };\n break;\n }\n }\n catch (error) {\n }\n var _sort = function (a, b) {\n // Make order reversable\n return sortFunc(a, b);\n };\n SongManager.songList.sort(_sort);\n let nList = SongManager.songList;\n let opened = SongGroup.getAllGroupNames(false);\n opened = [...new Set(opened)];\n SongManager.songListElement.innerHTML = \"\";\n let noGrouping = false;\n // Group Songs\n if (typeof Settings.current.songGrouping == \"number\" && Settings.current.songGrouping > 0 && Settings.current.songGrouping <= 7) {\n let groups = {};\n let addToGroup = function (name, song, missingText = \"No group set\") {\n if (name == null || (typeof name == \"string\" && name.trim() == \"\")) {\n name = missingText;\n }\n if (groups.hasOwnProperty(name)) {\n groups[name].push(song);\n }\n else {\n groups[name] = [song];\n }\n };\n switch (Settings.current.songGrouping) {\n case 1:\n SongManager.songList.forEach(s => {\n addToGroup(s.details.artist, s, \"[No artist set]\");\n });\n break;\n case 2:\n SongManager.songList.forEach(s => {\n addToGroup(s.details.album, s, \"[No album set]\");\n });\n break;\n case 3:\n SongManager.songList.forEach(s => {\n addToGroup(s.details.source, s, \"[No source set]\");\n });\n break;\n case 4:\n SongManager.songList.forEach(s => {\n addToGroup(s.details.language, s, \"[No language set]\");\n });\n break;\n case 5:\n SongManager.songList.forEach(s => {\n addToGroup(s.details.genre, s, \"[No genre set]\");\n });\n break;\n case 6:\n SongManager.songList.forEach(s => {\n addToGroup(s.details.year, s, \"[No year set]\");\n });\n break;\n case 7:\n SongManager.songList.forEach(s => {\n addToGroup(s.details.customGroup, s, \"[No group set]\");\n });\n break;\n case 8:\n SongManager.songList.forEach(s => {\n addToGroup(s.details.artist[0].toUpperCase(), s, \"[No artist set]\");\n });\n break;\n case 9:\n SongManager.songList.forEach(s => {\n addToGroup(s.details.title[0].toUpperCase(), s, \"[No title set]\");\n });\n break;\n default:\n noGrouping = true;\n break;\n }\n if (noGrouping == false) {\n for (const key in groups) {\n if (groups.hasOwnProperty(key)) {\n const sg = new SongGroup(key);\n sg.songList = groups[key];\n if (opened.includes(sg.name)) {\n sg.collapsed = false;\n }\n else {\n sg.collapsed = true;\n }\n sg.refreshList();\n }\n }\n }\n }\n // Don't Group Songs\n else {\n noGrouping = true;\n }\n if (noGrouping == true) {\n for (let i = 0; i < nList.length; i++) {\n const song = nList[i];\n song.refreshElement();\n SongManager.songListElement.appendChild(song.element);\n }\n }\n SongManager.search();\n }\n else {\n console.error(\"No div element applied to SongManager.songListElement\", \"SongManager.songListElement is \" + typeof SongManager.songListElement);\n }\n Toxen.resetTray();\n }",
"render(){\n if(this.props.data.length > 0) { \n return (\n <div className=\"photo-container\">\n <h2>Results</h2>\n <ul>\n {this.props.data.map( obj => (\n <Photo key={obj.id} data={obj}/>\n ))} \n </ul>\n </div>\n )\n } else { \n return <NoResults loadState={this.props.loadState}/>\n }\n\n }",
"insertionSort() {\r\n // eslint-disable-next-line\r\n if (this.disabled == false) this.animate(sortingAlgos.insertionSort(this.state.array), this.state.animationSpeed);\r\n\r\n }",
"sortViewPressed() {\n\n LayoutAnimation.configureNext(CustomLayoutAnimation);\n\n this.setState({ sortViewVisible: true })\n\n }",
"function sortArtist() {\r\n document.querySelector('#artH').addEventListener('click', function (e) {\r\n const artist = paintings.sort((a, b) => {\r\n return a.LastName < b.LastName ? -1 : 1;\r\n })\r\n displayPaint(artist);\r\n })\r\n }",
"function photographersPage() {\n // RAZ of the tag's filters on logo's click\n const logo = document.getElementsByClassName(\"logo--photographer\")[0];\n logo.addEventListener(\"click\", function() {\n localStorage.removeItem(\"id\");\n }, true);\n // Redirect to home page, if there is no photographer's id in the local storage\n const id = localStorage.getStorage(\"id\");\n if (id === null) window.location.href = \"./index.html\";\n // Instanciate the pages renderer with the values\n const photographerPage = new PhotographersPage(getArraysJsonElement(photographers, \"id\", id)[0]);\n // Render the clickable tags list in the header\n photographerPage.renderPhotographerTags();\n // Render the header information\n photographerPage.renderHeaderInformation();\n // Render all the photographers's photos\n photographerPage.renderPhotographersCards(0);\n // Render the photographer's further information\n photographerPage.renderPhotographersFurtherInformations();\n // Prepare the contact modal\n photographerPage.initializeContactForm();\n // Prepare the photo modal\n photographerPage.initializePhotoLightboxModal();\n}",
"componentDidUpdate() {\n if (this.state.beforeSort) {\n this.sortCurrencies();\n }\n }",
"_renderTopRatedFilms() {\n this._topRatedFilmsComponent.resetList();\n render(this._filmsComponent.getElement(), this._topRatedFilmsComponent);\n this._topRatedFilmControllers = this._renderFilms(\n this._topRatedFilmsComponent,\n this._filmsModel.getTopRatedFilms()\n );\n }",
"function ajaxSortCollectionMedia (collectionId, media, onSuccess) {\n $.ajax({\n type: 'PATCH',\n url: URL_COLLECTION,\n data: {\n action: 'sort',\n collection_id: collectionId,\n media: media,\n _token: CSRF_TOKEN\n },\n success: onSuccess\n });\n }",
"function sort(type, page, sr) {\n var order = sessionStorage.getItem(\"order\").split(\",\");\n console.log(\"pre:\" + order);\n switch (type) {\n case 0:\n order.sort(SortByName);\n break;\n case 1:\n order.sort(SortByShowing);\n break;\n case 2:\n order.sort(SortByPopularity);\n break;\n default:\n break;\n }\n console.log(\"posle: \" + order);\n sessionStorage.setItem(\"order\", order.toString());\n showFilms(page, sr);\n}",
"_renderMostCommentedFilms() {\n this._mostCommentedFilmsComponent.resetList();\n render(this._filmsComponent.getElement(), this._mostCommentedFilmsComponent);\n this._mostCommentedFilmControllers = this._renderFilms(\n this._mostCommentedFilmsComponent,\n this._filmsModel.getMostCommentedFilms()\n );\n }",
"function sortFeeds() {\n feed_list.sort(function(x, y){\n return y.timestamp - x.timestamp;\n });\n if((image_loaded || status_loaded) && users_loaded) {\n displayFeeds();\n }\n}",
"function sortBy() {\n //DOM ELEMENTS\n let divCards = gridGallery.children;\n divCards = Array.prototype.slice.call(divCards);\n // CHECK VALUE\n switch (sortByBtn.value) {\n // IF VALUE IS DATE\n case \"date\":\n divCards.sort(function(a, b) {\n if (a.childNodes[0].date < b.childNodes[0].date) {\n return -1;\n } else {\n return 1;\n }\n });\n for (let i = 0; i < divCards.length; i++) {\n gridGallery.appendChild(divCards[i]);\n }\n break;\n // IF VALUE IS POPULARITY\n case \"popularity\":\n divCards.sort(function(a, b) {\n return b.childNodes[3].textContent - a.childNodes[3].textContent;\n });\n for (let i = 0; i < divCards.length; i++) {\n gridGallery.appendChild(divCards[i]);\n }\n break;\n // IF VALUE IS TITLE\n case \"title\":\n divCards.sort(function(a, b) {\n if (a.childNodes[1].textContent < b.childNodes[1].textContent) {\n return -1;\n } else {\n return 1;\n }\n });\n break;\n }\n // REMOVE ELEMENTS\n gridGallery.innerHTML = \"\";\n // ADD ELEMENTS FROM SWITCH CASE'S RESULT\n for (let i = 0; i < divCards.length; i++) {\n gridGallery.appendChild(divCards[i]);\n }\n}",
"UPDATE_SORT(store,sort){\n // only update sort store if different sort is selected\n // I noticed clicking on sort buttons multiple times was messing with sort so I added this extra check\n if (store.selectedSort !== sort){\n store.selectedSort = sort\n store.weatherData = sortArray(store.weatherData, store.selectedSort)\n } \n }",
"function sortCards() {\n let cards = Array.from(sensorCards.children);\n let sortedFragment = document.createDocumentFragment();\n\n cards.sort(sortFunction);\n\n cards.forEach(function(card) {\n sortedFragment.appendChild(card);\n });\n\n sensorCards.innerHTML = '';\n sensorCards.appendChild(sortedFragment);\n}",
"function sortAuthor() {\r\n closeBookDetailsIfVisible();\r\n removeCurrentSelection();\r\n $('.bookshelf').isotope({ sortBy : \"author\" });\r\n getCurrentSelection();\r\n AuthorSortIcon();\r\n currentSortType = AUTHOR_SORT_TYPE;\r\n return false;\r\n }",
"function watchReviewSort() {\r\n const routes = window.location.pathname.split('/');\r\n const gameid = parseInt(routes[routes.length - 1]);\r\n $('#sort-reviews-condition').one('input', (event) => {\r\n const $this = event.target;\r\n const SORT_CONDITION = $($this).val().toString();\r\n // @ts-ignore\r\n reviewsSortCondition = SORT_CONDITION;\r\n loadSingleGameContent(gameid);\r\n });\r\n $('#sort-reviews-order').one('input', (event) => {\r\n const $this = event.target;\r\n const SORT_ORDER = $($this).val().toString();\r\n // @ts-ignore\r\n reviewsSortOrder = SORT_ORDER;\r\n loadSingleGameContent(gameid);\r\n });\r\n}",
"sortedArticles() {\n let articles = []\n if (this.props.articleData.articles) {\n articles = this.props.articleData.articles\n }\n switch (this.state.sortType) {\n case 0:\n return [...articles].sort((a, b) => a.title > b.title)\n case 1:\n return [...articles].sort((a, b) => a.authors[0] > b.authors[0])\n case 2:\n return [...articles].sort((a, b) => a.conferences[0] > b.conferences[0])\n case 3:\n return [...articles].sort((a, b) => a.frequency < b.frequency)\n default:\n return []\n }\n }",
"function addImagesSortButtonHandler() {\r\n // Depricated for new settings\r\n /*\r\n var sort = getImagesSortType();\r\n \r\n //var $el = $(\".options-settings-images-sort-item\"); // Old Settings\r\n var $el = $(\".nav-settings-images-sort > li\"); // New Settings\r\n var $item = $el.filter(\"[data-sort=\" + sort + \"]\");\r\n \r\n //if ($item) $item.addClass(\"active\"); // Old Settings\r\n if(NAVI) NAVI.setTab($item);// New Settings\r\n \r\n if (sort == 0) { //gallery\r\n $(\"#options-settings-images-upload\").css('display', 'none');\r\n } else if (sort == 1) { //your uploads\r\n $(\"#options-settings-images-upload\").css('display', 'block');\r\n }\r\n\r\n $el.on(\"click\", function () {\r\n var $el = $(this);\r\n var val = parseInt($el.attr(\"data-sort\"));\r\n var currentSort = getImagesSortType();\r\n\r\n if (currentSort != val) {\r\n BRW_sendMessage({\r\n command: \"setImagesSortType\",\r\n val: val\r\n });\r\n } //if\r\n });\r\n */\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add new box at given position | function addBoxAtPosition(bed, bb, position) {
var box = moveTo(bb, position);
if (isEmpty(bed)) {
bed.boxes = [box];
}
else {
bed.boxes.push(box);
}
return bed;
} | [
"function PlaceBox()\n{\n\ttarget = Point.Add(boardPosition, FacingToDirectionPoint(facing));\n\tif (!inLevel.InBounds(target))\n\t{\n\t\tErrorOut(\"I can't place a box there!\");\n\t\treturn;\n\t}\n\t\n\tvar placement = inLevel.GetHeight(target);\n \tvar here = inLevel.GetHeight(boardPosition);\n \t\n \tif (!inLevel.GetObjectsAt(target) && !(placement > here)) {\n \t if (placement == here) {\n \t \tplacement ++;\n \t } else {\n \t \tPlaceStep();\n \t }\n \t\tDebug.Log(\"Target_X:\" + target.GetX() + \" Target_Y\" + placement + \" Target_Z\" + target.GetY());\n \t\tinLevel.SpawnBox(target.GetX(), target.GetY());\n \t\t//it can't be !inLevel.InBounds(target) because it ignores switch\n \t} else if (inLevel.GetObjectsAt(target)) {\n \t\tErrorOut(\"I can't place a box there!\");\n \t}\n}",
"grow()\n {\n let box = this.createSnakeBox();\n this.placeBoxAtEnd(box);\n this.boxes.push(box);\n }",
"function updatePosition() {\n\t \n\t\tbox.css({\n\t\t\t'width': ($(element).width() - 2) + 'px',\n\t\t\t'top': ($(element).position().top + $(element).height()) + 'px',\n\t\t\t'left': $(element).position().left +'px'\n\t\t});\n\t}",
"function addBox(lat1, lng1, lat2, lng2, color) {\n var loc1=new google.maps.LatLng(lat1, lng1)\n var loc2=new google.maps.LatLng(lat2, lng2)\n var rectangle = new google.maps.Rectangle({\n strokeColor: color,\n strokeOpacity: 0.7,\n strokeWeight: 1,\n fillColor: color,\n fillOpacity: 0.19,\n map: map,\n bounds: new google.maps.LatLngBounds(loc1, loc2)\n });\n var index = makeIndex(lat1, lng1, lat2, lng2)\n boxes[index] = rectangle\n}",
"function moveBox(box){\n\t\t\n\t\tif(box.clasName != 'em_box'){ //if selected box is not empty (if box has a number)\n\t\t\t\n\t\t\t//getEmptyNextBox method tried to get empty box that is next to it\n\t\t\tvar emptyBox = getEmptyNextBox(box);\n\t\t\t\n\t\t\tif(emptyBox){\n\t\t\t\t// Temporary data for an empty box\n\t\t\t\tvar temp = {style: box.style.cssText, id: box.id};\n\t\t\t\t\n\t\t\t\t// Exchanges id and style values for the empty boxs\n\t\t\t\tbox.style.cssText = emptyBox.style.cssText;\n\t\t\t\tbox.id = emptyBox.id;\n\t\t\t\temptyBox.style.cssText = temp.style;\n\t\t\t\temptyBox.id = temp.id;\n\t\t\t\t\n\t\t\t\tif(position == 1){\n\t\t\t\t\tcheckSequence(); //calls the method to check correct order\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t}",
"createRect(){\n let rect = Rect.createRect(this.activeColor);\n this.canvas.add(rect);\n this.notifyCanvasChange(rect.id, \"added\");\n }",
"function moveNodeForNew(node) {\n // when create new box dom, move pass to 150 right\n var first_sub_node_x = getFirstSubNodePosition(node).x;\n // move each node position\n // add paret node, then sub node change position\n // add sub node, then parent node do not change position\n $('g[data-object-id=\"'+node.parent_id+'\"]>use').each(function(index_g, element_g){\n var x = first_sub_node_x + index_g * 150;\n $(element_g).attr(\"x\", x);\n });\n $('g[data-object-id=\"'+node.parent_id+'\"]>text').each(function(index_g, element_g){\n var x = first_sub_node_x + index_g * 150;\n $(element_g).attr(\"x\", x+30);\n });\n $('g[data-object-id=\"'+node.parent_id+'\"]>line').each(function(index_g, element_g){\n var x = first_sub_node_x + index_g * 150;\n $(element_g).attr(\"x2\", x+50);\n });\n // moving px\n var px = 0;\n $('use[data-object-id=\"'+node.object_id+'\"]').parent().find('g').children('use').each(function(index_g, element_g){\n var x = parseInt($(element_g).attr(\"x\"));\n px = x - parseInt($(element_g).attr(\"x\"));\n $(element_g).attr(\"x\", x-75);\n });\n $('use[data-object-id=\"'+node.object_id+'\"]').parent().find('g').children('text').each(function(index_g, element_g){\n var x = parseInt($(element_g).attr(\"x\"));\n $(element_g).attr(\"x\", x-75);\n });\n $('use[data-object-id=\"'+node.object_id+'\"]').parent().find('g').children('line').each(function(index_g, element_g){\n var x1 = parseInt($(element_g).attr(\"x1\"));\n var x2 = parseInt($(element_g).attr(\"x2\"));\n $(element_g).attr(\"x1\", x1-75);\n $(element_g).attr(\"x2\", x2-75);\n });\n }",
"function updateBoxes(newFrame) {\n\t\tconsole.log(newFrame);\n\t\tclearCustomBoxes();\n\t\tframe = newFrame;\n\n\t\tupdateStandardBoxes(newFrame);\n\t\tvar boxesData = boxes.custom[frame];\n\t\tif (boxesData != null) {\t\t\t//creates custom boxes\n\t\t\tfor (var i = 0; i < boxesData.length; i++) {\n\t\t\t\tmakeCustomBox(boxesData[i]);\n\t\t\t}\n\t\t}\n\t}",
"function getNextBox(box){\n\t\t\t\tvar x = box.x;\n\t\t\t\tvar y = box.y;\n\t\t\t\tif(x == 8){\n\t\t\t\t\tx = 0;\n\t\t\t\t\ty++;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tx++;\n\t\t\t\t}\n\n\t\t\t\tif(y > 8){\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\treturn getBox(x,y);\n\t\t\t\t}\n\t\t\t}",
"function addLabelAndBox(name) {\n addLabel(name);\n addTextBox(name);\n}",
"function deleteBox() {\r\n\r\n var sO = CurStepObj;\r\n var len = sO.boxExprs.length;\r\n var pos = sO.focusBoxId; // delete pos\r\n\r\n // Remove box expression and attributes\r\n //\r\n sO.boxExprs.splice(pos, 1);\r\n sO.boxAttribs.splice(pos, 1);\r\n\r\n // change the input box and redraw\r\n //\r\n changeCWInputBox(sO.focusBoxId - 1, true); \r\n\r\n}",
"merge(box) {\n const x = Math.min(this.x, box.x);\n const y = Math.min(this.y, box.y);\n const width = Math.max(this.x + this.width, box.x + box.width) - x;\n const height = Math.max(this.y + this.height, box.y + box.height) - y;\n return new Box(x, y, width, height);\n }",
"function addSquare() {\n var square = document.createElement(\"div\");\n square.className = \"square\";\n square.style.left = parseInt(Math.random() * 650) + \"px\";// 0 ~ (700 -50)\n square.style.top = parseInt(Math.random() * 250) + \"px\";//0 ~ (300-50)\n square.style.backgroundColor = getRandomColor();\n square.onclick = squareClick;\n \n var squarearea = document.getElementById(\"squarearea\");\n squarearea.appendChild(square);\n }",
"function addMaskBox() {\r\n\r\n var sO = CurStepObj;\r\n var len = sO.boxExprs.length;\r\n var pos = sO.focusBoxId + 1; // append pos\r\n\r\n // Add an \"if\" expression by default\r\n //\r\n var expr = new ExprObj(false, ExprType.If, \"if\");\r\n sO.boxExprs.splice(pos, 0, expr);\r\n\r\n // Note: We use a dummy indentation of value 0. The correct indentation\r\n // will be set when we draw the code window below\r\n //\r\n sO.boxAttribs.splice(pos, 0, new BoxAttribs(0, CodeBoxId.Mask));\r\n\r\n changeCWInputBox(pos, true); // change the input box and redraw\r\n}",
"function tryAt(bed, place, newBox, oldBox) {\n\t //Get distance between midpoint of new and old box\n\t var sizeOldBox = getSize(oldBox);\n\t var sizeNewBox = getSize(newBox);\n\t var margin = getMargin(bed);\n\t var hdist = 0.5 * (sizeOldBox.x + sizeNewBox.x) + margin;\n\t var vdist = 0.5 * (sizeOldBox.y + sizeOldBox.y) + margin;\n\t var oldCenter = getCenter(oldBox);\n\n\t //Get position of midpoint for new box\n\t if (place == 'left') {\n\t\t var position = new THREE.Vector2(oldCenter.x - hdist, oldCenter.y);\n\t }\n\t else if (place == 'right') {\n\t\t var position = new THREE.Vector2(oldCenter.x + hdist, oldCenter.y);\n\t }\n\t else if (place == 'above') {\n\t\t var position = new THREE.Vector2(oldCenter.x, oldCenter.y + vdist);\n\t }\n\t else if (place == 'below') {\n\t\t var position = new THREE.Vector2(oldCenter.x, oldCenter.y - vdist);\n\t }\n\t else {\n\t\t return undefined;\n\t }\n\n\t //Check if new box can be placed at 'postion'\n\t if (canPlaceAt(bed, newBox, position)) {\n\t\t return position;\n\t }\n\t else {\n\t\t return undefined;\n\t }\n}",
"function createBoxes(amount) {\n for (let i = 0; i < amount; i += 1) {\n const newDiv = document.createElement('div');\n newDiv.style.height = `${30 + i * 10}px`;\n newDiv.style.width = `${30 + i * 10}px`;\n newDiv.style.backgroundColor = colorForBoxes();\n getBoxes.appendChild(newDiv);\n }\n}",
"function fillBox (box, content) {\n\n box.html(content);\n }",
"function moveBoxes() {\n var spaces = [1, -1, 19, 20, 21, -19, -20, -21];\n var randNewSpace = Math.floor(Math.random()*spaces.length);\n if(box.checked === true && box.id < 400 || box.id > 0){\n box.id = parseInt(box.id)+ parseInt(spaces[randNewSpace]);\n //console.log(parseInt(box.id) + parseInt(spaces[randNewSpace]));\n box.id = parseInt(box.id);\n }\n else if(box.checked === true && box.id > 400 || box.id < 0){\n box.checked = false;\n }\n }",
"function Boxes_container(direction)\n{\n\tthis.name = String.fromCharCode(nb_boxes++);\n\n\tthis.boxes = [];\n\tthis.direction = direction;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load img for img_name. Only one image can be loaded for a static object return false if load fails, else return true | load_sprite (img_name, sx, sy, sw, sh) {
if (cached_assets[img_name] == null) return false;
this._sprites['idle'] = [];
this._sprites['idle'][0] = cached_assets[img_name];
this._sx = sx || 0;
this._sy = sy || 0;
this._width = sw || cached_assets[img_name].width;
this._height = sh || cached_assets[img_name].height;
return true;
} | [
"is_image() {\n if (\n this.file_type == \"jpg\" ||\n this.file_type == \"png\" ||\n this.file_type == \"gif\"\n ) {\n return true;\n }\n return false;\n }",
"function imageisloaded(image) {\n if (image == null || ! image.complete()) {\n alert(\"image not loaded :(\");\n return false;\n }\n else {\n return true; \n }\n}",
"static isImageLoaded(img){// During the onload event, IE correctly identifies any images that\n// weren’t downloaded as not complete. Others should too. Gecko-based\n// browsers act like NS4 in that they report this incorrectly.\nif(!img.complete){return false;}// However, they do have two very useful properties: naturalWidth and\n// naturalHeight. These give the true size of the image. If it failed\n// to load, either of these should be zero.\nif(img.naturalWidth===0){return false;}// No other way of checking: assume it’s ok.\nreturn true;}",
"_computeHasImage(fields) {\n if (\n fields &&\n typeof fields.images !== typeof undefined &&\n typeof fields.images[0] !== typeof undefined &&\n typeof fields.images[0].src !== typeof undefined\n ) {\n return true;\n }\n return false;\n }",
"function hasImage(attId) {\n var yes;\n var url = getBaseUrl() + \"colorswatch/index/isdir/\";\n jQuery.ajax(url, {\n async: false,\n method: \"post\",\n data: {\n dir: attId,\n },\n success: function (data) {\n yes = JSON.parse(data).yes;\n },\n });\n return yes;\n}",
"function checkImages(){ //Check if the images are loaded.\n\n if(game.doneImages >= game.requiredImages){ //If the image loads, load the page to the DOM.\n\n init();\n }else{ //loop until the images are loaded.\n\n setTimeout(function(){\n checkImages();\n },1);\n\n }\n }",
"canLoad(url) {\n return !!(this.files.has(url) ||\n this.fallbackLoader && this.fallbackLoader.canLoad(url));\n }",
"load()\r\n {\r\n this.image = loadImage(this.imagePath);\r\n }",
"imageLoaded(){}",
"function isFullSizeImageLoaded() {\n var el = document.getElementById('lightBoxImage');\n return el && el.width && el.width >= MINIMUM_IMAGE_WIDTH;\n }",
"function load_planets_image() {\n planets_image.source = new Image();\n planets_image.source.src = 'assets/img/planets.png';\n planets_image.source.onload = function() {\n planets_image.loaded = true;\n };\n }",
"function load_image( href ) {\n\t\t\tvar image = new Image();\n\t\t\timage.onload = function() {\n\t\t\t\treveal( '<img src=\"' + image.src + '\">' );\n\t\t\t}\n\t\t\timage.src = href;\n\t\t}",
"function isItem(check, item) {\n return check.image == images[item];\n}",
"function getImg(name){\r\n\tlet myList = readFile(\"Members\", name);\r\n\tlet json = myList;\r\n\tfor(let i = 0; i < json.length; i++){\r\n\t\tif(!json[i].endsWith(\".txt\")){\r\n\t\t\treturn json[i];\r\n\t\t}\r\n\t}\r\n\treturn \"none\";\r\n}",
"function isValidImageKey(imageKey) {\n if (imageKey) {\n return true;\n }\n \n return false;\n}",
"function loadOrRestoreImage (row, data, displayIndex) {\n // Skip if it is a container-type VM\n if (data.vm.type === \"container\") {\n return;\n }\n\n var img = $('img', row);\n var url = img.attr(\"data-url\");\n\n if (Object.keys(lastImages).indexOf(url) > -1) {\n img.attr(\"src\", lastImages[url].data);\n lastImages[url].used = true;\n }\n\n var requestUrl = url + \"&base64=true\" + \"&\" + new Date().getTime();\n\n $.get(requestUrl)\n .done(function(response) {\n lastImages[url] = {\n data: response,\n used: true\n };\n\n img.attr(\"src\", response);\n })\n .fail(function( jqxhr, textStatus, error) {\n var err = textStatus + \", \" + error;\n console.warn( \"Request Failed: \" + err );\n });\n}",
"function checkImg() {\n if(props.image) {\n return (\n <figure>\n <img className=\"mb-5\" src={props.image} width=\"50%\" height=\"50%\" alt=\"Book cover\" />\n <br />\n </figure>\n ) \n }\n return null;\n }",
"function getCachedImage(path){\n\n\tif(!io.fileExistsSync(path)){\n\t\t// File does not exist so.. doenst really matter\n\t\treturn false;\n\t}else{\n\t\t// Should exist\n\t\treturn true;\n\t}\n}",
"load_animation (anim_name, img_names, pos_list, sw, sh, animation_length) {\n\t\tpos_list = pos_list || [];\n\t\tlet names_length = img_names.length, pos_length = pos_list.length;\n\t\tlet length = (names_length >= pos_length) ? names_length : pos_length;\n\t\tif (this._sprites[anim_name] == undefined)\n\t\t\tthis._sprites[anim_name] = [];\n\t\tfor (let i = this._sprites[anim_name].length; i < length; i++) {\n\t\t\tlet img_i = i, pos_i = i;\n\t\t\tif (i >= names_length) img_i = names_length - 1;\n\t\t\tif (i >= pos_length) pos_i = pos_length - 1;\n\n\n\t\t\tlet sx = pos_list[i] || 0;\n\t\t\tif (sx != 0) sx = sx[0];\n\t\t\tlet sy = pos_list[i] || 0;\n\t\t\tif (sy != 0) sy = sy[1];\n\t\t\tlet new_img = {\n\t\t\t\timg: cached_assets[img_names[img_i]],\n\t\t\t\tx: sx,\n\t\t\t\ty: sy\n\t\t\t};\n\t\t\tthis._sprites[anim_name].push(new_img);\n\t\t}\n\t\tthis._width = sw || cached_assets[img_names[0]].width;\n\t\tthis._height = sh || cached_assets[img_names[0]].height;\n\t\t// sprite change time in milliseconds\n\t\tthis._sprite_change_time = (animation_length/length)*1000;\n\t\treturn true;\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
set the mock account IDs to use for the test | setMockAccountIds (callback) {
if (this.dontIncludeErrorGroupId) {
this.apiRequestOptions.headers['X-CS-Mock-Error-Group-Id'] = "";
} else {
this.apiRequestOptions.headers['X-CS-Mock-Error-Group-Id'] = this.data.codeError.objectId;
}
/*
const codeErrorId = this.data.codeError.accountId;
const accountIds = [];
while (
accountIds.length === 0 ||
accountIds.includes(codeErrorId)
) {
for (let i = 0; i < 3; i++) {
accountIds[i] = this.codeErrorFactory.randomAccountId();
}
}
if (!this.dontIncludeCodeErrorAccountId) {
accountIds.splice(1, 0, this.data.codeError.accountId);
}
this.apiRequestOptions.headers['X-CS-Mock-Account-Ids'] = `${accountIds.join(",")}`;
*/
callback();
} | [
"async setAccountID() {\n const [responseAccountData, responseStatus] = await this.getAccountData(this.state.login, 'login');\n\n if (responseAccountData && responseAccountData.data.length > 0) {\n await this.setState({accountID: responseAccountData.data[0].id});\n }\n }",
"fillAccountsList () {\n this.accountListCallId++\n var callid = this.accountListCallId\n var txOrigin = this.el.querySelector('#txorigin')\n this.settings.getAccounts((err, accounts) => {\n if (this.accountListCallId > callid) return\n this.accountListCallId++\n if (err) { addTooltip(`Cannot get account list: ${err}`) }\n for (var loadedaddress in this.loadedAccounts) {\n if (accounts.indexOf(loadedaddress) === -1) {\n txOrigin.removeChild(txOrigin.querySelector('option[value=\"' + loadedaddress + '\"]'))\n delete this.loadedAccounts[loadedaddress]\n }\n }\n for (var i in accounts) {\n var address = accounts[i]\n if (!this.loadedAccounts[address]) {\n txOrigin.appendChild(yo`<option value=\"${address}\" >${address}</option>`)\n this.loadedAccounts[address] = 1\n }\n }\n txOrigin.setAttribute('value', accounts[0])\n })\n }",
"function setupTestAccounts() {\n\n const UNITTEST_ACCT_NAME = \"Enigmail Unit Test\";\n const Cc = Components.classes;\n const Ci = Components.interfaces;\n\n // sanity check\n let accountManager = Cc[\"@mozilla.org/messenger/account-manager;1\"].getService(Ci.nsIMsgAccountManager);\n\n\n function reportError() {\n return \"Your profile is not set up correctly for Enigmail Unit Tests\\n\" +\n \"Please ensure that your profile contains exactly one Account of type POP3.\\n\" +\n \"The account name must be set to '\" + UNITTEST_ACCT_NAME + \"'.\\n\" +\n \"Alternatively, you can simply delete all accounts except for the Local Folders\\n\";\n }\n\n function setIdentityData(ac, idNumber, idName, fullName, email, useEnigmail, keyId) {\n\n let id;\n\n if (ac.identities.length < idNumber - 1) throw \"error - cannot add Identity with gaps\";\n else if (ac.identities.length === idNumber - 1) {\n id = accountManager.createIdentity();\n ac.addIdentity(id);\n }\n else {\n id = ac.identities.queryElementAt(idNumber - 1, Ci.nsIMsgIdentity);\n }\n\n id.identityName = idName;\n id.fullName = fullName;\n id.email = email;\n id.composeHtml = true;\n id.setBoolAttribute(\"enablePgp\", useEnigmail);\n\n if (keyId) {\n id.setIntAttribute(\"pgpKeyMode\", 1);\n id.setCharAttribute(\"pgpkeyId\", keyId);\n }\n }\n\n function setupAccount(ac) {\n let is = ac.incomingServer;\n is.downloadOnBiff = false;\n is.doBiff = false;\n is.performingBiff = false;\n is.loginAtStartUp = false;\n\n setIdentityData(ac, 1, \"Enigmail Unit Test 1\", \"John Doe I.\", \"user1@enigmail-test.net\", true, \"ABCDEF0123456789\");\n setIdentityData(ac, 2, \"Enigmail Unit Test 2\", \"John Doe II.\", \"user2@enigmail-test.net\", true);\n setIdentityData(ac, 3, \"Enigmail Unit Test 3\", \"John Doe III.\", \"user3@enigmail-test.net\", false);\n setIdentityData(ac, 4, \"Enigmail Unit Test 4\", \"John Doe IV.\", \"user4@enigmail-test.net\", true);\n }\n\n for (let acct = 0; acct < accountManager.accounts.length; acct++) {\n let ac = accountManager.accounts.queryElementAt(acct, Ci.nsIMsgAccount);\n if (ac.incomingServer.type !== \"none\") {\n if (ac.incomingServer.type !== \"pop3\" || ac.incomingServer.prettyName !== UNITTEST_ACCT_NAME) {\n throw reportError();\n }\n }\n }\n\n let configured = 0;\n\n // try to configure existing account\n for (let acct = 0; acct < accountManager.accounts.length; acct++) {\n let ac = accountManager.accounts.queryElementAt(acct, Ci.nsIMsgAccount);\n if (ac.incomingServer.type !== \"none\") {\n setupAccount(ac);\n ++configured;\n }\n }\n\n // if no account existed, create new account\n if (configured === 0) {\n let ac = accountManager.createAccount();\n let is = accountManager.createIncomingServer(\"dummy\", \"localhost\", \"pop3\");\n is.prettyName = UNITTEST_ACCT_NAME;\n ac.incomingServer = is;\n setupAccount(ac);\n }\n}",
"function setUpStorageClient(err, credentials){\n if (err) return console.log(err);\n\n storageClient = new StorageManagementClient(credentials, subscriptionId);\n //getStorageAccountsLists();\n //getStorageKeyList();\n createStorageAccount();\n //getStorageKeyList();\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 setUserId(state){\n state.userId = Math.floor(Math.random()*100);\n}",
"async function set(trackIds) {\n const cacheId = uuid.generate();\n redis.sadd(`tracks:${cacheId}`, trackIds);\n redis.expireat(`tracks:${cacheId}`, parseInt(+new Date() / 1000) + 10);\n return cacheId;\n}",
"setToken (userId, token) {\n assert.array(listOfUuids, { required: true })\n assert.integer(ttl)\n\n return new Promise((resolve, reject) => {\n this[$].client.set(`upload-token::${userId}`, true, 'EX', 3600, (error, reply) => {\n if (error) return reject(error)\n })\n\n resolve()\n })\n }",
"function setUserID(){\n if(isNew){\n spCookie = getSpCookie(trackerCookieName);\n getLead(isNew, spCookie, appID);\n }\n }",
"function setAccount() {\n console.log('check setAccount ', cache);\n\n let topbar = document.querySelector('.topbar');\n\n loadingEnd(); // TODO: Check\n // console.log(this.responseText);\n\n const urlParams = new URLSearchParams(window.location.search);\n let id = urlParams.get('id');\n let user\n if (id == null) {\n user = cache['user'];\n } else {\n user = cache['other'];\n }\n\n // Load project\n startProjectLoading();\n if (user['project_id'] != 0) {\n loadProject(user['project_id'], function () {setProject(user)});\n } else {\n setProject(user);\n }\n\n // Setup user bio\n topbar.querySelector('.topbar__name').innerText = user.name;\n let phone = user.phone;\n phone = '+' + phone[0] + ' (' + phone.slice(1, 4) + ') ' + phone.slice(4, 7) + '-' + phone.slice(7);\n topbar.querySelector('.topbar__phone').innerText = phone;\n\n document.querySelector('.team__title').innerText = user.team;\n\n //setup.sh avatar\n if (user.avatar != null && user.avatar != undefined && user.avatar != '') {\n topbar.querySelector('.topbar__avatar').style.backgroundImage = \"url('\" + user.avatar + \"')\";\n }\n\n // Setup user type label\n switch (user['user_type']) {\n case 0: // User\n // pass\n break;\n\n case 1: // Host\n topbar.querySelector('.topbar__type').innerText = 'Moderator';\n break;\n\n case 2: // Admin\n topbar.querySelector('.topbar__type').innerText = 'Admin';\n break;\n }\n\n setCredits();\n}",
"changeCredentialsBeforeObtainingTokenForDevice(token) {\n let credentials = this.credentials.getCredentials();\n delete credentials.uuid;\n credentials.code = token.device_code;\n this.credentials.setCredentials(credentials);\n }",
"function setNumber() {\n\tsecretNumber = Math.ceil(Math.random() * 99);\n}",
"_init() {\n this._Entity = Account;\n this._identifier.init(Identifier.ENTITY_TYPE.TYPE_ACCOUNT, [ATTR_EMAIL, ATTR_USERNAME]);\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 createUsersForTestingInvites() {\n return userTaskHelper.createUserAndTeam().then(function (thisUser) {\n user = thisUser.user;\n // Create user that will receive the invites\n return userTaskHelper.createUserAndTeam(false, 'test2@test.com');\n })\n .then(function (thisUser) {\n return new Promise(function (resolve) {\n secondUser = thisUser.user;\n resolve();\n });\n });\n}",
"updatePendingInvites(userInvites){\n for(let i of userInvites){\n if(!this.session.settings.invites.hasOwnProperty(i)){\n this.session.settings.invites[i] = {}\n }\n }\n for (let i of Object.keys(this.session.settings.invites)){\n if(!userInvites.includes(i)){\n delete this.session.settings.invites[i];\n }\n }\n\n this.saveClientSettings(this.session.settings, this.session.privateKey);\n }",
"function assignIdsToQuestions() {\n for (let i = 0; i < questions.length; i++) {\n (questions[i]).id = '#dropdown' + (i+1);\n }\n}",
"function setCredits() {\n currentCredits = accruedCredits;\n showCredits(currentCredits, creditsRecorded);\n updateCombined(accruedCredits - lastCredits);\n lastCredits = accruedCredits;\n}",
"function setUpTests()\n {\n// var fullInteractionData = $.parseJSON(app.scorm.scormProcessGetValue('cmi.interactions.0.learner_response'));\n var fullInteractionData;\n if(app.scorm.scormProcessGetValue('cmi.suspend_data') !== ''){\n fullInteractionData = $.parseJSON(app.scorm.scormProcessGetValue('cmi.suspend_data'));\n }\n else if(app.scorm.scormProcessGetValue('cmi.interactions.0.learner_response') !== ''){\n fullInteractionData = $.parseJSON(app.scorm.scormProcessGetValue('cmi.interactions.0.learner_response'));\n }\n else{\n console.log('There is a problem with test submission.');\n }\n \n // Inject the CMI DB data into the questionBank on first load\n if (fullInteractionData) {\n $.each(fullInteractionData, function (index, value)\n {\n if (!app.questionBank[index]) {\n app.questionBank[index] = value;\n }\n }); \n }\n \n // Setup the current test's question bank\n if (!app.questionBank[testID]) {\n app.questionBank[testID] = [];\n }\n \n return fullInteractionData;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
tell the nodebalancer that I am here | function tell(){
stickyLoadBalancer.tellBalancer(balancer, own);
} | [
"markAlive()\n\t{\n\t\tif ( ! this.m_bAlive )\n\t\t{\n\t\t\tthis.m_bAlive = true;\n\t\t\tthis.emit( 'peer_alive' );\n\t\t}\n\t}",
"async function heartbeat(req, res) {\n debug('HEARTBEAT')\n const { ip } = req.params\n try {\n var response = await bots.heartbeat(ip)\n res.send(response)\n } catch (error) {\n console.log(error)\n res.sendStatus(500)\n }\n \n }",
"offline () {\n log.warn(`Replica \"${this}\" got offline`);\n this.isDown = true;\n this.pool.node.emit('replica', {\n eventType: 'mod',\n object: this\n });\n }",
"function status(req,res,next) {\n\n if ( req.url === \"/ping\" ) {\n res.end(\"ok\");\n } else {\n next();\n }\n }",
"enterExplicitDelegation(ctx) {\n\t}",
"function checkNeighbour() {\n sendToPid(CheckState.neighbour, ROOM, CHECK);\n Utility.log('Checking neighbour: ', CheckState.neighbour);\n }",
"function ping() {\n primus.clearTimeout('ping').write('primus::ping::'+ (+new Date));\n primus.emit('outgoing::ping');\n primus.timers.pong = setTimeout(pong, primus.options.pong);\n }",
"checkServerStatus(){\nreturn this.post(Config.API_URL + Constant.HEALTHCHECK_CHECKSERVERSTATUS);\n}",
"function announceResults() {\n socket.sockets.emit(\"gameOver\");\n}",
"function pingFromPlant(){\n\n}",
"function serverReachableHandler(e) {\n document.getElementById(\"errorDiv\").innerHTML = \"\";\n }",
"function ping() {\n rpc.tunnel.ping(function (err, _ts) {\n if (err) return console.error(err)\n clearTimeout(timer)\n timer = setTimeout(ping, 10e3)\n })\n }",
"exitExplicitDelegation(ctx) {\n\t}",
"function heartbeat() {\n for (var key in this._nodes) {\n var node = this._nodes[key];\n\n // ensure more` than a second has elapsed since the last send. this works\n // because this use of hrtime returns a tuple of [seconds, nanoseconds] and\n // if the seconds field is non-zero it will evaluate to true. also ensure\n // there's actually a node and that the node is connected\n if (process.hrtime(node.lastSend)[0] && node && node.stream) {\n heartbug(this.id, 'hearbeat to', key);\n // node.stream.conn.write('true\\r\\n');\n\n node.stream.send({ $masterless: { heartbeat: true } });\n }\n }\n}",
"function heartbeatCallback(heartbeatCtx) {\n console.log('heartbeatCallback called');\n if (heartbeatCtx.description !== statusDescription) {\n statusDescription = heartbeatCtx.description;\n }\n if (heartbeatCtx.startGameLabel !== startGameLabel) {\n startGameLabel = heartbeatCtx.startGameLabel;\n }\n }",
"function handle_alive(socket, data) {\n var sender_id = data['sender_id'];\n var in_connection_id = _get_from_conn_id(data);\n connection_id_to_socket[in_connection_id] = socket;\n socket_id_to_connection_id[socket.id] = in_connection_id;\n\n if (!(sender_id && sender_id.startsWith('[World'))) {\n // Worker has connected, check to see if the connection exists\n let agent_state = connection_id_to_agent_state[in_connection_id];\n if (agent_state === undefined) {\n // Worker is connecting for the first time, init state and forward alive\n _send_message(world_id, AGENT_ALIVE, data);\n let new_state = new LocalAgentState(in_connection_id);\n connection_id_to_agent_state[in_connection_id] = new_state;\n active_connections.add(in_connection_id)\n } else if (agent_state.conversation_id != data['conversation_id']) {\n // Agent is reconnecting, and needs to be updated in full\n let update_packet = agent_state.get_reconnect_packet();\n _send_message(in_connection_id, UPDATE_STATE, update_packet);\n }\n } else {\n world_id = in_connection_id;\n // Send alive packets to the world, but not from the world\n socket.send(\n JSON.stringify({ type: 'conn_success', content: 'Socket is open!' })\n );\n if (main_thread_timeout === null) {\n main_thread_timeout = setTimeout(main_thread, 50);\n }\n }\n}",
"function registerHit(node)\n{\n if (node.hit == undefined)\n {\n $.get(\"/hit/\" + node.name, {},\n function(count)\n {\n node.hitCount = count;\n });\n node.hit = true;\n }\n}",
"function checkServerIpAddressForRestart()\n\t{\n\t\tserverIpAddressDisplayString(function(addressString)\n\t\t{\n\t\t\t// If address string has changed, then display\n\t\t\t// the new address and restart servers.\n\t\t\tif (mIpAddressString != addressString)\n\t\t\t{\n\t\t\t\tmIpAddressString = addressString\n\t\t\t\tdisplayServerIpAddress()\n\t\t\t\tSERVER.restartServers()\n\t\t\t}\n\t\t})\n\t}",
"function hangUp(){\r\n socket.emit(\"end\", ID, self);\r\n fetch(\"/end\", {\r\n method: 'POST',\r\n headers: {\r\n 'Content-Type': 'application/json'\r\n },\r\n body: JSON.stringify({\r\n ID: ID\r\n })\r\n }).then(response => {\r\n response.redirected;\r\n window.location.href = response.url;\r\n });\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Database URL. Change this to restaurants.json file location on your server. | static get DATABASE_URL() {
const port = 3000 // Change this to your server port
return `http://localhost:${port}/data/restaurants.json`;
} | [
"static get DATABASE_URL() {\n return '/data/restaurants.json';\n }",
"static get DATABASE_GET_ALL_FAVORITES() {\r\n return `http://localhost:${DBHelper.PORT}/restaurants/?is_favorite=true`;\r\n }",
"static setDatabaseUrlOneFavorite(id, fav) {\r\n return `http://localhost:${DBHelper.PORT}/restaurants/${id}/?is_favorite=${fav}`;\r\n }",
"load() {\n let database = fs.readFileSync(__dirname + '/database.json', 'utf8');\n return JSON.parse(database);\n }",
"loadDatabase() {\n fs.readFile(this.databasePath, (error, data) => {\n if (error) {\n return console.error(\"Unable to load database.\")\n }\n this.database = JSON.parse(data)\n console.log(this.database)\n })\n }",
"static get DATABASE_SUBMIT_REVIEW() {\r\n return `http://localhost:${DBHelper.PORT}/reviews`;\r\n }",
"static urlForRestaurant(restaurant) {\r\n return (`./restaurant.html?id=${restaurant.id}`);\r\n }",
"function loadRestaurants() {\n\ttry {\n\t\tvar loadString = fs.readFileSync('saveData.json');\n\t\tconsole.log('Loading Restaurants');\n\t\treturn JSON.parse(loadString);\n\t}catch(error) {\n\t\treturn [];\n\t}\n}",
"static getFavoriteRestaurants() {\r\n return DBHelper.goGet(\r\n `${DBHelper.RESTAURANT_DB_URL}/?is_favorite=true`,\r\n \"❗💩 Error fetching favorite restaurants: \"\r\n );\r\n }",
"leerDb() {\n try {\n const informacion = fs.readFileSync(this.pathDb, {\n encoding: 'utf8'\n });\n const { historial } = JSON.parse(informacion);\n return this.historial = historial;\n }\n catch (e) {\n console.error(`Error al leer el archivo.`.red.bold);\n }\n }",
"static getAllRestaurants() {\r\n return DBHelper.goGet(\r\n DBHelper.RESTAURANT_DB_URL,\r\n \"❗💩 Error fetching all restaurants: \"\r\n );\r\n }",
"function saveRestaurant(jsonObj) {\n\tvar requests = loadRestaurants();\n\n\trequests.push(jsonObj);\n\tfs.writeFileSync('saveData.json', JSON.stringify(requests, undefined, 1));\n}",
"function getDatabase() {\n return new Database(config.database.uri);\n}",
"connectionString () {\n const { url, protocol = 'mongodb', host, port, database } = this.config\n\n if (url) {\n return url\n }\n\n return host && port\n ? `${protocol}://${host}:${port}/${database}`\n : `${protocol}://${host}/${database}`\n }",
"static fetchRestaurantByfavorite(callback) {\n // Fetch all restaurants\n let open = idb.open(\"restaurants\", 1);\n open.then((db) => {\n let tx = db.transaction('restaurants');\n let keyValStore = tx.objectStore('restaurants', 'readonly');\n let favoriteIndex = keyValStore.index('is_favorite');\n return favoriteIndex.getAll(\"true\");\n }).then((data, error) => {\n if (error) {\n callback(error, null);\n } else {\n callback(null, data);\n }\n }).catch((error) => {\n callback(error, null);\n });\n }",
"function loadJSON() {\n var client = new XMLHttpRequest();\n client.open(\"GET\", databasefilename, true);\n client.onreadystatechange = function () { //callback\n if (client.readyState === 4) {\n if (client.status === 200 || client.status === 0) {\n database_obj = JSON.parse(client.responseText);\n processInput();\n }\n }\n };\n client.send();\n }",
"function uploadLocalJsonCollectionToDB(client, dataBaseName, collectionName) {\n\t\t\n\t\t//////////////////////////// Read json by nodejs fs (start) ////////////////////\n\t\t// var jsonObject;\n\t\tfs.readFile('db/sportsDB.json', 'utf8', function (err, data) {\n\t\tif (err) {\n\t\t\tconsole.error(\"Unable to read the json file\");\n\t\t\tthrow err;\n\t\t}\n\t\tconsole.error(\"Read the local json successfully\");\n\t\tconst jsonObject = JSON.parse(data);\n\t\tconsole.log(jsonObject);\n\t\tcreateMultipleDocuments(client, dataBaseName, collectionName, [jsonObject]);\n\t\t});\n\t\t//////////////////////////// Read json by nodejs fs (end) //////////////////////\n\t}",
"async readDatabase() {\n const { resource: databaseDefinition } = await this.client\n .database(this.databaseId)\n .read()\n console.log(`Reading database:\\n${databaseDefinition.id}\\n`)\n }",
"static RESTAURANT_URL_BY_ID(id) {\r\n return DBHelper.RESTAURANT_URL+\"/\"+id;\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Grant permission to the connection. | grantPermission(hub, permission, connectionId, options) {
const operationOptions = coreHttp.operationOptionsToRequestOptionsBase(options || {});
return this.client.sendOperationRequest({ hub, permission, connectionId, options: operationOptions }, grantPermissionOperationSpec);
} | [
"mayGrant(newPermission, granteePermissions = []) {\n return this._mayGrantOrRevoke('mayGrant', newPermission, granteePermissions);\n }",
"[SET_PERMISSION] (state, permissions) {\n state.permissions = permissions\n }",
"mayGrant(permission, granteePermissions = []) {\n const newPermission = new RNPermission(permission);\n if (this.grantsAllowed() === 0 || !this.matchIdentifier(newPermission)) return false;\n\n // All other grantPrivileges must be covered by our grantPrivileges\n return this._areLesserPrivileges(newPermission, granteePermissions);\n }",
"function grantPermission(resType, resID, perm, access_list, granter) {\n list = typeof(access_list) == 'string' ? [] + access_list : access_list\n for (var i = 0; i < access_list.length; i++) { //iterate over each email address\n // console.log(\"access_list[i]: \", access_list[i])\n if(access_list[i].includes(\"@\")){ //if entity name contains '@', assume entity type is User\n insert_user.run(access_list[i], access_list[i])\n entID = get_user.get(access_list[i])?.UserID\n entType = \"UserEnt\"\n } else { //if entity name does not contain '@', assume entity type is Group\n insert_group.run(access_list[i], granter, \"None\") \n entID = find_group.get(access_list[i])?.GroupID\n entType = \"GroupEnt\"\n }\n\n insert_perms(entType, entID, resType, resID, perm)\n update_perms(entType, entID, resType, resID, perm)\n }\n}",
"async grant (tokens, channel, options = {}) {\n\t\tif (!(tokens instanceof Array)) {\n\t\t\ttokens = [tokens];\n\t\t}\n\t\ttokens = tokens.filter(token => typeof token === 'string' && token.length > 0);\n\t\tconst displayTokens = tokens.map(token => {\n\t\t\tconst len = token.length;\n\t\t\treturn `${token.slice(0, 6)}${'*'.repeat(len-12)}${token.slice(-6)}`;\n\t\t});\n\t\tif (this._requestSaysToBlockMessages(options)) {\n\t\t\t// we are blocking PubNub messages, for testing purposes\n\t\t\tthis._log(`Would have granted access for ${displayTokens} to ${channel}`, options);\n\t\t\treturn;\n\t\t}\n\t\telse {\n\t\t\tthis._log(`Granting access for ${displayTokens} to ${channel}`, options);\n\t\t}\n\n\t\treturn this._grantMultipleHelper(tokens, [channel], options);\n\n\t\t/*\n\t\treturn Promise.all(tokens.map(async token => {\n\t\t\tconst channels = [channel];\n\t\t\t//if (options.includePresence) {\n\t\t\t//\tchannels.push(`${channel}-pnpres`);\n\t\t\t//}\n\t\t\tawait this._grantMultipleHelper(token, channels, options);\n\t\t}));\n\t\t*/\n\t}",
"grantWriteAccess () {\n\n\t\t\tlet clientId = appConfig.auth[process.env.NODE_ENV === 'production' ? 'prod' : 'dev'],\n\t\t\t\turl = 'https://api.github.com/authorizations';\n\n\t\t\treturn transport.request(url)//, null, this.buildAuthHeader())\n\t\t\t.then(\n\t\t\t\tresponse => {\n\t\t\t\t\tlet openRedistApp = response.find(authedApp => authedApp.app.client_id === clientId);\n\n\t\t\t\t\tif (!openRedistApp) throw new Error('User is not currently authed.');\n\n\t\t\t\t\tif (openRedistApp.scopes.includes('public_repo')) {\n\t\t\t\t\t\treturn { userHasWriteAccess: true };\n\t\t\t\t\t} else {\n\t\t\t\t\t\turl = `https://api.github.com/authorizations/${ openRedistApp.id }`;\n\t\t\t\t\t\treturn transport.request(url, null, {\n\t\t\t\t\t\t\t...this.buildAuthHeader(),\n\t\t\t\t\t\t\tmethod: 'PATCH',\n\t\t\t\t\t\t\tbody: {\n\t\t\t\t\t\t\t\tadd_scopes: [ 'public_repo' ]\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t)\n\t\t\t.then(\n\t\t\t\tresponse => {\n\t\t\t\t\treturn { userHasWriteAccess: true };\n\t\t\t\t}\n\t\t\t)\n\t\t\t.catch(error => {\n\t\t\t\t// fail loudly if the application errors further down the promise chain.\n\t\t\t\tthis.handleError(error);\n\t\t\t\tthrow error;\n\t\t\t});\n\n\t\t}",
"updatePermissions() {\n this.permissions = this.codenvyAPI.getProject().getPermissions(this.workspaceId, this.projectName);\n }",
"async function setPublicResourceAccess(resource, access, options = internal_defaultFetchOptions) {\n return await setActorClassAccess(resource, access, getPublicAccess$2, setPublicResourceAccess$1, options);\n}",
"function set_permissions(abs_path) {\n var p = 0;\n $.each($('.popover .explorer-popover-perm-body input:checked'), function(idx, e) {\n p |= 1 << (+$(e).attr('data-bit'));\n });\n\n var permission_mask = p.toString(8);\n\n // PUT /webhdfs/v1/<path>?op=SETPERMISSION&permission=<permission>\n var url = '/webhdfs/v1' + encode_path(abs_path) +\n '?op=SETPERMISSION' + '&permission=' + permission_mask;\n\n $.ajax(url, { type: 'PUT'\n }).done(function(data) {\n browse_directory(current_directory);\n }).fail(network_error_handler(url))\n .always(function() {\n $('.explorer-perm-links').popover('destroy');\n });\n }",
"function askPermission(status) {\n if (!status.hasPermission) {\n permissions.requestPermissions(\n list,\n function(status) {\n if (!status.hasPermission) error();\n },\n error\n );\n }\n }",
"visitGrant_statement(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"_mayGrantOrRevoke(functionName, newPermission, granteePermissions = []) {\n const newPerms = _.flatten(this._unwindParameters(newPermission));\n const ourPerms = this.permissions();\n return _.every(newPerms, (newPerm) => {\n return _.some(ourPerms, (ourPerm) => ourPerm[functionName](newPerm, granteePermissions));\n });\n }",
"function attempt() {\r\n connections[id].attempts++;\r\n if (connections[id].attempts > retry) {\r\n connections[id].attempts = 0;\r\n connections[id].deny++;\r\n self.log(chalk.yellow(\"Access denied: too many attempts.\"));\r\n callback(\"Access denied: too many attempts.\", false);\r\n return;\r\n }\r\n if (connections[id].deny >= deny && unlockTime > 0) {\r\n setTimeout(function(){\r\n connections[id].deny = 0;\r\n }, unlockTime);\r\n connections[id].attempts = 0;\r\n self.log(chalk.yellow(\"Account locked out: too many login attempts.\"));\r\n callback(\"Account locked out: too many login attempts.\", false);\r\n return;\r\n }\r\n gather(function(user, pass){\r\n user = search(user, pass, users);\r\n if (user) {\r\n connections[id].attempts = 0;\r\n connections[id].deny = 0;\r\n callback(\"Successfully Authenticated.\", true);\r\n } else {\r\n state.pass = void 0;\r\n setTimeout(function(){\r\n if (connections[id].attempts <= retry) {\r\n self.log(\"Access denied.\");\r\n }\r\n attempt();\r\n }, retryTime);\r\n }\r\n });\r\n }",
"function set_permit () {\n if (unset_permit_timeout != null)\n clearTimeout(unset_permit_timeout);\n\n // Set the flag.\n current_mode = 'permit';\n\n // Set timeout to only permit for 1 minute at a time.\n unset_permit_timeout = setTimeout(\n () => {\n if (confirm('You are in whitelist permit mode. Continue in permit mode?')) {\n set_permit();\n } else {\n unset_permit();\n }\n },\n 1000 * 60\n );\n}",
"function updateGrantedPermissions(um, stream) {\n const audioTracksReceived\n = Boolean(stream) && stream.getAudioTracks().length > 0;\n const videoTracksReceived\n = Boolean(stream) && stream.getVideoTracks().length > 0;\n const grantedPermissions = {};\n\n if (um.indexOf('video') !== -1) {\n grantedPermissions.video = videoTracksReceived;\n }\n if (um.indexOf('audio') !== -1) {\n grantedPermissions.audio = audioTracksReceived;\n }\n\n eventEmitter.emit(RTCEvents.PERMISSIONS_CHANGED, grantedPermissions);\n}",
"function _initializePermissionGrants(){\n return new Promise(function(resolve, reject){\n user.initializePermissionGrants(function(err){\n if(err){ return reject(err); }\n resolve();\n });\n });\n}",
"addPermissionToRole (roleId, action, isAllowed = true) {\n assert.equal(typeof roleId, 'string', 'roleId must be string')\n assert.equal(typeof action, 'string', 'action must be string')\n assert.equal(typeof isAllowed, 'boolean', 'isAllowed must be boolean')\n return this._apiRequest(`/role/${roleId}/permission`, 'POST', {\n action: action,\n // TODO: dear api \"programmer\", what's a bool? hint: it's not something you smoke\n allowed: isAllowed ? 'yes' : 'no'\n })\n }",
"function addPerm(cb) { \n patchRsc('ictrlREST.json', ictrlA, function () {\n console.log('ACCESS to iControl REST API: ictrlUser');\n cb(); \n });\n}",
"static add(permission){\n\t\tlet kparams = {};\n\t\tkparams.permission = permission;\n\t\treturn new kaltura.RequestBuilder('permission', 'add', kparams);\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function to make sure Car section isn't partially entered | function carSection () {
if (entryCarYear === "" || entryCarMake === "" || entryCarModel === "") {
var errorDiv = document.createElement('div')
// errorDiv.innerText = 'Required field!'
var field = document.getElementById('car-field')
field.appendChild(errorDiv)
field.classList.add('input-invalid')
}
else if (entryCarYear !== "" && entryCarMake !== "" && entryCarModel !== "") {
var errorDiv = document.createElement('div')
// errorDiv.innerText = 'Required field!'
var field = document.getElementById('car-field')
field.appendChild(errorDiv)
field.classList.add('input-valid')
}
} | [
"function midCars() {\n\tif (carRental.midAvail() > 0) {\n\t\tcarRental.bookMid();\n\t} else alert(\"no cars available\");\n}",
"validateCarData(car) {\n let requiredetail = 'license model latLong miles make'.split(' ');\n\n for (let field of requiredetail) {\n if (!car[field]) {\n this.errors.push(new DataError(`invalid field in validatin ${field}`, car));\n }\n }\n return car;\n }",
"isUnparked(vehicle){\n if( vehicle == null || vehicle == undefined)\n throw new Error(\"Could not Unpark..Invalid Vehicle..\")\n else{ \n index=this.checkForParkingSlot(vehicle)\n delete this.parking[index[0]][index[1]]\n noOfVehicles--\n owner.checkSpaceAvailable(vehicle)\n return true\n }\n }",
"function econCars() {\n\tif (carRental.econAvail() > 0) {\n\t\tcarRental.bookEcon();\n\t} else alert(\"no cars available\");\n}",
"function checkPos(car){\n for(let i = 0; i < car.length; i++){\n if(car[i].position.y > maxH + carH){\n atBottom = true;\n carsPassed++;\n if(car[i].getSpeed() > 20){\n setMovement(car[i], - 10);\n } else {\n setMovement(car[i], mode);\n }\n }\n }\n}",
"checkSpaceAvailable(vehicle)\n {\n throw new Error(\"Unparked..\"+vehicle)\n }",
"function city_has_building(pcity,\n\t\t pimprove)\n{\n /* TODO: implement. */\n return false;\n}",
"function checkview(section){\r\n const sectionBound = section.getBoundingClientRect();\r\n if(sectionBound.top <= 50 &§ionBound.top + sectionBound.bottom >= 100 && sectionBound.bottom >= 100){\r\n return true;\r\n }else{\r\n return false;\r\n }\r\n\r\n}",
"checkPartecipants(){\n \n }",
"function luxCars() {\n\tif (carRental.luxAvail() > 0) {\n\t\tcarRental.bookLux();\n\t} else alert(\"no cars available\");\n}",
"function endPhaseConditions(){\r\n\r\n if (killerCountSetup == 0 || userKilled || totalFuel == userScore + computerScore || fuel == 0){\r\n return false;\r\n }\r\n else{\r\n return true;\r\n }\r\n}",
"valid(x, y, soft, superSoft) {\n if (x > this.bounds.left + roadSize && x < this.bounds.right - roadSize && y > this.bounds.top + roadSize && y < this.bounds.bottom - roadSize) {\n return false;\n }\n if (superSoft) {\n if (x < -vehicleHeight / 2 - roadSize || x > canvas.width + vehicleHeight / 2 + roadSize || y < offset - vehicleHeight / 2 - roadSize || y > canvas.height + vehicleHeight / 2 + roadSize) {\n return false;\n }\n }\n else if (soft) {\n if (x < this.bounds.left && (y < this.bounds.top || y > this.bounds.bottom) || x > this.bounds.right && (y < this.bounds.top || y > this.bounds.bottom)) {\n return false;\n }\n else if (x > this.bounds.left + roadSize && x < this.bounds.right - roadSize && (y < this.bounds.top || y > this.bounds.bottom) || y > this.bounds.top + roadSize && y < this.bounds.bottom - roadSize && (x < this.bounds.left || x > this.bounds.right)) {\n return false;\n }\n else if ((!env.junctions[0] && y < canvas.height / 2 && (x < this.bounds.left || x > this.bounds.right)) || !env.junctions[1] && y > canvas.height / 2 && (x < this.bounds.left || x > this.bounds.right) || !env.junctions[2] && x < canvas.width / 2 && (y < this.bounds.top || y > this.bounds.bottom) || !env.junctions[3] && x > canvas.width / 2 && (y < this.bounds.top || y > this.bounds.bottom)) {\n return false;\n }\n }\n else {\n if (x < this.bounds.left || x > this.bounds.right || y < this.bounds.top || y > this.bounds.bottom) {\n return false;\n }\n }\n return true;\n }",
"function checkPlate(plate) {\n var num = plate.slice(0, 4);\n var letters = plate.slice(4);\n var checkLetters = /^[A-Z]+$/i;\n // comprovem si la matricula és diferent a 7\n if (plate.length != 7) {\n return false;\n }\n //comprovem si es númeric\n if (isNaN(num)) {\n return false;\n }\n //test busca coincidencies dins el que se li passa.\n if (!checkLetters.test(letters)) {\n return false;\n }\n return true;\n}",
"function checkColision(){\n return obstacles.obstacles.some(obstacle => {\n if(obstacle.y + obstacle.height >= car.y && obstacle.y <= car.y + car.height){\n if(obstacle.x + obstacle.width >= car.x && obstacle.x <= car.x + car.width){\n console.log(\"colision\")\n return true;\n }\n }\n return false;\n });\n}",
"function checkCollisions() {\n\t// check lTraffic\n\tvar numObs = lTraffic.length;\n\tvar i = 0;\n\tfor (i = 0; i < numObs; i++){\n\t\tif (rectOverlap(userCar, lTraffic[i])) {\n\t\t\thandleCollision();\n\t\t}\n\t}\n\t// TODO check rTraffic\n\tnumObs = rTraffic.length;\n\tfor (i = 0; i < numObs; i++) {\n\t\tif (rectOverlap(userCar, rTraffic[i])) {\n\t\t\thandleCollision();\n\t\t}\n\t}\n\t// TODO check bottom peds\n\t// TODO check top peds\n}",
"function rentCar() {\n\tvar renterName = document.getElementById(\"rname\").value;\n\tvar carType = document.getElementById(\"carchoice\").value;\n\tif (renterName.length > 0) {\n\t\tif (carType === \"economy\") {\n\t\t\teconCars();\n\t\t\trentals.addRenter(renterName, carType);\n\t\t\tchooseCar();\n\t\t} else if (carType === \"midsize\") {\n\t\t\tmidCars();\n\t\t\trentals.addRenter(renterName, carType);\n\t\t\tchooseCar();\n\t\t} else if (carType === \"luxury\") {\n\t\t\tluxCars();\n\t\t\trentals.addRenter(renterName, carType);\n\t\t\tchooseCar();\n\t\t} else alert(\"Please choose a car type\");\n\t} else alert(\"Please enter your name\");\n}",
"validateOccupancy(){\n if(this.occupancy ==''|| this.occupancy < 0 || this.occupancy > 180){\n return \"Occupancy cannot be empty, should not be negative and should not be morethan 180\";\n }\n else{\n return this.occupancy;\n }\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}",
"canMakeStep() {\n const nextHeadPoint = this.snake.getNextStepHeadPoint();\n\n return !this.snake.isOnPoint(nextHeadPoint) &&\n nextHeadPoint.x < this.config.getColsCount() &&\n nextHeadPoint.y < this.config.getRowsCount() &&\n nextHeadPoint.x >= 0 &&\n nextHeadPoint.y >= 0;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set ticksPassed to a new value (required for game updates/corrections). | setTicksPassed(newTicksPassed) {
this.ticksPassed = newTicksPassed
} | [
"function updateShotClock () {\n\tvar printShotClockTime = '';\n\tif (CURRENT_SHOT_CLOCK_TIME === 0) {\n\t\tdocument.getElementById('buzzer').play();\n\t\tstopClock();\n\t}\n\tif (CURRENT_SHOT_CLOCK_TIME < SHOT_CLOCK_TIME_CUTOFF) {\n\t\t$('#shotclocktimer').css('color', 'red');\n\t}\n\tvar formattedShotClockTime = msToTime(CURRENT_SHOT_CLOCK_TIME);\n\tif (CURRENT_SHOT_CLOCK_TIME >= TIME_CUTOFF) {\n\t\t// Greater than TIME_CUTOFF\n\t\tprintShotClockTime = formattedShotClockTime[1] + ':' + formattedShotClockTime[2];\n\t} else {\n\t\t// Less than TIME_CUTOFF\n\t\tvar ms = formattedShotClockTime[3];\n\t\tms = ms / 100;\n\t\tprintShotClockTime = parseInt(formattedShotClockTime[2]) + '.' + ms;\n\t}\n\t$('#shotclocktimer').text(printShotClockTime);\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 }",
"set score(newScore) {\r\n score = newScore;\r\n _scoreChanged();\r\n }",
"function setCurrentTime() {\n\t\tvar total = player.currentTime;\n\t\tcurrentTimeElement.innerHTML = timeFormat(total);\n\t}",
"function _updateTimer(){\n _timeNow = Date.now();\n var $dt = (_timeNow-_timeThen);\n\n _delta = _delta + $dt; // accumulate delta time between trips, but not more than trip window\n _now = _now+_delta; // accumulate total time since start of timer\n _timeThen = _timeNow;\n\n // record the number of trip windows passed since last reset\n _passedTrips = Math.floor(_delta / _trip);\n\n // determine if timer tripped\n if(_delta > _trip){\n _isTripped = true;\n _timeNow = Date.now();\n // assign current value to the excess amount beyond tripping point,\n // reset the accumulation to whatever is less than the trip window\n _delta = _delta % _trip;\n _timeThen = Date.now();\n }\n }",
"set score(val) {\n this._score = val;\n console.log('score updated');\n emitter.emit(G.SCORE_UPDATED);\n }",
"function teamPointsUpdate(event, points){\n self.points = points;\n }",
"function updateTillPlayed()\n{\n setCookie('timePlayed', song.currentTime);\n}",
"function setTimestamp_() {\n const currentTime = formatTime_(sketchPlayer.sketch.getCurrentTime());\n const duration = formatTime_(sketchPlayer.sketch.videoDuration());\n $timestamp.text(currentTime + '/' + duration);\n\n // Clear any pending timer, since this function could either be called as the\n // result of an onSeekUpdate update event, or from a previous timer firing.\n clearTimeout(timestampUpdateTimer);\n timestampUpdateTimer = setTimeout(setTimestamp_, 500);\n}",
"function changeDelayBetweenSteps() {\n drawing.delay = stepDelaySlider.value;\n updateStepDelaySliderText(drawing.delay);\n}",
"updateScore(){\n this.score += 1;\n this.labelScore.text = this.score;\n }",
"function tick() {\n const canvas = canvasRef.current;\n if (!isPlayingRef.current || !canvas) {\n return;\n }\n const newPosition = (audioContext.currentTime - startTimeRef.current) * playbackRate;\n currentPositionRef.current = newPosition;\n if (newPosition > totalSecs) {\n // stop playing when reached the end or over\n stop();\n updateCanvas();\n return;\n }\n updateCanvas();\n requestAnimationFrame(tick);\n }",
"increasePoints(points) {\n\t\tthis.points += points;\n\t}",
"calculateTurnMeter() {\n this.turnMeter += this.tickRate;\n if (this.turnMeter >= 100) {\n this.turnMeter -= 100;\n this.isTurn = true;\n } \n }",
"function updateTotal(playerTotal, playerHand) {\n playerTotal = getTotal(playerHand);\n return playerTotal;\n}",
"reset () {\n this.total = this.seconds * 1000.0;\n this._remaining = this.total;\n this._clearInterval();\n this.tick();\n }",
"function decrementTries() {\n triesLeft --;\n triesMessage.textContent = triesLeft;\n}",
"function updateScore(elapsedTime){\r\n\t\tif(!myShip.getSpecs().hit && !myShip.getSpecs().invincible){\r\n\t\t\tvar oldCounter = Math.floor(updateScoreCounter);\r\n\t\t\tupdateScoreCounter += elapsedTime/1000;\r\n\t\t\tvar newCounter = Math.floor(updateScoreCounter);\r\n\r\n\t\t\tif(newCounter == oldCounter + 1){\r\n\t\t\t\taddToScore(10);\r\n\t\t\t}\r\n\t\t}\r\n\t}",
"function run() {\n iteration++;\n drawVerticals(l, W, H, ctx);\n totalCrossed += drawSticks(sticks, l, W, H, ctx);\n console.log(totalCrossed);\n var pi = 2 * iteration * sticks / totalCrossed;\n document.getElementById(\"consola\").innerHTML = \"Iteration: \" + iteration;\n document.getElementById(\"consola\").innerHTML +=\n \", Total: \" + iteration * sticks;\n document.getElementById(\"consola\").innerHTML += \", Hits: \" + totalCrossed;\n document.getElementById(\"consola\").innerHTML += \", pi: \" + pi.toFixed(4);\n document.getElementById(\"consola\").innerHTML +=\n \", error: \" + Math.abs((pi / Math.PI - 1) * 100).toFixed(2) + \"%\";\n console.log(\"pi: \" + 2 * iteration * sticks / totalCrossed);\n\n console.log(iteration);\n if (iteration == nTries) clearInterval(timer);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A constructor for defining new trucks | function Truck( options) {
this.state = options.state || "used";
this.wheelSize = options.wheelSize || "large";
this.color = options.color || "blue";
//NOT defined in prototype
this.drive = function() {
console.log("truck drive");
}
this.breakDown = function() {
console.log("truck breakdown");
}
} | [
"function TruckFactory() {}",
"function TruckFactory() {\n TruckFactory.prototype = new VehicleFactory();\n TruckFactory.vehicleClass = Truck;\n}",
"function Duck(){\n\tthis.speciesName = 'duck';\n}",
"function TruckersComponent(_truckerService) {\n this._truckerService = _truckerService;\n }",
"function Car(vehicletype,name,model,type){ //\nVehicle.call(this, vehicletype)\n if(typeof(vehicletype) == typeof(\"\")){\n this.vehicletype = vehicletype;\n }\n else{\n this.vehicletype = \"Car\";\n }\n if(typeof(name) == typeof(\"\")){\n this.name = name;\n }\n else{\n this.name = \"General\";\n }\n if(typeof(model) == typeof(\"\")){\n this.model = model;\n }\n else{\n this.model = \"GM\";\n }\n this.type = type;\n if(this.name === \"Porshe\" || this.name === \"Koenigsegg\"){\n this.numOfDoors = 2;\n }\n else{\n this.numOfDoors = 4;\n }\n this.speed = \"0 km/h\";\n this.drive = function(number){\n this.gear = number;\n if(this.name === \"Porshe\")\n this.speed = \"250 km/h\";\n if(this.name === \"MAN\")\n this.speed =\"77 km/h\";\n return this; \n }\n if(this.type === \"trailer\"){\n this.numOfWheels = 8;\n this.isSaloon = false;\n }\n else{\n this.numOfWheels = 4;\n this.isSaloon = true;\n }\n \n }",
"function Rockets (consuption) {\n this.consuption = consuption;\n this.fuel = 0;\n}",
"constructor() {\n this.name = \"yourself\"\n this.worn = []\n }",
"function createRandomVehicle() {\n const parkingLot = new HouseParkingLot({\n id: between(0, 10000),\n position: new Vector(between(-100, 100), between(-100, 100), between(-5, 5)),\n rotation: between(0, 360),\n interiorId: between(0, 17)\n });\n\n return new HouseVehicle({\n id: between(0, 10000),\n modelId: between(400, 610)\n\n }, parkingLot);\n }",
"constructor(name, weight, eyeColor){\n//Assigns it to this instance\n// this is the object that is instantiated (created) \nthis.name = name //assigns value to this specific instance of a gorilla\nthis.weight = weight\nthis.isAlive = true // a default can also be set\nthis.eyeColor = eyeColor\nthis.bananasEaten = 0\nconsole.log(('you built a gorilla'));\n\n}",
"constructor(pairs) {\n super(pairs, \"Plugboard\");\n }",
"constructor() {\n //const LATTICE_NUM = globalThis.latticeNum;\n const LATTICE_PORT = 31415;\n const LATTICE_URL = `https://sustain.cs.colostate.edu:${LATTICE_PORT}`;\n this.service = new SustainClient(LATTICE_URL, \"sustainServer\");\n this.modelService = new JsonProxyClient(LATTICE_URL, \"sustainServer\");\n return this;\n }",
"constructor(id, name, price, wheels, doors, hasAc, owner, academy) {\n super(id, name, price, wheels, doors, hasAc);\n // setting value in constructor to private field (not recomended to set value send from outside to private field)\n // if(academy) this.#academy = academy;\n this._owner = owner;\n }",
"function TpelletTile(){\n\tthis.pellet = new Tsphere();\n\tthis.tile = new Ttile();\n}",
"constructor(scene, slices, stacks)\n {\n super(scene);\n this.blWheel = new MyWheel(scene, slices, stacks);\n this.brWheel = new MyWheel(scene, slices, stacks);\n\n //Create Axis\n this.rAxis = new MyAxis(scene,slices,stacks);\n }",
"constructor(options = {}) {\n options.name = options.name || \"Tokyo Disney Resort - Magic Kingdom\";\n options.timezone = options.timezone || \"Asia/Tokyo\";\n\n // set park's location as it's entrance\n options.latitude = options.latitude || 35.634848;\n options.longitude = options.longitude || 139.879295;\n\n // Magic Kingdom Park ID\n options.park_id = options.park_id || \"tdl\";\n options.park_kind = options.park_kind || 1;\n\n // Geofence corners\n options.location_min = new GeoLocation({\n latitude: 35.63492433179704,\n longitude: 139.87755417823792\n });\n options.location_max = new GeoLocation({\n latitude: 35.63234322451754,\n longitude: 139.8831331729889\n });\n\n // inherit from base class\n super(options);\n }",
"function Motorcycle(make,model,year) {\n //using call\n Car.call(this,make,model,year)\n this.numWheels = 2;\n}",
"function Duck(name) {\n this.name = name;\n this.whatDoes = this._selectWhatDuckDoes(name);\n}",
"function TravelBox() {\n this.travelBoxPlaces = [];\n }",
"function newTank(data){\n\tlet spawnpoint = newSpawnpoint();\n\ttanks.push(new Tank(data[\"id\"], spawnpoint.x, spawnpoint.y, tankSettings[\"width\"], tankSettings[\"height\"], spawnpoint.angle, tankSettings[\"speed\"], tankSettings[\"acceleraton\"], data[\"color\"]));\n\tscoreboard.addPlayer(data[\"id\"], data[\"name\"], tankSettings[\"defaultElo\"], data[\"color\"]);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Resets the progress arrays after the given IDs to their original state: index 0 and section selected false. | function resetIndicesAfterIDs(iCourseID, iSectionID) {
for(var k = iSectionID + 1; k < aCurrentIndices[iCourseID].length; k++) {
aCurrentIndices[iCourseID][k][0] = 0;
aCurrentIndices[iCourseID][k][1] = false;
}
for(var j = iCourseID + 1; j < aCurrentIndices.length; j++) {
for(var k = 0; k < aCurrentIndices[j].length; k++) {
aCurrentIndices[j][k][0] = 0;
aCurrentIndices[j][k][1] = false;
}
}
} | [
"function clearOldSelectedDIVs() {\n if (Object.prototype.toString.call(selectedDIVs) === '[object Array]') {\n if (selectedDIVs.length < 1) return;\n selectedDIVs.forEach(function(_div) {\n $(_div).css('background-color', 'transparent');\n $(_div).css('opacity', 0.35);\n $(_div).css('border', 'none');\n });\n }\n\n\n}",
"function resetAfterSuddenIntervalStop(){\n for(i = 0; i < barAmount; i++){\n intsToSortArray[i].changeColor(\"#8083c9\");\n }\n updateCanvas();\n}",
"resetIndex() {\n this._offset = 0;\n }",
"reset() {\n\tthis.progress = new Progress(0);\n\tthis.question = [];\n\tthis.setChanged();\n\tthis.notifyObservers(this.progress);\n\tthis.clearChanged();\n }",
"function clearAllSelection(){\n ds.clearSelection();\n arrDisp.length=0;\n updateSelDisplay();\n updateCurrSelection('','','startIndex',0);\n updateCurrSelection('','','endIndex',0);\n}",
"function resetImages(arr) {\n arr.forEach((element) => {\n let temp = images.find((item) => {\n return item.id === element;\n });\n temp.clicked = false;\n });\n}",
"function clearSelectedPoints () {\n\tselectedPoints = [];\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 }",
"resetEverything() {\n this.resetLoader();\n this.remove(0, Infinity);\n }",
"resetOptions(){\r\n\t\t// reset all extras;\r\n\t\tconst $selects = $('.sm-box').find('select');\r\n\t\t$($selects).each((i, el) => {\r\n\t\t\tconst name = $(el).attr('id');\r\n\t\t\t$(`#${name}`).prop('selectedIndex', 0);\r\n\t\t\tthis.resetSheetValues(name);\r\n\t\t});\r\n\t}",
"function resetTour(){\n \n yourtourids = [];\n \n updateTour();\n resetDistance();\n \n }",
"resetSections() {\n $sectionWithBackLink?.detach();\n this.$currentSection.empty();\n currentSection = null;\n }",
"function setIndex(val) {\n index = val;\n for (let i = 0; i < num_bars; i++) {\n byId('myProgress_' + i).classList.remove(\"mystyle\");\n }\n byId('myProgress_' + index).classList.add(\"mystyle\");\n}",
"function resetSelectCorrPopup() {\n availableCorrList = [];\n traceObject(corrList);\n trace(\"-----------\");\n traceObject(usedCorrElementsIds);\n trace(\"-----------\");\n for (var i = 0; i < corrList.length; i++) {\n var corrItemIsUsed = usedCorrElementsIds.some(function (element, index) {\n return element === corrList[i].id;\n });\n if (!corrItemIsUsed) {\n availableCorrList.push(corrList[i]);\n }\n }\n traceObject(availableCorrList);\n trace(\"%%%%%%%%\");\n initSelectCorrPopupObjectsContainer(availableCorrList);\n}",
"function clearSelectedStates() {\n _scope.ugCustomSelect.selectedCells = [];\n }",
"function clearIndices() {\n\tglobal.indices = {};\n\tlet table = document.getElementById('indices-table');\n\t// Clear table\n\twhile (table.firstChild) {\n\t\ttable.removeChild(table.firstChild);\n\t}\n}",
"resetIndexes()\n {\n const self = this;\n self[_reducedIndexes] = null;\n self[_optimizedIndexes] = null;\n self[_naiveIndex] = null;\n self[_keyStatistics] = null;\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}",
"assignRegions(indices, callback = null) {\n const color = this.getColor();\n\n // Modifying the new data before setting it as the state\n let currentData = cloneDeep(this.state.scenarioData);\n let currentColorData = cloneDeep(this.state.colorData);\n let removedColors = [];\n let addedColor = false;\n\n indices.forEach(index => {\n const previousColor = currentData[this.state.activeEntry].regionDict[index].color;\n // Update for scenarioData the color of the region\n currentData[this.state.activeEntry].regionDict[index].color = color;\n\n // Only need to update if the previousColor is different from current color\n if (previousColor !== color) {\n // Deal with decrementing previous color's colorData entry, if any (no color means region not labelled/colored)\n if (previousColor) {\n currentColorData[this.state.activeEntry][previousColor] -= 1;\n if (currentColorData[this.state.activeEntry][previousColor] === 0) {\n // If the assigning took the count of regions of the color to 0, then remove it from the colorData\n delete currentColorData[this.state.activeEntry][previousColor];\n removedColors.push(previousColor);\n }\n }\n\n // Deal with incrementing or creating entry for added color's colorData entry, if the color is not null (i.e. in erase mode)\n if (color) {\n if (color in currentColorData[this.state.activeEntry]) {\n currentColorData[this.state.activeEntry][color] += 1;\n } else {\n currentColorData[this.state.activeEntry][color] = 1;\n addedColor = true;\n }\n }\n }\n });\n\n // Setting state, then do callback\n this.setState({ scenarioData: currentData, colorData: currentColorData },\n () => {\n this.mapRef.current.resetSpecifiedRegionStyle(indices);\n if (callback) {\n callback();\n }\n\n // Running plugin methods\n this.runPluginFunc(\"onAssignRegions\", [indices, color, removedColors, addedColor]);\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Show 9 hours within a work day. Each hour is displayed in a row. Each row contains an hour, a test array and a save button | function show_hours() {
// Print out nine Hours with appropriate formating classes
for (let hour = 9; hour < 18; hour++) {
var current_hour = d.getHours();
let hour_class;
if (hour < current_hour) {
hour_class = "past";
} else if (hour == current_hour) {
hour_class = "present";
} else {
hour_class = "future";
}
// Create the row elements and attached their hour values
$("#schedule").append(`<row class="row time-block" value=${hour}>
<div class="col-2 hour">${hour > 12 ? hour - 12 : hour}</div>
<textarea class="col-9 description ${hour_class}"></textarea>
<button class="col-1 saveBtn"><i class="fas fa-save"></i></button>
</row>`);
}
renderLineItems();
} | [
"function generateHours(index, hour) {\r\n\t\t\t\thour = hour < 10 ? \"0\" + hour : hour;\r\n\t\t\t\tvar timeArray = [];\r\n\t\t\t\ttimeArray.push(hour + \":\" + \"00\");\r\n\t\t\t\ttimeArray.push(hour + \":\" + \"15\");\r\n\t\t\t\ttimeArray.push(hour + \":\" + \"30\");\r\n\t\t\t\ttimeArray.push(hour + \":\" + \"45\");\r\n\t\t\t\t$.each(timeArray, generateTimeOption);\r\n\t\t\t}",
"function addRow(inputHour) {\n //determine if the row should be in the past, present, or future\n let presentState = determineTimeState(inputHour);\n \n //create row with components (hour display, text area, and button)\n let rowEl = $(\"<div class=\\\"time-block row \" + presentState + \"\\\"></div>\");\n \n //attach the components to the div\n let hourEl = createHourElement(inputHour);\n let textAreaEl = createTextAreaElement(inputHour);\n let buttonEl = createButtonElement(inputHour);\n\n $(rowEl).append(hourEl, textAreaEl, buttonEl);\n \n\n //attach the div row to the container\n $(\".container\").append(rowEl);\n}",
"function iterateRows() {\n var numHours = calendarEndHour - calendarStartHour;\n for (let i = 0; i <= numHours; i++) {\n makeRow(i);\n assignTime(i);\n }\n }",
"function timeOneDayOfWeek() {\n const hoursPerDay = 24;\n let time = [];\n let formattedTime;\n for (i = 0; i < hoursPerDay + 1; i++) { //fill in all of the hours\n formattedTime = (moment().subtract(i, \"hours\")).format(\"hA\"); //give the time in format X AM/PM\n fillTimes(); // fill blank time\n time.push(formattedTime); //add to beginning of array\n } //do this for all 24 hours\n\n return time.reverse();\n\n function fillTimes() {\n let index = 7\n while (index) {\n time.push({\n date: $scope.options.arrWeekDates[index - 1],\n time: formattedTime,\n hide: true\n });\n index--\n }\n }\n }",
"function getListOfHours(){\n for(var index = 8; index < 18 ; index++){ //fill in all of the hours\n if (index == 0) { // if index = 0 \n timeBlocksList.push((index + 12) + \"AM\"); // Add hour to timeBlocksList\n }\n else if (index < 12) { // if index < 12 \n timeBlocksList.push(index + \"AM\"); // Add hour to timeBlocksList\n }\n else if (index == 12) { // if index = 12 \n timeBlocksList.push(index + \"PM\"); // Add hour to timeBlocksList\n }\n else if (index > 12) { // if index > 12 \n timeBlocksList.push((index - 12) + \"PM\"); // Add hour to timeBlocksList\n }\n } \n }",
"function clickHour() {\n let oldSelected = document.querySelector(\".selectedHourTile\");\n if (oldSelected != null) {\n oldSelected.classList.remove(\"selectedHourTile\");\n }\n this.classList.add(\"selectedHourTile\");\n $(\"selectedHour\").textContent = this.textContent + \" \" + $(\"selectedAmpm\").textContent;\n \n // make load button visible\n $(\"loadContainer\").style.display = \"block\";\n\n // duration check \n // for now im too lazy to write a check, just going to reset to 1 every time\n // might be slightly annoying for user\n $(\"selectedDuration\").textContent = \"1 hour(s) long\";\n }",
"function updateHours()\n{\n let nowHours = new Date();\n let nowHoursString = \"\";\n\n if (nowHours.getHours() === 0 && militaryTime === 0) {\n hoursMath.innerHTML = `1 + 2 = 12`;\n hours.innerHTML = \"Hours\";\n ledFirst(hours11, hours12, hours14, hourOnLED, hourOffLED, 1);\n ledSecond(hours21, hours22, hours24, hours28, hourOnLED, hourOffLED, 2);\n }\n\n else if (nowHours.getHours() === 1) {\n hoursMath.innerHTML = `0 + ${nowHours.getHours()} = ${nowHours.getHours()}`;\n hours.innerHTML = \"Hour\";\n ledFirst(hours11, hours12, hours14, hourOnLED, hourOffLED, 0);\n ledSecond(hours21, hours22, hours24, hours28, hourOnLED, hourOffLED, nowHours.getHours()*1);\n }\n\n\n else if (nowHours.getHours() < 10 && nowHours.getHours() != 0 && nowHours.getHours() != 1) {\n hoursMath.innerHTML = `0 + ${nowHours.getHours()} = ${nowHours.getHours()}`;\n hours.innerHTML = \"Hours\";\n ledFirst(hours11, hours12, hours14, hourOnLED, hourOffLED, 0);\n ledSecond(hours21, hours22, hours24, hours28, hourOnLED, hourOffLED, nowHours.getHours()*1);\n }\n\n else if (nowHours.getHours() === 12) {\n hoursMath.innerHTML = `1 + 2 = 12`;\n hours.innerHTML = \"Hours\";\n ledFirst(hours11, hours12, hours14, hourOnLED, hourOffLED, 1);\n ledSecond(hours21, hours22, hours24, hours28, hourOnLED, hourOffLED, 2);\n }\n\n else if (nowHours.getHours() === 13 && militaryTime === 0) {\n hoursMath.innerHTML = `0 + 1 = 1`;\n hours.innerHTML = \"Hour\";\n ledFirst(hours11, hours12, hours14, hourOnLED, hourOffLED, 0);\n ledSecond(hours21, hours22, hours24, hours28, hourOnLED, hourOffLED, 1);\n }\n\n else if (nowHours.getHours() > 11 && nowHours.getHours() < 22 && militaryTime === 0) {\n nowHoursString = (nowHours.getHours()-12).toString();\n hoursMath.innerHTML = `0 + ${nowHoursString[0]} = ${nowHoursString[0]}`;\n hours.innerHTML = \"Hours\";\n ledFirst(hours11, hours12, hours14, hourOnLED, hourOffLED, 0);\n ledSecond(hours21, hours22, hours24, hours28, hourOnLED, hourOffLED, nowHoursString[0]*1);\n }\n\n else if (nowHours.getHours() <= 23 && nowHours.getHours() >= 22 && militaryTime === 0) {\n nowHoursString = (nowHours.getHours()-12).toString();\n hoursMath.innerHTML = `${nowHoursString[0]} + ${nowHoursString[1]} = ${nowHoursString}`;\n hours.innerHTML = \"Hours\";\n ledFirst(hours11, hours12, hours14, hourOnLED, hourOffLED, nowHoursString[0]*1);\n ledSecond(hours21, hours22, hours24, hours28, hourOnLED, hourOffLED, nowHoursString[1]*1);\n }\n \n else {\n nowHoursString = nowHours.getHours().toString();\n hoursMath.innerHTML = `${nowHoursString[0]} + ${nowHoursString[1]} = ${nowHoursString}`;\n hours.innerHTML = \"Hours\";\n ledFirst(hours11, hours12, hours14, hourOnLED, hourOffLED, nowHoursString[0]*1);\n ledSecond(hours21, hours22, hours24, hours28, hourOnLED, hourOffLED, nowHoursString[1]*1);\n }\n\n}",
"function createHourArr() {\n for (var i = 0; i < 9; i++) {\n var hour = moment().hour(i + 9).format(\"h a\");\n hourArr.push(hour);\n };\n}",
"createTimeLabelColumnArray() {\n\n let timeColumn = [];\n\n // We push an empty box first to account for the top left corner.\n timeColumn.push(this.createLabelSlot(\"\"));\n\n // Shows start at 8AM and on the latest days, shows end at 11PM.\n // hence i = 8 until i <= 23\n for (let i = 8; i <= 23; i++) { \n let label = \"\";\n if (i < 11) { // Before 11AM\n label = i + \"AM-\" + (i + 1) + \"AM\";\n } else if (i == 11) { // At 11AM\n label = i + \"AM-\" + (i + 1) + \"PM\";\n } else if (i == 12) { // At Noon\n label = i + \"PM-\" + (i + 1 - 12) + \"PM\";\n } else { // Any time after noon\n label = (i - 12) + \"PM-\" + (i + 1 - 12) + \"PM\";\n }\n timeColumn.push(this.createLabelSlot(label));\n }\n \n return timeColumn;\n }",
"function loadWorkScheduleScreen(){\n\tvar dayArray = ['mo','tu','we','th','fr','sa','su'];\n\t\n\t//Set the numbers and fill heights for the 7 days of the week\n\tfor(i=0;i<7;i++){\n\t\t$(\"#workScheduleHours-\" + dayArray[i])[0].innerHTML = U.profiles[Profile].workSchedule[dayArray[i]];\n\t\t$(\"#workScheduleDayFill-\" + dayArray[i])[0].style.height = (U.profiles[Profile].workSchedule[dayArray[i]] * 4.7) + \"%\";\n\t}\n\t//Initial set up shows Monday by default\n\t$(\"#workScheduleCurrentDay\")[0].innerHTML = \"Monday\";\n\t$(\"#workScheduleCurrentDayHoursInput\")[0].value = U.profiles[Profile].workSchedule.mo;\n\t$(\".errorDiv\").hide();\n}",
"function Hours() {\n this.hoursPerWeek = 40;\n // Can't make this easily configurable because workwork and liberty both\n // assume Monday to Friday to be working days and Saturday and Sunday to be\n // non-working days\n this.daysPerWeek = 5;\n this.regions = null;\n this.vacationDaysTotal = 0;\n this.vacationDays = [];\n this.estimatedSickDaysTotal = 0;\n this.sickDays = [];\n\n // TODO setting hoursWorked as a simple number is in contrast to vacation days\n // and sick days for which we add the actual, individual days and can\n // calculate the number of vacation days/sick days depending on the date.\n // To have the same for hours/days worked we would need to add the worked\n // hours for each day individually. Maybe allow both?\n this.hoursWorked = 0;\n}",
"function getHoursFromTemplate(){var hours=parseInt(scope.hours,10);var valid=scope.showMeridian?hours>0&&hours<13:hours>=0&&hours<24;if(!valid){return undefined;}if(scope.showMeridian){if(hours===12){hours=0;}if(scope.meridian===meridians[1]){hours=hours+12;}}return hours;}",
"function renderDayAndWeekCosts(date) {\r\n // Check if cost/hour information exists for particular day (If not it's all 0)\r\n if (!hoursAndCosts['day_hours_costs'].hasOwnProperty(date)) {\r\n _resetDayCosts(date);\r\n } else {\r\n // Display day hours and cost\r\n var dayCosts = hoursAndCosts['day_hours_costs'][date];\r\n for (var department in dayCosts) {\r\n if (!dayCosts.hasOwnProperty(department)) {\r\n continue;\r\n }\r\n var $depRow = $dayCostTable.find(\"tr[data-dep-id=\"+department+\"]\");\r\n var $depHours = $depRow.find(\"td[data-col=hours]\");\r\n var $depOvertime = $depRow.find(\"td[data-col=overtime]\");\r\n var $depCost = $depRow.find(\"td[data-col=cost]\");\r\n\r\n $depHours.text(dayCosts[department]['hours']);\r\n $depOvertime.text(dayCosts[department]['overtime_hours']);\r\n commaCost = numberWithCommas(Math.round(dayCosts[department]['cost']));\r\n $depCost.text(\"$\" + commaCost);\r\n }\r\n }\r\n // Find what workweek the day clicked belongs to\r\n var weekCosts = {};\r\n var weekDuration = {};\r\n var allWorkweekCosts = hoursAndCosts['workweek_hours_costs'];\r\n for (var i=0; i < allWorkweekCosts.length; i++) {\r\n var weekStart = allWorkweekCosts[i]['date_range']['start'];\r\n var weekEnd = allWorkweekCosts[i]['date_range']['end'];\r\n if (moment(date).isSameOrAfter(weekStart) && moment(date).isSameOrBefore(weekEnd)) {\r\n weekCosts = allWorkweekCosts[i]['hours_cost'];\r\n weekDuration = allWorkweekCosts[i]['date_range'];\r\n break;\r\n }\r\n }\r\n // Display week hours and cost\r\n for (var department in weekCosts) {\r\n if (!weekCosts.hasOwnProperty(department)) {\r\n continue;\r\n }\r\n var $depRow = $weekCostTable.find(\"tr[data-dep-id=\"+department+\"]\");\r\n var $depHours = $depRow.find(\"td[data-col=hours]\");\r\n var $depOvertime = $depRow.find(\"td[data-col=overtime]\");\r\n var $depCost = $depRow.find(\"td[data-col=cost]\");\r\n\r\n $depHours.text(weekCosts[department]['hours']);\r\n $depOvertime.text(weekCosts[department]['overtime_hours']);\r\n commaCost = numberWithCommas(Math.round(weekCosts[department]['cost']));\r\n $depCost.text(\"$\" + commaCost);\r\n }\r\n // Render day and week titles\r\n var dayTitle = moment(date).format(\"dddd, MMMM Do\");\r\n var weekStart = moment(weekDuration['start']).format(\"MMMM Do\");\r\n var weekEnd = moment(weekDuration['end']).format(\"MMMM Do\");\r\n\r\n $dayCostTitle.text(dayTitle);\r\n $weekCostTitle.text(weekStart + \" - \" + weekEnd);\r\n }",
"function validateHour() {\n $(\".form-control\").each(function (index) {\n const hourTimeBlock = $(this).attr(\"aria-label\");\n const dateTimeBlock = moment(hourTimeBlock, \"ha\");\n const description = localStorage.getItem(hourTimeBlock);\n\n $(this).val(description);\n\n if (!currentDay.isBefore(dateTimeBlock, \"hour\")) {\n if (currentDay.isSame(dateTimeBlock, \"hour\")) {\n $(this).addClass(\"present\");\n } else {\n $(this).addClass(\"past\");\n }\n } else if (!currentDay.isAfter(dateTimeBlock, \"hour\")) {\n $(this).addClass(\"future\");\n }\n });\n}",
"displayHourSelection(e) {\n e.preventDefault();\n\n let options = [];\n for (let i = 1; i <= 12; i++) {\n let className = \"\";\n if (i === StateManager.GetFeedRecorderData().SelectedHour) className = \"selected\";\n options.push(\n <button\n key={\"hour-\" + i}\n className={FormatCssClass(className)}\n onClick={this.changeHourSelection}\n >{i}</button>\n )\n }\n\n let modalContent = (\n <div className={FormatCssClass(\"options-hour\")}>\n {options}\n </div>\n );\n\n StateManager.UpdateValue(\n \"UI.SelectedModalData\",\n {\n AllowDismiss: true,\n Content: modalContent\n }\n );\n\n }",
"function displayTime(hours,miutes,seconds,milliseconds){\n\t\tdocument.getElementById(\"timerBoard\").innerHTML = padZero(hours,2)+\":\"+padZero(minutes,2)+\":\"+padZero(seconds,2)+\":\"+padZero(milliseconds,3);\n\t}",
"function generateElements(){\n // Generate as many as needed.\n for (i = 0; i < MAX_TIMESLOTS; i++){\n // The timeblock div.\n var timeslot = document.createElement(\"div\");\n timeslot.classList.add(\"time-block\");\n\n // The row div.\n var row = document.createElement(\"div\");\n row.classList.add(\"row\");\n\n // The hour span.\n var hour = document.createElement(\"span\");\n hour.classList.add(\"hour\");\n\n // The text area.\n var textArea = document.createElement(\"textarea\");\n textArea.classList.add(\"textarea\");\n\n // The save buttons.\n var saveBtn = document.createElement(\"button\");\n saveBtn.classList.add(\"saveBtn\");\n saveBtn.textContent = \"Save\";\n\n // Get the container for all of the timeblocks.\n var container = document.getElementsByClassName(\"container\");\n // Append the timeslots on to the container.\n container[0].appendChild(timeslot);\n // Append the row onto the timeslot.\n timeslot.appendChild(row);\n // Append the hour onto the row.\n row.appendChild(hour);\n // Append the textArea onto the row.\n row.appendChild(textArea);\n // Append the saveBtn onto the row.\n row.appendChild(saveBtn);\n }\n}",
"function createHoursElement(hours, collapsibleHours) {\n var collapsibleHoursHeader = $(\"<div>\").addClass(\"collapsible-header waves-effect waves-yellow\").html(\"Hours\")\n var hoursListItem = $(\"<li>\")\n if (hours.length > 1) {\n var colHeaderIcon = $(\"<i>\").addClass(\"material-icons\").html('expand_more')\n collapsibleHoursHeader.prepend(colHeaderIcon)\n var collapsibleHoursBody = $(\"<div>\").addClass(\"collapsible-body\")\n var hoursList = $(\"<ul>\").addClass(\"collection listHours\")\n for (j = 0; j < hours.length; j++) {\n var collDay = $(\"<li>\").addClass(\"collection-item\").text(hours[j])\n hoursList.append(collDay)\n }\n collapsibleHoursBody.append(hoursList)\n hoursListItem.append(collapsibleHoursHeader).append(collapsibleHoursBody)\n collapsibleHours.append(hoursListItem)\n collapsibleHours.collapsible();\n }\n else {\n collapsibleHoursHeader.html(\"Hours: \" + hours[0].capitalize())\n collapsibleHours.append(collapsibleHoursHeader)\n }\n}",
"function generateTimeTable() {\n const table = document.getElementById(\"tblTimetable\"),\n daysTimes = document.getElementById(\"daysTimesDiv\").dataset,\n days = (\", \" + daysTimes.days).split(\", \"),\n timeRange = daysTimes.times.split(\", \")\n generateTimeTableHead(table, days)\n generateTimeTableBody(table, days, timeRange)\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method is used to return the first 4 bytes of the packet as a string which should be JOIN, MOVE, or CHAT | getNextPacketType(){
if(this.buffer.length < 4)return null;
return this.buffer.slice(0,4).toString();
} | [
"function ipV4OctetString() {\n return operator_1.chain(string_1.stringToNaturalNumber(), number_1.ltEq(255), (_name, octet) => {\n return octet.toString();\n });\n}",
"function LeftAlt(unicode) {\n var packet = asHIDPacket(4, 0) + asHIDPacket(4, 98) + asHIDPacket(4, 0);\n\n unicode.toString().split(\"\").forEach(digit => {\n packet += asHIDPacket(4, [98, 89, 90, 91, 92, 93, 94, 95, 96, 97][parseInt(digit)]) + asHIDPacket(4, 0);\n });\n packet += asHIDPacket(0, 0);\n\n return packet;\n}",
"static bytes4(v) { return b(v, 4); }",
"static bytes6(v) { return b(v, 6); }",
"function nextCommand() {\n\t\t\tvar command = header.readByte();\n\n\t\t\t// Short waits\n\t\t\tif((command & 0xF0) == 0x70) {\n\t\t\t\treturn (command & 0x0F);\n\t\t\t}\n\n\t\t\t// Everything else\n\t\t\tswitch(command) {\n\t\t\t\tcase 0x4f:\t// GameGear PSG stereo register\n\t\t\t\t\theader.skipByte();\n\t\t\t\t\treturn 0;\n\t\t\t\tcase 0x50:\t// PSG\n\t\t\t\t\tpsg.write(header.readByte());\n\t\t\t\t\treturn 0;\n\t\t\t\tcase 0x51:\t// YM2413\n\t\t\t\t\theader.skipShort();\n\t\t\t\t\treturn 0;\n\t\t\t\tcase 0x52:\t// YM2612 port 0\n\t\t\t\t\theader.skipShort();\n\t\t\t\t\treturn 0;\n\t\t\t\tcase 0x53:\t// YM2612 port 1\n\t\t\t\t\theader.skipShort();\n\t\t\t\t\treturn 0;\n\t\t\t\tcase 0x54:\t// YM2151\n\t\t\t\t\theader.skipShort();\n\t\t\t\t\treturn 0;\n\t\t\t\tcase 0x61:\t// Wait a number of samples\n\t\t\t\t\treturn header.readShort();\n\t\t\t\tcase 0x62:\t// Wait one frame (NTSC - 1/60th of a second)\n\t\t\t\t\treturn 735;\n\t\t\t\tcase 0x63:\t// Wait one frame (PAL - 1/50th of a second)\n\t\t\t\t\treturn 882;\n\t\t\t\tcase 0x66:\t// END\n\t\t\t\t\tif(settings.loop_samples > 0) {\n\t\t\t\t\t\theader.seek(settings.loop_offset);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tisPlaying = false;\n\t\t\t\t\t}\n\t\t\t\t\treturn 0;\n\t\t\t\tcase 0xe0: // Seek\n\t\t\t\t\theader.skipLong();\n\t\t\t\t\treturn 0;\n\t\t\t\tdefault:\n\t\t\t\t\tif((command > 0x30) && (command <= 0x4e)) {\n\t\t\t\t\t\theader.skipByte();\n\t\t\t\t\t} else if((command > 0x55) && (command <= 0x5f)) {\n\t\t\t\t\t\theader.skipShort();\n\t\t\t\t\t} else if((command > 0xa0) && (command <= 0xbf)) {\n\t\t\t\t\t\theader.skipShort();\n\t\t\t\t\t} else if((command > 0xc0) && (command <= 0xdf)) {\n\t\t\t\t\t\theader.skipByte();\n\t\t\t\t\t\theader.skipShort();\n\t\t\t\t\t} else if((command > 0xe1) && (command <= 0xff)) {\n\t\t\t\t\t\theader.skipLong();\n\t\t\t\t\t}\n\t\t\t\t\treturn 0;\n\t\t\t}\n\t\t}",
"function ipV6SegmentString() {\n return operator_1.chain(string_1.varChar(1, 4), string_1.hexadecimalString(), (_name, str) => {\n if (/^0+$/.test(str)) {\n return \"0\";\n }\n return str.toLowerCase()\n .replace(/^0+/, \"\");\n });\n}",
"msg_type_str(id) {\n const text = Nano.EnumMsgtype[id];\n if (text) {\n return '<small>0x' + this.dec2hex(id) + ' - ' + text.toLowerCase() + '</small>';\n }\n else {\n return \"unknown\";\n }\n }",
"function encode_packet( packet ) {\n var encoded = to_bytes( packet.id );\n encoded += String.fromCodePoint( packet.flags ).toBytes();\n encoded += String.fromCodePoint( packet.codes ).toBytes();\n encoded += to_bytes( packet.qd ); // Questions\n encoded += to_bytes( packet.answers.length ); // Answers\n encoded += to_bytes( packet.authority.length ); // Authority\n encoded += to_bytes( packet.additional.length ); // Additional\n encoded += encode_question(packet);\n packet.answers.forEach( function(answer) {\n encoded += gen_resource_record(packet, answer.name, answer.type, answer.class, answer.ttl, answer.rdata);\n });\n packet.authority.forEach( function(rec) {\n encoded += gen_resource_record(packet, rec.name, rec.type, rec.class, rec.ttl, rec.rdata);\n });\n packet.additional.forEach( function(rec) {\n encoded += gen_resource_record(packet, rec.name, rec.type, rec.class, rec.ttl, rec.rdata);\n });\n return encoded;\n}",
"function serialize(robot_command) {\n var num_packet = 10;\n var buffer = new ArrayBuffer(num_packet);\n var uint8View = new Uint8Array(buffer);\n\n var binarized_command = new Object();\n binarized_command = scalingToBinary(robot_command);\n\n uint8View[0] = 0xFF;\n uint8View[1] = 0xC3;\n\n uint8View[2] = binarized_command.id;\n\n uint8View[3] = binarized_command.vel_norm;\n uint8View[4] = binarized_command.vel_theta;\n uint8View[5] = binarized_command.omega;\n\n uint8View[6] = 0x00;\n if (binarized_command.dribble_power > 0) {\n uint8View[6] |= 0x80;\n }\n uint8View[6] = 0x20;\n if (binarized_command.kick_power > 0) {\n uint8View[6] |= 0x10;\n }\n if (binarized_command.kick_type == \"CHIP\") {\n uint8View[6] |= 0x08;\n }\n uint8View[6] |= 0x04;\n if (binarized_command.charge_enable == true) {\n uint8View[6] |= 0x02;\n }\n\n // TODO : ErrFlag\n\n\n // TODO : Overflow err expression\n uint8View[7] = 0x00;\n uint8View[7] += binarized_command.dribble_power;\n uint8View[7] <<= 4;\n uint8View[7] += binarized_command.kick_power;\n\n // Make checksum\n uint8View[8] = 0x00;\n for (var i=2; i<8; i++) {\n uint8View[8] ^= uint8View[i];\n }\n uint8View[9] = uint8View[8] ^ 0xFF;\n\n return buffer;\n}",
"function messageFromBinaryCode(code) {\n // we can split the string in the params every 8 characters to have an array to work with.\n let binaryArr = code.match(/.{8}/g)\n // we can have a variable that holds the string being decipher from the binary code\n let message = ''\n // we would then iterate over the arr and use our helper to convert the binary code to decimal numbers, then refer to the ascii code to determine what character represents, and lastly we want to concatenate the ascii character found to the string.\n for(let binary in binaryArr){\n let character = String.fromCharCode(binaryToDecimal(binaryArr[binary]))\n message += character\n }\n\n return message\n}",
"static bytes14(v) { return b(v, 14); }",
"function getPosition(id){\n\treturn isDigital(id)?\"Port \"+id.charAt(0)+\" Pin \"+id.charAt(1):getName(id);\n}",
"function ServerBehavior_toString()\n{\n var partStr = \"\";\n for (var i = 0; i < this.sbParticipants.length; ++i)\n {\n partStr += ((partStr.length) ? \", \" : \"\") + this.sbParticipants[i].getName();\n }\n \n var str = \"ServerBehavior Instance\\n\"\n + \"=======================\\n\"\n + \"Name: \" + this.name + \"\\n\"\n + \"Title: \" + this.title + \"\\n\"\n + \"Parameters: {\" + this.getParameters() + \"}\\n\"\n + \"IsIncomplete: \" + this.incomplete + \"\\n\"\n + \"Participants: \" + partStr + \"\\n\"\n + \"ForceMultipleUpdate: \" + this.bForceMultipleUpdate + \"\\n\"\n + \"ForcePriorUpdate: \" + this.forcePriorUpdate + \"\\n\"\n + \"Family: \" + this.family + \"\\n\"\n + \"Errors: \" + this.errorMsg + \"\\n\"\n + \"UD4 backward compatible? \" + (this.type != null) + \"\\n\";\n\n // Add UD4 backward compatible properties if it is backward compatible.\n if (this.type != null)\n {\n str += \"\\nUD4 Backward Compatible Properties\\n\"\n + \"==================================\\n\"\n + \"Type: \" + this.type + \"\\n\"\n + \"ServerBehavior: \" + this.serverBehavior + \"\\n\"\n + \"SubType: \" + this.subType + \"\\n\"\n + \"DataSource: \" + this.dataSource + \"\\n\"\n + \"Params: \" + this.params + \"\\n\"\n + \"DeleteTypes: \" + this.deleteTypes + \"\\n\"\n + \"Weights: \" + this.weights + \"\\n\"\n + \"Types: \" + this.types + \"\\n\"; \n }\n\n return str;\n}",
"static bytes15(v) { return b(v, 15); }",
"function parseEstimoteTelemetryPacket(data) { // data is a 0-indexed byte array/buffer\n\n // byte 0, lower 4 bits => frame type, for Telemetry it's always 2 (i.e., 0b0010)\n var frameType = data.readUInt8(0) & 0b00001111;\n var ESTIMOTE_FRAME_TYPE_TELEMETRY = 2;\n if (frameType != ESTIMOTE_FRAME_TYPE_TELEMETRY) {\n return;\n }\n\n // byte 0, upper 4 bits => Telemetry protocol version (\"0\", \"1\", \"2\", etc.)\n var protocolVersion = (data.readUInt8(0) & 0b11110000) >> 4;\n // this parser only understands version up to 2\n // (but at the time of this commit, there's no 3 or higher anyway :wink:)\n if (protocolVersion > 2) {\n return;\n }\n\n // bytes 1, 2, 3, 4, 5, 6, 7, 8 => first half of the identifier of the beacon\n var shortIdentifier = data.toString('hex', 1, 9);\n\n // byte 9, lower 2 bits => Telemetry subframe type\n // to fit all the telemetry data, we currently use two packets, \"A\" (i.e., \"0\")\n // and \"B\" (i.e., \"1\")\n var subFrameType = data.readUInt8(9) & 0b00000011;\n\n var ESTIMOTE_TELEMETRY_SUBFRAME_A = 0;\n var ESTIMOTE_TELEMETRY_SUBFRAME_B = 1;\n\n // ****************\n // * SUBFRAME \"A\" *\n // ****************\n if (subFrameType == ESTIMOTE_TELEMETRY_SUBFRAME_A) {\n\n\n var errors;\n if (protocolVersion == 2) {\n // in protocol version \"2\"\n // byte 15, bits 2 & 3\n // bit 2 => firmware error\n // bit 3 => clock error (likely, in beacons without Real-Time Clock, e.g.,\n // Proximity Beacons, the internal clock is out of sync)\n errors = {\n hasFirmwareError: ((data.readUInt8(15) & 0b00000100) >> 2) == 1,\n hasClockError: ((data.readUInt8(15) & 0b00001000) >> 3) == 1\n };\n } else if (protocolVersion == 1) {\n // in protocol version \"1\"\n // byte 16, lower 2 bits\n // bit 0 => firmware error\n // bit 1 => clock error\n errors = {\n hasFirmwareError: (data.readUInt8(16) & 0b00000001) == 1,\n hasClockError: ((data.readUInt8(16) & 0b00000010) >> 1) == 1\n };\n } else if (protocolVersion == 0) {\n // in protocol version \"0\", error codes are in subframe \"B\" instead\n }\n\n // ***** ATMOSPHERIC PRESSURE\n\n\n return {\n shortIdentifier,\n frameType: 'Estimote Telemetry',\n subFrameType: 'A',\n protocolVersion,\n errors\n };\n\n // ****************\n // * SUBFRAME \"B\" *\n // ****************\n } else if (subFrameType == ESTIMOTE_TELEMETRY_SUBFRAME_B) {\n\n\n var batteryVoltage =\n (data.readUInt8(18) << 6) |\n ((data.readUInt8(17) & 0b11111100) >> 2);\n if (batteryVoltage == 0b11111111111111) {\n batteryVoltage = undefined;\n }\n\n // ***** ERROR CODES\n // byte 19, lower 2 bits\n // see subframe A documentation of the error codes\n // starting in protocol version 1, error codes were moved to subframe A,\n // thus, you will only find them in subframe B in Telemetry protocol ver 0\n var errors;\n if (protocolVersion == 0) {\n errors = {\n hasFirmwareError: (data.readUInt8(19) & 0b00000001) == 1,\n hasClockError: ((data.readUInt8(19) & 0b00000010) >> 1) == 1\n };\n }\n\n // ***** BATTERY LEVEL\n // byte 19 => battery level, between 0% and 100%\n // if all bits are set to 1, it means it hasn't been measured yet\n // added in protocol version 1\n var batteryLevel;\n if (protocolVersion >= 1) {\n batteryLevel = data.readUInt8(19);\n if (batteryLevel == 0b11111111) {\n batteryLevel = undefined;\n }\n }\n\n return {\n shortIdentifier,\n frameType: 'Estimote Telemetry',\n subFrameType: 'B',\n protocolVersion,\n batteryVoltage,\n batteryLevel,\n errors\n };\n }\n }",
"toString(){\n let longestHeader = this.headerRow.reduce(LONGEST_STRING_LENGTH_IN_ARRAY, 0);\n let longestCell = this.body.reduce(LONGEST_STRING_LENGTH_IN_ARRAY_OF_ARRAYS, 0);\n let cellSize = (longestHeader < longestCell) ? longestCell : longestHeader;\n let ret = \"\";\n // build headers\n ret += PAD_JOIN_ARRAY(this.headerRow, cellSize);\n ret += this.body.map((row)=>'\\n' + PAD_JOIN_ARRAY(row, cellSize)).join('');\n\n return ret;\n }",
"static bytes13(v) { return b(v, 13); }",
"function decodeMessage() {\n// new RegExp( \"(\\\\d)(\\\\d{2})(.{\" + smash._securityTokenLength + \"})(.{\" + smash._securityTokenLength + \"})(\\\\d)(\\\\d{2})(.*)\" )\n\t\tvar type=currentHash.substr(0,1);\n\t\tvar msn=currentHash.substr(1,2);\n\t\tvar nextStart = 3;\n\t\tvar tokenParent=currentHash.substr(nextStart,smash._securityTokenLength);\n\t\tnextStart += smash._securityTokenLength;\n\t\tvar tokenChild=currentHash.substr(nextStart,smash._securityTokenLength);\n\t\tnextStart += smash._securityTokenLength;\n\t\tvar ack=currentHash.substr(nextStart,1);\n\t\tnextStart += 1;\n\t\tvar ackMsn=currentHash.substr(nextStart,2);\n\t\tnextStart += 2;\n\t\t// The payload needs to stay raw since the uri decoding needs to happen on the concatenated data in case of a large message\n\t\tvar payload=currentHash.substr(nextStart);\n\t\tlog( \"In : Type: \" + type + \" msn: \" + msn + \" tokenParent: \" + tokenParent + \" tokenChild: \" + tokenChild + \" ack: \" + ack + \" msn: \" + ackMsn + \" payload: \" + payload );\n\t\tmessageIn={type: type, msn: msn, tokenParent: tokenParent, tokenChild: tokenChild, ack: ack, ackMsn: ackMsn, payload: payload};\n\t\treturn true;\n\t}",
"mimeToString(mimePart, includeHeaders) {\n EnigmailLog.DEBUG(\n \"persistentCrypto.jsm: mimeToString: part: '\" + mimePart.partNum + \"'\\n\"\n );\n\n let msg = \"\";\n let rawHdr = mimePart.headers._rawHeaders;\n\n if (includeHeaders && rawHdr.size > 0) {\n for (let hdr of rawHdr.keys()) {\n let formatted = formatMimeHeader(hdr, rawHdr.get(hdr));\n msg += formatted;\n if (!formatted.endsWith(\"\\r\\n\")) {\n msg += \"\\r\\n\";\n }\n }\n\n msg += \"\\r\\n\";\n }\n\n if (mimePart.body.length > 0) {\n let encoding = getTransferEncoding(mimePart);\n if (!encoding) {\n encoding = \"8bit\";\n }\n\n if (encoding === \"base64\") {\n msg += EnigmailData.encodeBase64(mimePart.body);\n } else {\n let charset = getCharset(mimePart, \"content-type\");\n if (charset) {\n msg += EnigmailData.convertFromUnicode(mimePart.body, charset);\n } else {\n msg += mimePart.body;\n }\n }\n }\n\n if (mimePart.subParts.length > 0) {\n let boundary = EnigmailMime.getBoundary(\n rawHdr.get(\"content-type\").join(\"\")\n );\n\n for (let i in mimePart.subParts) {\n msg += `--${boundary}\\r\\n`;\n msg += this.mimeToString(mimePart.subParts[i], true);\n if (msg.search(/[\\r\\n]$/) < 0) {\n msg += \"\\r\\n\";\n }\n msg += \"\\r\\n\";\n }\n\n msg += `--${boundary}--\\r\\n`;\n }\n return msg;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The range of the view [time] | get viewRange() {
return this._viewDrawWidth / this.pixelsWidthPerUnitTime;
} | [
"get viewEndTime() {\n return this._viewStartTime + this.viewRange;\n }",
"get temporalRangeMax() {\n return this.temporalRange[1];\n }",
"getSelectedRange() {\n let range;\n if (!Object(_syncfusion_ej2_base__WEBPACK_IMPORTED_MODULE_0__[\"isNullOrUndefined\"])(this.startValue) && !Object(_syncfusion_ej2_base__WEBPACK_IMPORTED_MODULE_0__[\"isNullOrUndefined\"])(this.endValue)) {\n range = (Math.round(Math.abs((this.removeTimeValueFromDate(this.startValue).getTime() -\n this.removeTimeValueFromDate(this.endValue).getTime()) / (1000 * 60 * 60 * 24))) + 1);\n this.disabledDateRender();\n if (!Object(_syncfusion_ej2_base__WEBPACK_IMPORTED_MODULE_0__[\"isNullOrUndefined\"])(this.disabledDayCnt)) {\n range = range - this.disabledDayCnt;\n this.disabledDayCnt = null;\n }\n }\n else {\n range = 0;\n }\n return { startDate: this.startValue, endDate: this.endValue, daySpan: range };\n }",
"function duration_within_display_range(range_start, range_end, event_start, event_end) {\n if (event_start < range_start) {\n return duration_seconds_to_minutes(event_end - range_start);\n } else if (event_end > range_end) {\n return duration_seconds_to_minutes(range_end - event_start);\n } else {\n return duration_seconds_to_minutes(event_end - event_start);\n } \n }",
"getBounds(time) {\n\t\tif (time === undefined && this._frameKey) {\n\t\t\ttime = this._frameKey;\n\t\t} else if (index === undefined) {\n\t\t\ttime = this._times[0];\n\t\t}\n\t\tconst layer = this._frameLayers[time];\n\t\treturn layer.getBounds();\n\t}",
"getViewport() {\n return {\n minX: this.minX,\n maxX: this.maxX,\n minY: this.minY,\n maxY: this.maxY,\n xRange: this.currentXRange,\n yRange: this.currentYRange\n };\n }",
"function setSliderMinMaxDates(range) {\n $scope.layoutEndTimeMS = range.max;\n $scope.layoutStartTimeMS = range.min;\n $scope.currentDate = range.min;\n $scope.layoutCurTimeMS = range.min;\n }",
"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 time2ViewPos(t) {\n return ~~((t - viewportPosition) / audioBuffer.duration * totalClientWidth);\n}",
"getRangeStart() {\n return ChromeVoxState.instance.getCurrentRange().start.node;\n }",
"function Range() {\n\tthis.minCells = 2 // Can operate on a minimum of 2 cells\n\tthis.maxCells = 4 // Can operate on a maximum of 4 cells\n\tthis.symbol = 'range'\n}",
"setRanges() {\r\n\t\tthis.ranges.x = d3.scaleTime()\r\n\t\t\t.range([0, this.dimensions.width - this.margins.x]);\r\n\r\n\t\tthis.ranges.y = d3.scaleLinear()\r\n\t\t\t.range([this.dimensions.height - (2 * this.margins.y), 0]);\r\n\t}",
"function range(timeline, phase) {\n const details = scrollTimelineOptions.get(timeline);\n\n const unresolved = null;\n if (timeline.phase === 'inactive')\n return unresolved;\n\n if (!(timeline instanceof ViewTimeline))\n return unresolved;\n\n // Compute the offset of the top-left corner of subject relative to\n // top-left corner of the container.\n const container = timeline.source;\n const target = timeline.subject;\n\n return calculateRange(phase, container, target, details.axis, details.inset);\n}",
"isElementShowing(e) {\n return this.props.time >= e.start_time &&\n this.props.time <= e.end_time;\n }",
"timeToRatio(time) {\n return (time - this._viewStartTime) / this.viewRange;\n }",
"_getTimeRangeInReverse(startTime, endTime) {\n const slices = this.streamBuffer.getTimeslices({start: startTime, end: endTime}).reverse();\n return {\n streams: slices.map(timeslice => timeslice.streams).filter(Boolean),\n links: slices.map(timeslice => timeslice.links).filter(Boolean)\n };\n }",
"function updateDisplayTimeRange() {\n if (model.properties.actualDuration === null || model.properties.actualDuration === Infinity) {\n return;\n }\n updatePropertyRange('displayTime', 0, model.properties.actualDuration);\n }",
"function adjustVisibleTimeRangeToAccommodateAllEvents() {\r\n timeline.setVisibleChartRangeAuto();\r\n}",
"static forRange(view, className, range) {\n if (range.empty) {\n let pos = view.coordsAtPos(range.head, range.assoc || 1)\n if (!pos) return []\n let base = getBase(view)\n return [\n new RectangleMarker(\n className,\n pos.left - base.left,\n pos.top - base.top,\n null,\n pos.bottom - pos.top\n )\n ]\n } else {\n return rectanglesForRange(view, className, range)\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Eliminar de la agenda | function del()
{
var r = confirm("¿Estas seguro de eliminar?");
if(r == true)
{
agenda.results.splice(index, 1);
primer();
}
} | [
"function handleDelete(event) {\n\tlet id = event.target.id;\n\n\tlet output = [];\n\n\toutput = db_appointments.filter(function (value) {\n\t\treturn value.idPengunjung !== id;\n\t});\n\n\tdb_appointments = output;\n\n\tevent.target.parentElement.remove();\n}",
"function accionEliminar()\t{\n\t\tvar arr = new Array();\n\t\tarr = listado1.codSeleccionados();\n\t\teliminarFilas(arr,\"DTOEliminarMatricesDescuento\", mipgndo, 'resultadoOperacionMsgPersonalizado(datos)');\n\t}",
"function eliminarTarea() {\n\n axios.delete(URL + 'tarea/' + tareaSeleccionada.id,\n {\n headers: { Authorization: 'Bearer ' + JSON.parse(state.token) }\n }\n )\n .then((res) => {\n\n mostrarNotificacion('Tarea eliminada exitosamente', 'success')\n buscarTareas(); //actualizar lista de tareas\n })\n .catch((err) => {\n mostrarNotificacion('Error al eliminar', 'warning')\n console.log(err)\n })\n }",
"function borrarRegistro(){\n \n /*aId.splice(posicion,1);\n aDireccion.splice(posicion,1);\n aLatitud.splice(posicion,1);\n aLongitud.splice(posicion,1);\n */\n\n aContenedor.splice(posicion,1)\n contador--;\n\n\n posicion=0;\n mostrarRegistro(posicion);\n\n}",
"function eventDelete(){\n\t\tid = $('.btnAcceptE').val();\n\t\tnumPag = $('ul .current').val();\n\t\t$.ajax({\n type: \"POST\",\n url: \"../admin/eventos/deleteEvent\",\n dataType:'json',\n data: { \n\t\t\t\tid:id\n\t\t\t},\n success: function(data){\n\t\t\t\t\tvar aux = 0;\n\t\t\t\t\t$('#tableEvents tbody tr').each(function(index) {\n aux++;\n });\n\t\t\t\t\t\n\t\t\t\t\t//si es uno regarga la tabla con un indice menos\n\t\t\t\t\tif(aux == 1){\n\t\t\t\t\t\tnumPag = numPag-1;\n\t\t\t\t\t}\n\t\t\t\t\tajaxMostrarTabla(column,order,\"../admin/eventos/getallSearch\",(numPag-1),\"event\");\n\t\t\t\t\t$('#divMenssagewarning').hide(1000);\n\t\t\t\t\t$('#alertMessage').empty();\n\t\t\t\t\t$('#alertMessage').append(\"se ha eliminado el evento\");\n\t\t\t\t\t$('#divMenssage').show(1000).delay(1500);\n\t\t\t\t\t$('#divMenssage').hide(1000);\n \t}\n\t\t});\n\t}",
"function deleteVassalOnClick(e){\r\n // Remove the element\r\n g_vassals.splice(parseInt(e.currentTarget.parentNode.id.split('vassal_')[1]), 1);\r\n\r\n setVassals();\r\n setVassalTable();\r\n}",
"function deleteToDo(position){\r\ntoDos.splice(position, 1);\r\ndisplayToDos();\r\n}",
"function deleteTask(){\n // get indx of tasks\n let mainTaskIndx = tasksIndxOf(delTask['colName'], delTask['taskId']);\n // del item\n tasks.splice(mainTaskIndx, 1);\n // close modal\n closeModal();\n // update board\n updateBoard();\n // update backend\n updateTasksBackend();\n}",
"deleteAppointment(date,time)\n {\n if (this.map.has(date)) {\n\n for (let i=0; i<this.map.get(date).length; i++)\n {\n if (this.map.get(date)[i].date == date && this.map.get(date)[i].time == time) {\n this.map.get(date).splice(i,1);\n break;\n }\n }\n }\n }",
"function deleteCourse(e) {\n if(e.target.classList.contains('borrar-curso')) {\n const courseId = e.target.getAttribute('data-id');\n // delete del array articulos carrito por el data-id\n articulosCarrito = articulosCarrito.filter( course => course.id !== courseId )\n \n carritoHtml(); // itera sobre el cart y show su html\n \n\n }\n}",
"function delData_Proses() {\n\n var id = $('#id').val();\n\n var dbRef_delete = firebase.database();\n var piutang_umAlat = dbRef_delete.ref(\"transaksi/\" + id);\n piutang_umAlat.remove();\n $('#ModalDel').modal('hide');\n tampilData();\n }",
"function eliminarCurso(e) {\n if (e.target.classList.contains('borrar-curso')) {\n const cursoId = e.target.getAttribute('data-id');\n\n articulosCarrito = articulosCarrito.filter(curso => curso.id !== cursoId);\n \n carritoHTML();\n }\n}",
"function erase(e) {\n database.database_call(`DELETE FROM subnote WHERE id=${id} `);\n alerted.note(\"The current note was deleted!\", 1);\n Alloy.Globals.RenderSubNotesAgain();\n $.view_subnotes.close();\n}",
"function siEliminarM(datos) {\n\tvar parametros = {\n\t\t\"datos\": datos,\n\t\t\"tabla\": \"MENU\",\n\t\t\"campo\": \"IdMenu\"\n\t};\n\teliminar(parametros);\n}",
"function removeEventAfterDelete(data) {\r\n var info = JSON.parse(data);\r\n $removeScheduleBtn.css(\"display\", \"block\");\r\n $removeBtnConfirmContainer.css(\"display\", \"none\");\r\n var schedulePk = info[\"schedule_pk\"];\r\n // Remove from hidden events if in hidden schedule times list\r\n schIndex = findWithAttr(schedulesWithHiddenTimes, \"id\", schedulePk);\r\n if (schIndex !== -1) { schedulesWithHiddenTimes.splice(schIndex, 1); }\r\n\r\n\r\n // Update title string to reflect changes to schedule & rehighlight\r\n $event = $fullCal.fullCalendar(\"clientEvents\", schedulePk);\r\n if (!displaySettings[\"unique_row_per_employee\"] || $event[0].eventRowSort == EMPLOYEELESS_EVENT_ROW) {\r\n $fullCal.fullCalendar(\"removeEvents\", schedulePk);\r\n } else {\r\n var start = moment($event[0].start);\r\n var date = start.format(DATE_FORMAT);\r\n var eventRow = $event[0].eventRowSort;\r\n var employeePk = employeeSortedIdList[eventRow];\r\n // Check if employee is assigned more than once per day, if not, create\r\n // a blank event to maintain row sort integrity\r\n if (!_employeeAssignedMoreThanOnceOnDate(date, employeePk)) {\r\n var blankEvent = _createBlankEvent(date, employeePk, eventRow);\r\n $fullCal.fullCalendar(\"renderEvent\", blankEvent);\r\n }\r\n $fullCal.fullCalendar(\"removeEvents\", schedulePk)\r\n }\r\n // Update cost display to reflect any cost changes\r\n if (info[\"cost_delta\"]) {\r\n updateHoursAndCost(info[\"cost_delta\"]);\r\n reRenderAllCostsHours();\r\n }\r\n // Disable schedule note\r\n $scheduleNoteText.val(\"Please Select A Schedule First\");\r\n $scheduleNoteBtn.prop('disabled', true);\r\n // Inactivate schedule buttons and get proto eligibles\r\n $removeScheduleBtn.addClass(\"inactive-btn\");\r\n $editScheduleBtn.addClass(\"inactive-btn\");\r\n getProtoEligibles({data: {date: $addScheduleDate.val()}});\r\n }",
"deleteTodo() {\n\t let todo = this.get('todo');\n\t this.sendAction('deleteTodo', todo);\n\t }",
"function viewTaskdeleteThisTask() {\r\n if (confirm(\"You are about to delete this task?\")) {\r\n // Get taskobject === clicked taskCard\r\n TempLocalStorageTaskArray = getLocalStorage(\"task\");\r\n tempIndex = TempLocalStorageTaskArray.findIndex(obj => obj.name === viewTaskTitleDiv.innerHTML);\r\n //delete from localstorage where thisTask === \"task\".name\r\n // finn index og splice fra array\r\n TempLocalStorageTaskArray.splice(tempIndex, 1);\r\n setLocalStorage(\"task\", TempLocalStorageTaskArray);\r\n } else {\r\n console.log('no task was deleted');\r\n }\r\n\r\n\r\n}",
"function removeLinha() {\r\n $(\"#remove\").click(function () {\r\n $(\"tr.tbody4\").remove();\r\n\r\n alert(\"O aluno(a) foi removido do sistema com sucesso.\");\r\n });\r\n}",
"function deleteContact(e) {\n // navegar hacia el padre para ubicar el id del contacto\n if (e.target.parentElement.classList.contains(\"btn-delete\")) {\n const id = e.target.parentElement.getAttribute(\"data-id\");\n // console.log(id);\n const resp = confirm(\"Estas seguro de eliminar el contacto?\");\n if (resp) {\n // llamdo al ajax\n // crear el objeto\n const xhr = new XMLHttpRequest();\n\n // abrir la conexion\n xhr.open(\"GET\", `includes/models/model-contacts.php?id=${id}&accion=borrar`, true);\n\n // leer la respuesta\n xhr.onload = function () {\n if (this.status === 200) {\n const response = JSON.parse(xhr.responseText);\n\n if (response.response == \"success\") {\n // eliminar registro del DOM\n e.target.parentElement.parentElement.parentElement.remove();\n\n // mostrar una notificacion\n showNotification(\"Contacto eliminado\", \"success\");\n\n // actualizamos el contador de contactos\n numContacts();\n } else {\n // mostrar una notificacion\n showNotification(\"Hubo un error...\", \"error\");\n }\n }\n };\n\n // enviar la peticion\n xhr.send();\n }\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns scale based on original and end position of the two points. | function getScale(point1, startPoint1, point2, startPoint2) {
var initialDistance = getDistance(startPoint1, startPoint2);
var currentDistance = getDistance(point1, point2);
return Math.abs(currentDistance / initialDistance);
} | [
"function scaleSegment(x1, y1, x2, y2) {\r\n const magn = mag(x1, y1, x2, y2);\r\n const prop1 = (magn - 35) / magn;\r\n const prop2 = (magn - 45) / magn;\r\n const x_1p = x2 - (x2 - x1) * prop1;\r\n const y_1p = y2 - (y2 - y1) * prop1;\r\n const x_2p = x1 + (x2 - x1) * prop2;\r\n const y_2p = y1 + (y2 - y1) * prop2;\r\n return [x_1p, y_1p, x_2p, y_2p];\r\n}",
"get scale() { return (this.myscale.x + this.myscale.y)/2;}",
"function forceFromPoints(p1, p2, magnitude) {\n return p2.subNew(p1).normalize_().scale_(magnitude);\n }",
"_applyScale(point) {\n let scale = this.getScale()\n return {\n x: point.x * scale,\n y: point.y * scale,\n z: point.z * scale,\n }\n }",
"scale(scale) {\n const result = new Matrix();\n this.scaleToRef(scale, result);\n return result;\n }",
"get scale() {\n\t\treturn {\n\t\t\tx: this.dimens.x/this.width,\n\t\t\ty: this.dimens.y/this.height,\n\t\t};\n\t}",
"scale(scale) {\n return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);\n }",
"function linearScale(domain, range, value) {\n return ((value - domain[0]) / (domain[1] - domain[0])) * (range[1] - range[0]) + range[0];\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 }",
"onTransformScaling() {\n const scale = this.getClosestScaleToFitExtentFeature();\n this.setScale(scale);\n }",
"set scale(newscale)\n\t{\n\t\tthis.myscale.x = newscale;\n\t\tthis.myscale.y = newscale;\n\n\t\tthis.container.style.transform = \"scale(\" + newscale + \",\" + newscale + \")\";\n \n\t\t//get width and height metrics\n\t\tthis.size.x = this.container.getBoundingClientRect().width;\n this.size.y = this.container.getBoundingClientRect().height;\n\n\t\t//adjust z order based on scale\n\t\tthis.container.style.zIndex = (100 * newscale).toString();\n\t}",
"scaleToRange(x) {\r\n var t;\r\n t = this.minHeight + ((x - this.minTemp) * (this.maxHeight - this.minHeight)) / (this.maxTemp - this.minTemp); // Based on a formula googled from various sources.\r\n return t;\r\n }",
"static Lerp(start, end, amount) {\n const w = start.width + (end.width - start.width) * amount;\n const h = start.height + (end.height - start.height) * amount;\n return new Size(w, h);\n }",
"static Center(value1, value2) {\n const center = Vector2.Add(value1, value2);\n center.scaleInPlace(0.5);\n return center;\n }",
"static Center(value1, value2) {\n const center = Vector4.Add(value1, value2);\n center.scaleInPlace(0.5);\n return center;\n }",
"function calculateYScaleAndTranslation() {\n yScale = -graphHeight / (signal.getMaxValue() - signal.getMinValue());\n yTranslation = -yScale * signal.getMaxValue() + topMargin;\n }",
"get forceScale() {}",
"scale(scale) {\n return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);\n }",
"function gScale(sx,sy,sz) {\r\n modelViewMatrix = mult(modelViewMatrix,scale(sx,sy,sz)) ;\r\n}",
"getClosestScaleToFitMap() {\n const mapView = this.map.getView();\n const mapExtent = mapView.calculateExtent();\n const scales = this.getScales();\n let fitScale = scales[0];\n\n scales.forEach(scale => {\n const scaleVal = scale.value ? scale.value : scale;\n const printExtent = this.calculatePrintExtent(scaleVal);\n const contains = containsExtent(mapExtent, printExtent);\n\n if (contains) {\n fitScale = scale;\n }\n });\n\n return fitScale;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function for initialize shadows panel and additional listeners | initShadows($MIRROR, $SHADOWS_PANEL, _SOC_DATA) {
const $mirror_content = $($MIRROR.contents());
console.debug(
"Mirror is loaded: width[%s], height[%s]",
$mirror_content.width(),
$mirror_content.height()
);
// Set width and height for proper position
$MIRROR.height($mirror_content.height());
$SHADOWS_PANEL.height($mirror_content.height());
// Calculate shadows and set correct positions
const mirrorUtil = new MirrorUtil();
_SOC_DATA.rootNode = mirrorUtil.getPageComponents($mirror_content.find("body"));
const pageUtil = new PageUtil();
pageUtil.shadowsTreeNodes(_SOC_DATA.rootNode).forEach((el) => {
$SHADOWS_PANEL.append(el);
});
const HOVER_BORDER_SIZE = 2; // in px
mirrorUtil
.getShadows(_SOC_DATA.rootNode.children)
.forEach((el) => {
console.debug("Set position of: %s", el[4]);
const shadow = $("#" + el[4]);
if (shadow) {
shadow.css({
"top": el[0],
"left": el[1] + HOVER_BORDER_SIZE,
"width": el[2] - HOVER_BORDER_SIZE * 4,
"height": el[3] - HOVER_BORDER_SIZE * 2
});
}
});
const _menu = new ShadowComponentMenu();
$SHADOWS_PANEL.on("click", ".shadow-component", (e) => {
const id = $(e.target).attr("id");
if (id) {
const selectedShadow = _SOC_DATA.rootNode.getChildById(id);
if (selectedShadow) {
_SOC_DATA.selectedEl = selectedShadow;
}
}
_menu.showToolbar(e.target);
});
$SHADOWS_PANEL.show();
} | [
"init() {\n this._createShadowRoot()\n this._attachStyles()\n this._createElements()\n }",
"addDropShadows() {\n let offset = this.calendarView.mShadowOffset;\n let shadowStartDate = this.date.clone();\n shadowStartDate.addDuration(offset);\n this.calendarView.mDropShadows = [];\n for (let i = 0; i < this.calendarView.mDropShadowsLength; i++) {\n let box = this.calendarView.findDayBoxForDate(shadowStartDate);\n if (box) {\n box.setDropShadow(true);\n this.calendarView.mDropShadows.push(box);\n }\n shadowStartDate.day += 1;\n }\n }",
"function setShadow(data, clock) {\n clock.rotateElement(shadow, data.angle);\n shadow.style.opacity = data.opacity;\n}",
"init() {\n if (!this.menuButton) {\n this.menuButton = this.createMenuButton();\n }\n this.menuButton.addEventListener(\n 'click',\n this.handleButtonClick.bind(this)\n );\n if (!this.closeButton) {\n this.closeButton = this.createCloseButton();\n }\n this.closeButton.addEventListener(\n 'click',\n this.handleButtonClick.bind(this)\n );\n this.disableTab(this.overlay);\n }",
"function init() {\n\t\tstatsPanelBind()\n\t}",
"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 setupImageControls() {\n Data.Controls.Brightness = document.getElementById('brightness');\n Data.Controls.Contrast = document.getElementById('contrast');\n Data.Controls.Hue = document.getElementById('hue');\n Data.Controls.Saturation = document.getElementById('saturation');\n\n Data.Controls.Brightness.value = Settings.Filters.Brightness;\n Data.Controls.Contrast.value = Settings.Filters.Contrast;\n Data.Controls.Hue.value = Settings.Filters.Hue;\n Data.Controls.Saturation.value = Settings.Filters.Saturation;\n\n Data.Controls.Brightness.addEventListener('input', filterChange);\n Data.Controls.Contrast.addEventListener('input', filterChange);\n Data.Controls.Hue.addEventListener('input', filterChange);\n Data.Controls.Saturation.addEventListener('input', filterChange);\n\n document.getElementById('image-controls-reset').\n addEventListener('click', imageControlsResetClick);\n document.getElementById('image-controls-save').\n addEventListener('click', imageControlsSaveClick);\n}",
"function parallax_init()\n{\n\t//Nucleo do widget (não mecha)\n\tparallax_Box = document.createElement(\"div\");\n\tparallax_Box.id = \"parallaxContainer\";\n\tdocument.body.insertBefore(parallax_Box, document.body.firstChild);\n\n\tparallax_Layer0 = $(parallax_Box);\n\t\n\tparallax_custom_init();\n\t\n\t//Ajustes finais\n\t$(window).scroll(parallax_run);\n\t$(window).resize(parallax_size);\n\tparallax_size(null);\n\tparallax_run(null);\n}",
"removeDropShadows() {\n // method that may be overwritten by derived bindings...\n if (this.calendarView.mDropShadows) {\n for (let box of this.calendarView.mDropShadows) {\n box.setDropShadow(false);\n }\n }\n this.calendarView.mDropShadows = null;\n }",
"setupLayers() {\n this.d3.select(this.holderSelector).selectAll('*').remove();\n\n this.createSVGLayer();\n this.createPointsLayer();\n this.createTargetsLayer();\n }",
"init_controls() {\n if (this.$controls.length == 0) {\n return;\n }\n this.color_system_controls = make_sliders_for_color_system(this.color_system, this.$controls);\n\n // fullscreen button\n if (!this.$figure.find('.fullscreen-button').length) {\n // if no fullscreen button exists yet (can happen in comparisons), create one\n this.$fullscreen_button = $(\n '<span class=\"fullscreen-button\">Fullscreen</span>'\n ).prependTo(this.$figure.find('.figure-title'));\n this.$fullscreen_button.click(() => {\n toggle_full_screen(this.$figure[0]);\n /*\n * Other changes will be done in the fullscreenchange event listener below.\n * This is necessary for other visualizations to keep working as well in case\n * this figure is inside a visualization comparison.\n */\n });\n }\n $(document).on(\"webkitfullscreenchange mozfullscreenchange fullscreenchange\", () => {\n this.$container.find(\"canvas\").removeAttr(\"style\"); // otherwise, the figure will keep the previously calculated size\n if (is_fullscreen()) { // just changed to fullscreen\n //this.keep_aspect = false; // will be re-set to true on fullscreenchange (see below)\n console.log(\"entered fullscreen\");\n this.$fullscreen_button.text(\"Exit fullscreen\");\n } else { // just exited fullscreen\n //this.keep_aspect = true;\n console.log(\"exited fullscreen\");\n this.$fullscreen_button.text(\"Fullscreen\");\n }\n this.on_resize();\n });\n }",
"function init(){\n setupSquares();\n setupModeButtons();\n\n reset();\n}",
"function setupColorControls()\n{\n dropper.onclick = () => setDropperActive(!isDropperActive()) ;\n color.oninput = () => setLineColor(color.value);\n colortext.oninput = () => setLineColor(colortext.value);\n\n //Go find the origin selection OR first otherwise\n palettedialog.setAttribute(\"data-palette\", getSetting(\"palettechoice\") || Object.keys(palettes)[0]);\n\n palettedialogleft.onclick = () => { updatePaletteNumber(-1); refreshPaletteDialog(); }\n palettedialogright.onclick = () => { updatePaletteNumber(1); refreshPaletteDialog(); }\n refreshPaletteDialog();\n}",
"function setupClasses(){\n // Gather Variables to Pass to Classes\n doodleNames = [\"krill\",\"worm\",\"sunshine\",\"smiles\"];\n drawZone = document.querySelector(\".draw-zone\");\n\n // Declare Classes\n svgLoader = new SVGLOADER(document.querySelectorAll(\"svg[data-type='svg']\"),svgData);\n svgStage = new SVGSTAGE(doodleNames,drawZone,document.body);\n touchSwipe = new TOUCHSWIPE(drawZone,drawZone.querySelector(\".doodle\"),svgStage.eventCallback.bind(svgStage));\n}",
"function Window_SwipeContainer() {\n this.initialize.apply(this, arguments);\n}",
"function init(){\n homeScreen.createHomePage();\n beaverEvents.addModel(beaverApp);\n beaverEvents.addModel(beaverRelations);\n beaverEvents.getViewState(homeScreen);\n beaverEvents.getViewState(profileView);\n beaverEvents.activeView = homeScreen.name;\n beaverEvents.viewState.homeScreen.showMapButton();\n // Display beavers\n beaverEvents.displayBeavers();\n // beaverEvents.getGeoLocation();\n homeScreenHandlers.setupEvents();\n}",
"init_advanced_controls(color_system_name) {\n let that = this;\n if (this.$figure.find(\".visualization-controls-advanced-toggle\").length == 0) {\n /* Add toggle for showing/hiding controls. */\n this.$controls_advanced.before(\n '<h3 class=\"visualization-controls-advanced-toggle\">' +\n '<span class=\"arrow\">▶ </span><span class=\"text\">Advanced controls</span></h3>'\n );\n this.$controls_advanced.hide();\n let $toggle = this.$figure.find(\".visualization-controls-advanced-toggle\");\n $toggle.click(function () {\n if (that.$controls_advanced.is(\":visible\")) {\n $toggle.find(\".arrow\").removeClass(\"arrow-rotated\");\n } else {\n $toggle.find(\".arrow\").addClass(\"arrow-rotated\");\n }\n that.$controls_advanced.toggle(300);\n });\n }\n\n this.$controls_advanced.append(\n '<h3 class=\"visualization-controls-system-header\">' +\n color_system_name +\n '</h3>'\n );\n this.show_only_color_solid_control = new VisualizationControlCheck(\n this.$controls_advanced,\n \"Show the color solid only\"\n );\n this.show_only_color_solid_control.add_listener((event) =>\n that.show_only_color_solid_changed.call(that, event));\n }",
"function ShadowGenerator(mapSize,light,useFullFloatFirst){this._bias=0.00005;this._normalBias=0;this._blurBoxOffset=1;this._blurScale=2;this._blurKernel=1;this._useKernelBlur=false;this._filter=ShadowGenerator.FILTER_NONE;this._filteringQuality=ShadowGenerator.QUALITY_HIGH;this._contactHardeningLightSizeUVRatio=0.1;this._darkness=0;this._transparencyShadow=false;/**\n * Controls the extent to which the shadows fade out at the edge of the frustum\n * Used only by directionals and spots\n */this.frustumEdgeFalloff=0;/**\n * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.\n * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.\n * It might on the other hand introduce peter panning.\n */this.forceBackFacesOnly=false;this._lightDirection=BABYLON.Vector3.Zero();this._viewMatrix=BABYLON.Matrix.Zero();this._projectionMatrix=BABYLON.Matrix.Zero();this._transformMatrix=BABYLON.Matrix.Zero();this._cachedPosition=new BABYLON.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE);this._cachedDirection=new BABYLON.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE);this._currentFaceIndex=0;this._currentFaceIndexCache=0;this._defaultTextureMatrix=BABYLON.Matrix.Identity();this._mapSize=mapSize;this._light=light;this._scene=light.getScene();light._shadowGenerator=this;var component=this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR);if(!component){component=new BABYLON.ShadowGeneratorSceneComponent(this._scene);this._scene._addComponent(component);}// Texture type fallback from float to int if not supported.\nvar caps=this._scene.getEngine().getCaps();if(!useFullFloatFirst){if(caps.textureHalfFloatRender&&caps.textureHalfFloatLinearFiltering){this._textureType=BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;}else if(caps.textureFloatRender&&caps.textureFloatLinearFiltering){this._textureType=BABYLON.Engine.TEXTURETYPE_FLOAT;}else{this._textureType=BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;}}else{if(caps.textureFloatRender&&caps.textureFloatLinearFiltering){this._textureType=BABYLON.Engine.TEXTURETYPE_FLOAT;}else if(caps.textureHalfFloatRender&&caps.textureHalfFloatLinearFiltering){this._textureType=BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;}else{this._textureType=BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;}}this._initializeGenerator();this._applyFilterValues();}",
"initAndPosition() {\n // Append the info panel to the body.\n $(\"body\").append(this.$el);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the HTML for an item tree link | function itemTree(leftId, leftPatch, rightId, rightPatch) {
var innerHtml = '<a href="ItemTrees#leftId=' + leftId + '&leftPatch=' + leftPatch + '&rightId=' + rightId + '&rightPatch=' + rightPatch + '">Item Trees: ';
innerHtml += champHtml(leftId);
innerHtml += ' (' + leftPatch + ') vs ';
innerHtml += champHtml(rightId);
innerHtml += ' (' + rightPatch + ')</a>';
return innerHtml;
} | [
"function bookmarksHtml(bm_node, depth) {\n var html = '';\n \n if (bm_node.children) {\n html = html + '<li class=\"group l_' + depth + '';\n if (bm_node.title == 'Other Bookmarks') {\n html = html + ' other';\n }\n html = html + '\"><ul class=\"folder\"><h3>' + bm_node.title + '</h3></label><div>';\n var child_html = '';\n \n if (bm_node.children.length == 0) {\n child_html = child_html + '<li class=\"empty\"><h4>(empty)</h4></li>';\n } else {\n for (var i = 0; i < bm_node.children.length; i++) {\n child_html = child_html + bookmarksHtml(bm_node.children[i], depth + 1);\n }\n }\n \n html = html + child_html + '</div></ul></li>';\n } else if (bm_node.url) {\n html = html + '<a href=\"' + bm_node.url + '\"><li';\n if (bm_node.url.indexOf('javascript:') != 0) {\n html = html + ' style=\"background-image: url(chrome://favicon/' + bm_node.url + ');\"';\n }\n html = html + '><h4>' + bm_node.title + '</h4></li></a>';\n }\n \n return html;\n}",
"function convertItemWithNameAndIdToDom(item, params) {\n let result = $(\"<span></span>\");\n // Checks, if we have valid link information, so the user can click on the item to move to it\n // The link will only be shown when the parameter does inhibit this. The inhibition might be required\n // in case the calling element wants to include its own action.\n const validLinkInformation = item.uri !== undefined && item.workspace !== undefined &&\n item.uri !== \"\" && item.workspace !== \"\";\n const inhibitLink = params !== undefined && params.inhibitItemLink;\n if (validLinkInformation && !inhibitLink) {\n const linkElement = $(\"<a></a>\");\n linkElement.text(item.name);\n if ((params === null || params === void 0 ? void 0 : params.onClick) !== undefined) {\n // There is a special click handler, so we execute that one instead of a generic uri\n linkElement.attr('href', '#');\n linkElement.on('click', () => { params.onClick(item); return false; });\n }\n else {\n linkElement.attr(\"href\", \"/Item/\" + encodeURIComponent(item.workspace) +\n \"/\" + encodeURIComponent(item.uri));\n }\n result.append(linkElement);\n }\n else {\n result.text(item.name);\n }\n // Add the metaclass\n if (item.metaClassName !== undefined && item.metaClassName !== null) {\n const metaClassText = $(\"<span class='dm-metaclass'></span>\");\n metaClassText\n .attr('title', item.metaClassUri)\n .text(\" [\" + item.metaClassName + \"]\");\n result.append(metaClassText);\n }\n return result;\n }",
"function itemTree() {\n return col('col-12 col-xl-3', \n div('itemTree', itemTreeTitle() + '<hr>' + itemTreeChange() + '<hr>' + itemTreeTree() + '<hr>' + itemTreeAdd())\n )\n}",
"function buildTreeNavigation() {\n\tvar html = '';\n\t\n\thtml += '<div class=\"tree_roles\">';\n\tfor (var i = 0; i < roles.length; i++) {\n\t\tvar role = roles[i];\n\t\t\n\t\thtml += '<div class=\"tree_role\">';\n\t\thtml += '<a href=\"' + i + '\" class=\"tree_role_link\"><img src=\"' + role.headshot + '\" class=\"tree_role_img\"/></a>';\n\t\thtml += ' <a href=\"' + i + '\" class=\"tree_role_link tree_link_text\">' + role.shortTitle + '</a>';\n\t\thtml += '</div>';\n\t\t\n\t\thtml += '<div class=\"tree_lessons\">';\n\t\tfor (var j = 0; j < role.lessons.length; j++) {\n\t\t\tvar lesson = role.lessons[j];\n\t\t\t\n\t\t\thtml += '<div class=\"tree_lesson\">';\n\t\t\thtml += '<a href=\"' + j + '\" class=\"tree_lesson_link\"><img src=\"' + lesson.icon + '\" class=\"tree_lesson_img\"/></a>';\n\t\t\thtml += ' <a href=\"' + j + '\" class=\"tree_lesson_link tree_link_text\">' + lesson.title + '</a>';\n\t\t\thtml += '</div>';\n\t\t}\n\t\thtml += '</div>';\n\t}\n\thtml += '</div>';\n\t\n\t$('#tree').html(html);\n\n\t$('#tree a.tree_role_link').bind('click', function(event) {\n\t\tevent.preventDefault();\n\t\tshowLessons(getRole($(this).attr('href')));\n\t});\n\t\n\t$('#tree a.tree_lesson_link').bind('click', function(event) {\n\t\tevent.preventDefault();\n\t\tshowLesson(getLesson(\n\t\t\t$(this).parent().parent().prevAll('.tree_role:first').children('a.tree_role_link').attr('href'), \n\t\t\t$(this).attr('href')\n\t\t));\n\t});\n}",
"function buildNode(id, name, parent){\n\t\tvar element = $(\"<li><a>\" + name + \"</i></a></li>\");\n\t\t\n\t\t$('a', element).attr('data-remote','true');\n\t\t$('a', element).attr('data-tagname', name);\n\t\t$('a', element).attr('href', window.location.href + '/?tag=' + name);\n\t\tparent.append(element); \n\t\treturn element;\n\t}",
"get ancestorTitle() {\n if (this.manifest && this.activeItem) {\n let tmpItem = this.manifest.items.find(\n (d) => this.activeItem.parent === d.id\n );\n // walk back up to the root\n while (tmpItem && tmpItem.parent != null) {\n // take the parent object of this current item\n tmpItem = this.manifest.items.find((i) => i.id == tmpItem.parent);\n }\n if (tmpItem) {\n return tmpItem.title;\n }\n }\n return \"\";\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}",
"function assemble_repo_node(repo_obj) {\n return $('<div></div>')\n .addClass('col-md-3')\n .append($('<div></div>')\n .addClass('well')\n .addClass('repo')\n .attr('data-lang-color', repo_obj.language)\n .append($('<a></a>')\n .attr('href', repo_obj.html_url)\n .attr('target', '_blank')\n .attr('rel', 'noreferrer')\n .append($('<h2></h2>')\n .text(repo_obj.name)\n .append(assemble_repo_meta(repo_obj.language, 'repo-language'))\n .append(assemble_repo_meta(repo_obj.pushed_at, 'repo-update', date_styler)))\n .append(assemble_repo_meta(repo_obj.description))));\n }",
"function writeContextMenuProperty(item){\r\n var link=\"<span class=\\\"contextmenu_property\\\">\"+item[\"property\"]+\":<\\/span> \"+item[\"val\"]+\"<br/>\";\r\n return link;\r\n}",
"function repoLink(name) {\n return '<a class=\"repo\" href=\"https://github.com/'+name+'\">'+name+'</a>';\n}",
"function html_link_from_todoist_task(task_title, task_id) {\n url = 'https://en.todoist.com/app?lang=en#task%2F' + String(task_id)\n html_task = \"<a target='_blank' href='\" + url + \"'>\" + task_title + \"</a>\"\n return html_task\n}",
"_getLinkText() {\n let text = this._gatherTextUnder(this.context.link);\n\n if (!text || !text.match(/\\S/)) {\n text = this.context.link.getAttribute(\"title\");\n if (!text || !text.match(/\\S/)) {\n text = this.context.link.getAttribute(\"alt\");\n if (!text || !text.match(/\\S/)) {\n text = this.context.linkURL;\n }\n }\n }\n\n return text;\n }",
"function renderLinks(eventID) {\n let htmlResult= `<div class=\"links\"><a href=\"/events\">Return to events list</a> | <a class=\"delete-link\" href=\"/delete?evnt=${encodeURI(eventID)}\">Delete this event</a></div>`;\n return htmlResult;\n}",
"getDeepLink(platform, link) {}",
"function writeContextMenuAction(item){\r\n\r\n var onclick=\"\";\r\n if(item[\"onclick\"]){ onclick='onclick=\"'+item[\"onclick\"]+';return false\"'; }\r\n var url = item[\"url\"];\r\n if (0!=url.indexOf(\"http\") && 0!=url.indexOf(contextPath)) {\r\n \turl = contextPath+url;\r\n }\r\n var link ='<a href=\"'+ url +'\" '+onclick+'>';\r\n link += '<img src=\"'+ contextPath +'/skins/default/images/icons/'+ item[\"icon\"] +'\" alt=\"\" height=\"16\" width=\"16\">';\r\n link += item[\"text\"];\r\n link += '</a>';\r\n\r\n return link;\r\n}",
"function buildItem(heading, currentLevel, maxLevel) {\n if (currentLevel > maxLevel) { return; }\n\n const item = $('<li class=\"usa-sidenav__item\"></li>');\n const link = $(`<a href=\"#${heading.attr(\"id\")}\">${heading.text()}</a>`);\n item.append(link);\n\n if (!(currentLevel + 1 > maxLevel)) {\n const sublist = buildSublist(heading, currentLevel, maxLevel);\n item.append(sublist);\n }\n\n return item;\n }",
"function generateMenu(menuItems) {\n return menuItems.reduce((c, v) => c += `<a href=\"${v.url}\">${v.text}</a>`, '');\n}",
"function CreateUrlTree ()\n{\n\treturn new UrlTreeNode (null, \"\", \"\");\n}",
"function addItemToTree (item) {\n\t\tlet newNavItem = $protoNavItem.clone(),\n\t\t\t$newNavItem;\n\n\t\tnewNavItem = newNavItem.html()\n\t\t\t.replace(/__ID__/g, item.id)\n\t\t\t.replace(/__PAGE_ID__/g, item.page_id)\n\t\t\t.replace(/__TEXT__/g, item.text || '')\n\t\t\t.replace(/__URL__/g, item.url || '')\n\t\t\t.replace(/checked=\"__BLANK__\"/g, item.blank ? 'checked' : '')\n\t\t\t.replace(/checked=\"__OBFUSCATE__\"/g, item.obfuscate ? 'checked' : '')\n\t\t\t.replace(/__DATA_ID__/g, item.data['id'] || '')\n\t\t\t.replace(/__DATA_CLASS__/g, item.data['class'] || '');\n\n\t\t$newNavItem = $(newNavItem);\n\n\t\t// Ajouter au body\n\t\t$menuSortable.append($newNavItem);\n\t\t// Afficher la bonne tab\n\t\t$newNavItem.find('.tabs-leads-to a[data-toggle=\"tab\"][data-leads-to=' + item.leadsTo + ']').tab('show');\n\t\t// Changer la valeur de l'input\n\t\t$newNavItem.find('.js-input-page-id').val(item.page_id);\n\n\t\t$menuSortable.nestedSortable('refresh');\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns timeout interval, with some random jitter | function getRandomTimeout () {
return self._intervalMs + Math.floor(Math.random() * self._intervalMs / 5)
} | [
"getTimeout(){cov_50nz68pmo.f[2]++;cov_50nz68pmo.s[6]++;return this.timeout;}",
"function eventDelay() {\n //Randomly select a value from 0 to 1s\n return Math.floor(Math.random() * 1001);\n }",
"function timeUntilActivationTimeout() {\n // use same timeout logic as `@adobe/node-openwhisk-newrelic`: https://github.com/adobe/node-openwhisk-newrelic/blob/master/lib/metrics.js#L38-L44\n return (process.env.__OW_DEADLINE - Date.now()) || DEFAULT_METRIC_TIMEOUT_MS;\n}",
"function getTimeout(timeout) {\n if (!isFinite(timeout) || !util.isPositiveNumber(timeout)) {\n timeout = 0;\n }\n \n return timeout;\n }",
"ms () { return this.now() - this.startMS }",
"function getTokenRefreshTimeout(token) {\n if (token) {\n var decoded = jwt.decode(token);\n\n // expiry date in future?\n if (decoded.exp && 1000 * decoded.exp > Date.now()) {\n // refresh once a day or halfway to expiry\n var timeout = Math.min(24 * 3.6e6, Math.ceil((1000 * decoded.exp - Date.now()) / 2));\n return timeout;\n }\n }\n\n // retry in 1s\n return 1000;\n }",
"resetTimer() {\n this.timer = 0;\n this.spawnDelay = GageLib.math.getRandom(\n this.spawnRate.value[0],\n this.spawnRate.value[1]\n );\n }",
"function randomJitter () {\n if (!d3.select(\"#checkbox-jitter\").node().checked) {\n return 0;\n }\n var jitterRange = JITTER_PERCENT * finishTime;\n return Math.random() * jitterRange - jitterRange / 2;\n }",
"generateTimeSlept()\r\n {\r\n var time = Math.floor((Math.random() * 1) + 1)\r\n console.log(time)\r\n }",
"function randomSleep() {\n return sleep(Math.floor(400 + 400 * Math.random()));\n }",
"function getRandomNum() {\n let time = new Date();\n return time.getMilliseconds();\n}",
"function get_time_allowed_msec(){\n var fpscript = document.getElementById('__fp_bp_is');\n var interval_sec = TIME_ALLOWED_SEC;\n\n if (fpscript){\n if (fpscript.dataset.interval_sec){\n interval_sec = fpscript.dataset.interval_sec;\n }\n }\n console.log(\"=> interval_sec=\", interval_sec);\n\n var interval_msec = (interval_sec * 1000);\n return interval_msec;\n }",
"function setupAwaitTaskTimer(maxIntervalMs, task) {\n setTimeout(function () {\n var c = 0;\n task(function () {\n c++;\n if (c === 1) {\n setupAwaitTaskTimer(maxIntervalMs, task);\n }\n });\n }, Math.random() * maxIntervalMs);\n}",
"function getFirstIntervalDelay () {\n\t\tvar now = Date.now();\n\t\tvar queryInterval = queryForecastFreqHrs * 60 * 60 * 1000;\n\t\tvar sinceLastInterval = now % queryInterval;\n\t\treturn (queryInterval - sinceLastInterval + (config.queryDelaySecs * 1000));\t\t\n\t}",
"static get sleepThreshold() {}",
"function getSpawnInterval() {\n return SPAWN_INTERVAL / (\n difficulty == \"easy\" ? EASY_MULTIPLIER : (\n difficulty == \"medium\" ? MEDIUM_MULTIPLIER : (\n difficulty == \"hard\" ? HARD_MULTIPLIER : EASY_MULTIPLIER\n )));\n}",
"getWaitTime(t) {\n let _now = new Date();\n let _then = new Date(parseInt(t));\n let _t = (_now - _then) / 1000;\n let _m = Math.floor(_t / 60);\n let _s = _t - (_m * 60);\n\n _m = this._timeDigit(_m); //pretty strings\n _s = this._timeDigit(_s);\n\n return `${_m}:${_s}`; \n }",
"function generateDelayTime() {\n //console.log(maximumButtonPressInterval + \" is the max, and \" + buttonPressInterval + \" is the min.\");\n var max = (maximumButtonPressInterval - buttonPressInterval) / 1000; /*This is the difference between the minumum and maximum time to press a button. Neessary to make equation simpler.*/\n //console.log(\"The max variable is: \" + max);\n var stretch = 2; /*Arbitrary constant that allows one to stretch the distribution. This effects how drasticly the distribution will favor shorter times.*/\n //console.log(`With all the variables, the equation should be the natural log of the natural exponent of ${stretch} - 1, plus 1 / ${max} , then subtract ${stretch} and then add 1`)\n var horizontalShiftConstant = Math.log(Math.exp(stretch - 1) + (1 / max)) - stretch + 1; /*This is necessary to line up the vertical asymptote.*/\n\n\n if (buttonPressInterval <= 0 || buttonType === \"Undo\" || buttonType === \"Unfollow\") {\n /*Will press Undo or Unfollow buttons every 300 to 500 milliseconds, distributed roughly randomly. We don't need a fancy human-esque delay generator. Facebook doesn't even care if buttons are pressed\n more quickly than this for Undo and Unfollow buttons, but I didn't feel comfortable making it instant.*/\n return 300 + 200 * Math.random();\n } else {\n /*This chunk of code determines the pseudo-random time between button presses. Ideally, this follows a Poisson Distribution, as that would pretty accurately describe the assumptions on this probability problem.\n This will allow some button presses to be exceptionally long and others short because buttonPressInterval is the minimum. The mean has to be much higher. In practice, however, I cannot figure out how to calculate\n the wait time between button presses following that distribution. So instead I invented my own. Call it what it may. It gets the job done. It was invented with some trial and error with a graphing calculator and a\n spreadsheet. It spits out a value between 3000 and 7000, given a random decimal between 0 and 1. We needed something that has a vertical asymptote just after 1, a y-value of 3000 at x=0, a function that is\n everywhere-increasing on the interval of [0,1], that grows really rapidly at the edge, but not rapidly at all near the beginning. I wish I could explain at a mathematical level why it does what we want, but all I\n can say is that it does. I am so sorry to black-box it!*/\n\n //var waitTime = buttonPressInterval + 1000 / (Math.exp(stretch - Math.random() + horizontalShiftConstant) - Math.exp(stretch - 1));\n //console.log(waitTime);\n //console.log(horizontalShiftConstant + \" is the horizontal Shift Constant in this equation\");\n //console.log(buttonPressInterval + \" is the minimum button press wait time in this equation\");\n //console.log(stretch + \" is the stretch variable in this equation\");\n var underBar = (Math.exp(stretch - Math.random() + horizontalShiftConstant) - Math.exp(stretch - 1));\n //console.log(underBar + \" is what 1000 is divided by in this equation\");\n\n return buttonPressInterval + 1000 / (Math.exp(stretch - Math.random() + horizontalShiftConstant) - Math.exp(stretch - 1));\n }\n }",
"get maxIdleTime() { return 60 * 60 * 1000; }",
"function getRandomTime(expireTime) {\n\n // get 1/20th of expire time\n var fractionExp = expireTime/20;\n\n // Get a random number between 1 and the fractionExp\n var randomExpireTime = Math.floor(Math.random() * fractionExp) + 1;\n\n if(randomExpireTime < 0) {\n // make a positive number\n randomExpireTime = randomExpireTime * -1;\n }\n\n logger.debug(\"ExpireTime randomized by: \" + randomExpireTime);\n\n var randomMod = randomExpireTime % 2;\n\n if(randomMod == 0) {\n // is an even number so subtract\n return (expireTime - randomExpireTime);\n }\n else if(randomMod == 1) {\n // is an odd so add\n return (expireTime + randomExpireTime);\n }\n else {\n logger.error(\"Error, unable to determine random expire time\");\n // just return what there is\n return expireTime;\n }\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
load list data for card promise | function loadList(cardId, token) {
return new Promise(function (resolve, reject) {
jQuery.get("https://api.trello.com/1/cards/" + cardId + "/list?key="+key+"&token=" + token, function (listData) {
resolve(listData);
});
});
} | [
"async loadCards() {\n await JsonPlaceholder.get(\"/posts\", {\n params: {\n _start: this.props.cardList.length + 1,\n },\n })\n .then((res) => {\n this.props.fetchCardsSuccess({\n loadMore: !(res.data.length < 10),\n cardList: res.data,\n });\n })\n .catch((err) => {\n this.props.fetchCardsFailed();\n });\n }",
"async function _getCardsAPI() {\r\n try {\r\n const data = await fetch(\"https://api.pokemontcg.io/v1/cards\");\r\n if (!data) throw new Error();\r\n const cards = await data.json();\r\n const cardsData = await [...Object.values(cards)][0];\r\n const names = await cardsData.map((card) => card.name).sort();\r\n\r\n names.forEach(function (name) {\r\n const html = `<button type= \"button\" class=\"cardButton\" id=\"${name.toLowerCase()}\">${name}</button>`;\r\n listContainer.insertAdjacentHTML(\"beforeend\", html);\r\n\r\n // Save cards data into the local storage. This avoid having to make an AJAX call for each card button click. Saving it into a local storage is not really a good practice as the file is not safe. I do not know how to use Redux...yet!\r\n const save = JSON.stringify(cardsData);\r\n localStorage.setItem(\"cardsData\", save);\r\n\r\n return cardsData;\r\n });\r\n } catch (err) {\r\n _errorMsg(listContainer);\r\n listContainer.style.display = \"none\";\r\n cardInfo.style.display = \"none\";\r\n back.addEventListener(\"click\", _errorMsg(cardPage));\r\n console.log(err);\r\n }\r\n}",
"function initCards() {\n let cards = [];\n //TODO: FIX\n for (let i = 0; i < count; i++) {\n cards.push(JSON.parse(localStorage.getItem(`cards-${i}`)));\n }\n console.log(cards);\n\n for (let card of cards) {\n if (card == null) {\n continue;\n }\n createCard(\n card.selectOptionType,\n card.inputCardNumber,\n card.formatedDate,\n card.id,\n true\n );\n }\n}",
"fetchCards() {\n fetch(CARDS_URL).then(response => {\n return response.json();\n }).then(data => {\n this.setState({ cards: data });\n });\n }",
"function load_customer_list() {\n\t\t\n\t\t//track starting function\n\t\t//console.log('loading the customer list');\n\t\t\n\t\t//gather the data\n\t\tfirebaseService.get.customer_list().then(function success(s) {\n\t\t\t\n\t\t\t//console.log('got this respons', s);\n\t\t\t\n\t\t\t//when the list has been loaded update the variables\n\t\t\t//vm.customerList = s;\n\t\t\tvm.customerList = $firebaseArray(firebase.database().ref().child('customers').child('customer_list'));\n\n\t\t\t//reflect the changes\n\t\t\t$scope.$apply();\n\n\t\t}).catch(function error(e) {\n\t\t\t//if there was an error throw the error\n\t\t\tconsole.log('error');\n\t\t});\n\t}",
"async getList() {\n const data = await this.getData();\n return data.map(tour => {\n return {\n title: tour.title,\n shortname: tour.shortname,\n summary: tour.summary,\n card: tour.card\n };\n });\n }",
"function loadList() {\n var begin = ((currentPage - 1) * numberPerPage);\n var end = begin + numberPerPage;\n\n pageList = hotelsArr.slice(begin, end);\n getDetails();\n check();\n}",
"function load() {\n numOfPages();\n loadList();\n}",
"loadAvailableItems() {\n // Load the available items and parses the data\n var tempList = lf.getAvailableItems();\n tempList.then((value) => {\n // Get the items, their ids, and data\n var items = value.items;\n var ids = value.ids;\n var genNames = value.genNames;\n\n // Save the item information\n var temp = [];\n for (var i = 0; i < ids.length; i++) {\n temp.push({\n name: items[i],\n title: items[i],\n id: ids[i],\n genName: genNames[i]\n });\n }\n\n // Add the option to register a new item to the list\n temp.push({ name: NEW_ITEM, title: NEW_ITEM, id: -1 });\n\n availableItems = temp;\n });\n }",
"fetchContactList() {\n\t\tfetchContacts({ accountIds : this.recordId })\n\t\t.then(result => {\n\t\t\tthis.contactList = result;\n\t\t\tthis.error = undefined;\n\n\t\t}) .catch(error => {\n\t\t\tthis.error = error;\n\t\t\tthis.contactList = undefined;\n\t\t});\n\t}",
"loadItemData() {\n this.setState({ loading: true });\n console.log(\"Loading item data\");\n fetch(SERVICE_URL + \"/items\")\n .then((data) => data.json())\n .then((data) => this.setState({ itemData: data, loading: false }));\n }",
"function load() {\n dashBoardService.getDashboardData().success(function(data) {\n var formatData = [];\n _.forEach(data, function(elem) {\n try {\n formatData.push({id: elem._id, title: elem._id.title, ip: elem._id.ip, count: elem.count, last: moment(elem.lastEntry).fromNow(), down: elem.timeIsOver});\n } catch (err) {\n console.log(err);\n }\n });\n vm.data = formatData;\n\n }).error( function(data, status, headers) {\n alert('Error: ' + data + '\\nHTTP-Status: ' + status);\n });\n }",
"loadList(listId) {\n //finds list\n let listIndex = -1;\n for (let i = 0; (i < this.toDoLists.length) && (listIndex < 0); i++) {\n if (this.toDoLists[i].id === listId)\n listIndex = i;\n }\n //loads this list\n if (listIndex >= 0) {\n let listToLoad = this.toDoLists[listIndex];\n this.setCurrentList(listToLoad);\n //this.currentList = listToLoad;//change to set current list\n this.view.viewList(this.currentList);\n this.view.refreshLists(this.toDoLists);\n //set currentlist \n }\n this.tps.clearAllTransactions();\n this.buttonCheck();\n }",
"ListOfCreditCards() {\n let url = `/me/paymentMean/creditCard`;\n return this.client.request('GET', url);\n }",
"async function getProductList() {\n\n await fetch('http://52.26.193.201:3000/products/list')\n .then(response => response.json())\n .then(response => setProductList([...response]))\n }",
"load() {\n\n this.cars = []\n //readFile(this.fileName).then(function(data){console.log(data)}) //2.We are reading the file because we are using promisify\n readFile(this.fileName, 'utf8')\n //.then(data => console.log(typeof data))\n .then(data => JSON.parse(data)) //3.JSON.parse is converting text into jSON data and push/add the content to the list of cars\n .then(carsList => { //4. then we are looping the array of objects and add each object into the list of cars.\n //console.log('before', this.cars)\n carsList.forEach(car => {\n // this.cars.push(car)\n this.add(new Car(car))\n })\n //console.log('after', this.cars)\n })\n\n }",
"function getFolUp() {\n $.get(\"/api/followup\", function(data) {\n console.log(\"FollowUp\", data);\n folUpCards = data;\n if (!folUpCards || !folUpCards.length) {\n displayEmpty();\n }\n else {\n initializeCards();\n }\n })\n .then(function() {\n })\n }",
"function loadList(data, header, title, itemFunc, itemBind) {\n $('#list-description').text(header);\n $('#list-name').text(title);\n $('#list-list li[data-role!=list-divider]').remove(); \n\n var list = $('#list-list');\n $.each(data, function(index, car) {\n var link = $('<a />').text(itemFunc(car)); \n link.bind('tap', itemBind(car));\n list.append($('<li />').append(link));\n });\n\n $.mobile.hidePageLoadingMsg();\n $.mobile.changePage($('#list'));\n list.listview('refresh');\n}",
"function addCardAppData(e) {\n\n// const listId =e.target.closest('.oneLists').getAttribute('data-id');\n\n // const listInAppData2 = appData.lists.board.find((list)=> listId === list.id);\n\n //\n // const cardOfAppData = {\n // members: [],\n // text: 'Add new task',\n // id: newCard.getAttribute(\"data-id\"),\n // }\n // listInAppData2.tasks.push(cardOfAppData);\n\n const title = e.target.closest('.oneLists').querySelector('.tagText').textContent\n const id =e.target.closest('.oneLists').getAttribute('data-id');\n\n const listInAppData =returnListReference(id)\n // appData.lists.board.find((bord) => id === bord.id)\n const cardId= e.target.closest('.oneLists').querySelector('.ulForCards li:last-child');\n\n const cardOfAppData = {\n members: [],\n text: 'Add new task',\n id: cardId.getAttribute('data-id'),\n }\n listInAppData.tasks.push(cardOfAppData)\n //pushnigNewCard(listInAppData, cardId);\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
FUNCTION: initValues() DESCRIPTION: This function is called in the inspectSelection() event. It is responsible for initializing all the components in the UI with default values. ARGUMENTS: none RETURNS: nothing | function initValues() {
NAME.value = "";
// FROM
ACTION.value = "";
TARGET.setIndex(0);
METHOD.setIndex(0);
ENCTYPE.setIndex(0);
FORMAT.pickValue('');
STYLE.value = '';
SKIN.pickValue('');
PRESERVEDATA.pickValue('');
SCRIPTSRC.value = '';
ARCHIVE.value = ''
HEIGHT.value = '';
WIDTH.value = '';
} | [
"function initialSliderValues() {\n\t// set initial values for config\n\tupdateSliderValue('cannyConfigThreshold1Slider',\n\t\t\t'cannyConfigThreshold1Textbox');\n\tupdateSliderValue('cannyConfigThreshold2Slider',\n\t\t\t'cannyConfigThreshold2Textbox');\n\tupdateSliderValue('houghConfigRhoSlider', 'houghConfigRhoTextbox');\n\tupdateSliderValue('houghConfigThetaSlider', 'houghConfigThetaTextbox');\n\tupdateSliderValue('houghConfigThresholdSlider',\n\t\t\t'houghConfigThresholdTextbox');\n\tupdateSliderValue('houghConfigMinLineLengthSlider',\n\t\t\t'houghConfigMinLineLengthTextbox');\n\tupdateSliderValue('houghConfigMaxLineGapSlider',\n\t\t\t'houghConfigMaxLineGapTextbox');\n\tupdateSliderValue('houghConfigMaxLineGapSlider',\n\t\t\t'houghConfigMaxLineGapTextbox');\n\n\t// set initial values for cam config\n\tupdateSliderValue('camEcSlider', 'camEcTextbox');\n\tupdateSliderValue('camBrSlider', 'camBrTextbox');\n\tupdateSliderValue('camSaSlider', 'camSaTextbox');\n}",
"_initializeGameValues() {\n this.currentFPS = GameConfig.STARTING_FPS;\n this.scoreBoard.resetScore();\n\n this.player = new Player(this.gameView.getPlayerName(), \"white\");\n this.food = new Food(this.boardView.getRandomCoordinate(this.player.segments), \"lightgreen\");\n this.gameView.hideChangeNameButton();\n }",
"function setSavedQueryValuesForControls() {\n argument_values = JSON.parse($('#update_arguments_form #argument_values').val())\n if (argument_values) {\n for (var argument_id in argument_values) {\n var current_value = argument_values[argument_id][\"value\"];\n if (current_value) {\n my_finder = '#script_argument_' + argument_id;\n my_selector = $(my_finder);\n if (my_selector) {\n my_selector.val(current_value)\n my_selector.attr('arg_val', current_value);\n }\n\n my_selector = $('#tree_renderer_' + argument_id);\n if (my_selector) {\n my_selector.attr('arg_val', current_value);\n }\n }\n }\n }\n}",
"function renderValues() {\n renderInitialValues(initialPhysicValues);\n renderInitialValues(resultPhysicValues);\n}",
"function initializeSliders() {\n rowSlider.value = num_rows;\n colSlider.value = num_cols;\n rowOutput.innerText = num_rows;\n colOutput.innerText = num_cols;\n document.getElementById(\"settings-sliders\").style.display = \"none\";\n}",
"function values(){\n\t\treturn selection;\n\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 initColorsSelectBox() {\n\tvar SelectNode = document.getElementById(\"ColorSet\");\n\tvar colorSetKeys = Object.keys(colorSetsObj);\n\tvar key;\n\tfor (key in colorSetKeys) {\n\t\tvar option = document.createElement(\"option\");\n\t\toption.value = colorSetKeys[key];\n\t\toption.text = colorSetsObj[colorSetKeys[key]].picker_label;\n\t\tSelectNode.add(option);\n\t}\n}",
"function setupColorControls()\n{\n dropper.onclick = () => setDropperActive(!isDropperActive()) ;\n color.oninput = () => setLineColor(color.value);\n colortext.oninput = () => setLineColor(colortext.value);\n\n //Go find the origin selection OR first otherwise\n palettedialog.setAttribute(\"data-palette\", getSetting(\"palettechoice\") || Object.keys(palettes)[0]);\n\n palettedialogleft.onclick = () => { updatePaletteNumber(-1); refreshPaletteDialog(); }\n palettedialogright.onclick = () => { updatePaletteNumber(1); refreshPaletteDialog(); }\n refreshPaletteDialog();\n}",
"function setValuesVisibility() {\n lodash.forEach(ctrl.sortOptions, function (value) {\n lodash.defaults(value, {visible: true});\n });\n }",
"function init() {\n utilsService.addDropdownOptions('from-currency', availableCurrencies);\n document.getElementById('amount').value = defaultAmount;\n getRates(selectedBase);\n}",
"function setSelectionsFromSlotValue() {\n\t\t// $log.log(preDebugMsg + \"setSelectionsFromSlotValue\");\n\t\tvar slotSelections = $scope.gimme(\"InternalSelections\");\n\t\tif(typeof slotSelections === 'string') {\n\t\t\tslotSelections = JSON.parse(slotSelections);\n\t\t}\n\n\t\tif(JSON.stringify(slotSelections) == JSON.stringify(internalSelectionsInternallySetTo)) {\n\t\t\t// $log.log(preDebugMsg + \"setSelectionsFromSlotValue got identical value\");\n\t\t\treturn;\n\t\t}\n\n\t\tif(slotSelections.hasOwnProperty(\"selections\")) {\n\t\t\tvar newSelections = [];\n\n\t\t\tif(unique > 0) {\n\t\t\t\tfor(var sel = 0; sel < slotSelections.selections.length; sel++) {\n\t\t\t\t\tvar newSel = slotSelections.selections[sel];\n\t\t\t\t\tvar X1 = newSel.minX;\n\t\t\t\t\tvar X2 = newSel.maxX;\n\n\t\t\t\t\tif(X2 < limits.minX || X1 > limits.maxX) {\n\t\t\t\t\t\t// completely outside\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tX1 = Math.max(limits.minX, X1);\n\t\t\t\t\tX2 = Math.min(limits.maxX, X2);\n\n\t\t\t\t\tvar x1 = legacyDDSupLib.val2pixelX(X1, unique, drawW, leftMarg, limits.minX, limits.maxX);\n\t\t\t\t\tvar x2 = legacyDDSupLib.val2pixelX(X2, unique, drawW, leftMarg, limits.minX, limits.maxX);\n\t\t\t\t\tif(x2 - x1 > 1) {\n\t\t\t\t\t\tnewSelections.push([X1,X2, x1,x2]);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\t// $log.log(preDebugMsg + \"setSelectionsFromSlotValue ignoring selection because it is too small.\");\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// $log.log(preDebugMsg + \"new selections: \" + JSON.stringify(newSelections));\n\t\t\t\tif(newSelections.length > 0) {\n\t\t\t\t\tselections = newSelections;\n\t\t\t\t\tupdateLocalSelections(false);\n\t\t\t\t\tdrawSelections();\n\t\t\t\t}\n\t\t\t}\n\t\t\telse { // no data\n\t\t\t\tfor(var sel = 0; sel < slotSelections.selections.length; sel++) {\n\t\t\t\t\tvar newSel = slotSelections.selections[sel];\n\t\t\t\t\tvar X1 = newSel.minX;\n\t\t\t\t\tvar X2 = newSel.maxX;\n\n\t\t\t\t\tnewSelections.push([X1,X2, 0,0]);\n\t\t\t\t}\n\t\t\t\tselections = newSelections;\n\t\t\t}\n\t\t}\n\t\tsaveSelectionsInSlot();\n\t}",
"_setDataToUI() {\n const data = this._data;\n if (data === undefined) return;\n console.log('View#_setDataToUI', this);\n\n if (data instanceof Object) {\n eachEntry(data, ([name, val]) => this._setFieldValue(name, val));\n } else {\n this._setVal(this.el, data);\n }\n }",
"function loadMethods(values) {\n\trequire([\"dojo/ready\", \"dijit/form/MultiSelect\", \"dijit/form/Button\", \"dojo/dom\", \"dojo/_base/window\"], function(ready, MultiSelect, Button, dom, win){\n\t\tready(function(){\n\t\t\tif (methodsMultiSelect != null) methodsMultiSelect.destroyRecursive(true);\n\t\t\tselMethods = dom.byId('selectMethods');\n\t\t\tselMethods.innerHTML = '';\n\t\t\t$.each(values, function(i, val) {\n\t\t\t\tvar c = win.doc.createElement('option');\n\t\t\t\tc.innerHTML = val;\n\t\t\t\tc.value = val;\n\t\t\t\tselMethods.appendChild(c);\n\t\t\t});\n\t\t\tmethodsMultiSelect = new MultiSelect({ name: 'selectMethods', value: '' }, selMethods);\n\t\t\tmethodsMultiSelect.watch('value', function () {\n\t\t\t\tvar selValues = methodsMultiSelect.get('value');\n\t\t\t\t$('#analysisSpecifications').css('display', 'none');\n\t\t\t\t$('#statusQueryWrapperDiv').css('display', 'none');\n\t\t\t\t$('#queryDiv').css('display', 'none');\n\t\t\t\tif (selValues != null) { \n\t\t\t\t\tif (selValues.length == 1) {\n\t\t\t\t\t\tif (selValues[0] == emptySelectionString) {\n\t\t\t\t\t\t\tmethodsMultiSelect.set('value', '');\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\trenderAvailableParameters();\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (selValues.length > 1) {\n\t\t\t\t\t\tmethodsMultiSelect.set('value', '');\n\t\t\t\t\t}\n\t\t\t\t} \n\t\t\t});\n\t\t\tmethodsMultiSelect.startup();\n\t\t});\n\t});\n}",
"function setNodeSelectorsDefaultValue() {\n ctrl.nodeSelectors = lodash.chain(ConfigService)\n .get('nuclio.defaultFunctionConfig.attributes.spec.nodeSelector', [])\n .map(function (value, key) {\n return {\n name: key,\n value: value,\n ui: {\n editModeActive: false,\n isFormValid: key.length > 0 && value.length > 0,\n name: 'nodeSelector'\n }\n };\n })\n .value();\n }",
"function init() {\n\n // reset any previous data\n displayReset();\n\n // read in samples from JSON file\n d3.json(\"data/samples.json\").then((data => {\n\n\n // ********** Dropdown Menu ************// \n\n // Iterate over each name in the names array to populate dropdowns with IDs\n data.names.forEach((name => {\n var option = idSelect.append(\"option\");\n option.text(name);\n })); //end of forEach loop\n\n // get the first ID from the list as a default value for chart\n var initId = idSelect.property(\"value\")\n\n // plot charts with initial ID\n displayCharts(initId);\n\n }));\n }",
"function init()\n {\n //Recursive deep copy of passing in options matching them against the defaults\n base.options = $.extend(true, {}, $.fn.grating.defaultOptions, options);\n base.$elems.each(function(key, value)\n {\n var _this = this;\n _this.$this = $(this);\n _this.$this.data(\"data-clickCount\", 0);\n\n var count = GetElementCount(_this.$this);\n var character = GetCharacter(_this.$this);\n var required = GetRequired(_this.$this);\n var errorText = GetValidationErrorText(_this.$this);\n /* Check if this is an instantiation of an already initilised element if so exit the init function allowing the caller to chain requests without holding onto a variable */\n if(_this.$this.children(base.options.elementType).length == count)\n {\n return;\n }\n var frag = $(document.createDocumentFragment());\n /* Add components to the parent to enable validation */\n var id = \"gRating_validation_input_for_\" + getUniqueId(_this.$this, key);\n var inputElement = $(\"<input type='hidden' id='\"+id+\"' name='\"+id+\"' data-error=\\\"\"+errorText+\"\\\">\");\n if(required)\n {\n inputElement.attr(\"data-validate\", \"true\");\n inputElement.addClass(base.options.formValidationClass);\n inputElement.attr(\"required\", \"required\");\n inputElement.attr(\"data-minlength\", \"1\");\n var helpBlock = $(\"<div class='help-block with-errors'></div>\");\n frag.append(helpBlock);\n }\n frag.append(inputElement);\n for (var i = 1; i < count + 1; i++)\n {\n var characterValue = typeof character === \"function\" ? GetAwesomeIcon(character(i - 1)) : character;\n\n var element = $(\"<\"+base.options.elementType+\">\" + characterValue + \"</\"+base.options.elementType+\">\");\n element.data(\"data-count\", i);\n frag.append(element);\n }\n _this.$this.append(frag);\n var children = _this.$this.children(base.options.elementType);\n children.css(base.options.ratingCss);\n /* Hover function if enabled switches between hover and non hover css states */\n children.hover(function(e)\n {\n if(IsEnabled(_this.$this))\n {\n if(e.type === \"mouseenter\")\n $(this).css(base.options.ratingHoverCss);\n else\n $(this).css(base.options.ratingCss);\n }\n });\n /* Mouse enter for highlighting character under cursor */\n children.mouseenter(function()\n {\n if(IsEnabled(_this.$this))\n populateRatingElements(_this.$this, $(this).data(\"data-count\"));\n });\n /* Click handler for selecting a character if allowed by clicklimit and enabled state */\n children.click(function()\n {\n if(IsEnabled(_this.$this))\n {\n //Increment the Click counter\n _this.$this.data(\"data-clickCount\", parseInt(_this.$this.data(\"data-clickCount\")) + 1);\n //Check if we have a Click Limit and if so whether we've exceeded it, if we have cancel the click event\n if(HasExceededclicklimit(_this.$this))\n {\n //Set disabled state and remove modified cursor if we have exceeded our click limit\n _this.$this.attr('disabled', 'disabled');\n _this.$this.children(base.options.elementType).css('cursor', 'default');\n return;\n }\n var value = $(this).data(\"data-count\");\n // If clicked on the same star again unselect all stars, otherwise there is no way to go to 0 stars after a value had been previously selected\n var deselectable = GetDeselectable(_this.$this);\n if(deselectable && _this.$this.attr(\"value\") == value)\n {\n value = 0;\n }\n _this.$this.attr(\"value\", value);\n\n /* Set the input field to the current value too, remove it if 0 to allow for validation errors */\n if(value == 0)\n inputElement.removeAttr(\"value\");\n else\n inputElement.attr(\"value\", value);\n\n populateRatingElements(_this.$this, value);\n\n if(typeof base.options.callback === \"function\")\n base.options.callback(_this.$this, value);\n }\n });\n /* Mouseleave on parent element reset back to last clicked element */\n _this.$this.mouseleave(function()\n {\n if(IsEnabled(_this.$this))\n populateRatingElements(_this.$this, _this.$this.attr(\"value\"));\n });\n /* Set initial value for rating */\n var value = GetValue(_this.$this, count);\n _this.$this.attr(\"value\", value);\n\n /* Only add a value if its above 0 so we can trigger validation errors */\n if(value > 0)\n inputElement.attr(\"value\", value);\n\n /* Draw the rating with the preselected value visible */\n populateRatingElements(_this.$this, value);\n\n /* If the parent is disabled default the mouseover icon to the correct state */\n if(IsEnabled(_this.$this) == false)\n {\n _this.$this.children(base.options.elementType).css('cursor', 'default');\n }\n });\n }",
"function initSelection() {\n canvas.on({\n \"selection:created\": function __listenersSelectionCreated() {\n global.console.log(\"**** selection:created\");\n setActiveObject();\n toolbar.showActiveTools();\n },\n \"before:selection:cleared\": function __listenersBeforeSelectionCleared() {\n global.console.log(\"**** before:selection:cleared\");\n },\n \"selection:cleared\": function __listenersSelectionCleared() {\n global.console.log(\"**** selection:cleared\");\n toolbar.hideActiveTools();\n },\n \"selection:updated\": function __listenersSelectionUpdated() {\n global.console.log(\"**** selection:updated\");\n setActiveObject();\n toolbar.showActiveTools();\n },\n });\n}",
"initDefaultSelectInfo() {\n const {\n type: chartType,\n selectLabel,\n selectSeries,\n } = this.options;\n\n if (selectLabel.use) {\n let targetAxis = null;\n if (chartType === 'heatMap' && selectLabel?.useBothAxis) {\n targetAxis = this.defaultSelectInfo?.targetAxis;\n }\n\n this.defaultSelectInfo = !this.defaultSelectInfo?.dataIndex\n ? { dataIndex: [], label: [], data: [] }\n : this.getSelectedLabelInfoWithLabelData(this.defaultSelectInfo.dataIndex, targetAxis);\n }\n\n if (selectSeries.use && !this.defaultSelectInfo) {\n this.defaultSelectInfo = { seriesId: [] };\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Goals: entrypoint for collecting modules and for compilation dynamic import wrapped in exported fuction prevents executing sideeffects early eager import, bundled in main chunk | async function main() {
return [Promise.resolve(/*! import() eager */).then(__webpack_require__.bind(__webpack_require__, /*! ./all-imports.js */ "./src/all-imports.js"))];
} | [
"async function buildShims() {\n // Install a package.json file in BUILD_DIR to tell node.js that the\n // .js files therein are ESM not CJS, so we can import the\n // entrypoints to enumerate their exported names.\n const TMP_PACKAGE_JSON = path.join(BUILD_DIR, 'package.json');\n await fsPromises.writeFile(TMP_PACKAGE_JSON, '{\"type\": \"module\"}');\n\n // Import each entrypoint module, enumerate its exports, and write\n // a shim to load the chunk either by importing the entrypoint\n // module or by loading the compiled script.\n await Promise.all(chunks.map(async (chunk) => {\n const modulePath = posixPath(chunk.moduleEntry ?? chunk.entry);\n const scriptPath =\n path.posix.join(RELEASE_DIR, `${chunk.name}${COMPILED_SUFFIX}.js`);\n const shimPath = path.join(BUILD_DIR, `${chunk.name}.loader.mjs`);\n const parentImport =\n chunk.parent ?\n `import ${quote(`./${chunk.parent.name}.loader.mjs`)};` :\n '';\n const exports = await import(`../../${modulePath}`);\n\n await fsPromises.writeFile(shimPath,\n `import {loadChunk} from '../tests/scripts/load.mjs';\n${parentImport}\n\nexport const {\n${Object.keys(exports).map((name) => ` ${name},`).join('\\n')}\n} = await loadChunk(\n ${quote(modulePath)},\n ${quote(scriptPath)},\n ${quote(chunk.scriptExport)},\n);\n`);\n }));\n\n await fsPromises.rm(TMP_PACKAGE_JSON);\n}",
"enterModularCompilation(ctx) {\n\t}",
"async function main () {\n // cjs\n await esbuild.build({\n entryPoints: ['src/index.mjs'],\n bundle: false,\n keepNames: true,\n format: 'cjs',\n outfile: path.join('./dist/', 'index.cjs'),\n platform: 'browser'\n })\n\n // esm\n // await esbuild.build({\n // entryPoints: ['src/index.js'],\n // bundle: false,\n // keepNames: true,\n // format: 'esm',\n // outfile: path.join('./dist/', 'index.mjs'),\n // platform: 'browser'\n // })\n}",
"call(context) {\n context = this.dmp.getContextById(context);\n if (context) {\n // step through the imported modules and run any that have a default function.\n // some modules take effect simply by importing them (e.g. CSS), but other\n // modules export a function that needs to be called (e.g. JS). The function is\n // required because importing only runs the first time it's imported. If a template\n // is included more than once in a request (such as <%include> in a for loop), the\n // JS should run once for each time it's included. Hence a default exported function.\n for (let module of this.modules) {\n if (module && module.default && module.default.apply) {\n module.default.apply(context, [ context.values ]);\n }\n }\n }\n }",
"enterStaticImportOnDemandDeclaration(ctx) {\n\t}",
"async function bootstrap() {\n\n // Load the WebAssembly Module\n // https://developer.mozilla.org/en-US/docs/WebAssembly/JavaScript_interface/instantiateStreaming\n const result = await WebAssembly.instantiateStreaming(\n fetch(\"lvglwasm.wasm\"),\n importObject\n );\n\n // Store references to WebAssembly Functions and Memory exported by Zig\n wasm.init(result);\n\n // Start the Main Function\n main();\n}",
"function bootstrap() {\n var winston = require('winston');\n var logger = winston.loggers.get('logger');\n logger.info(\"Loading modules...\");\n return require('./ia_module_loader')(ia_interface, iaPath)\n .then(function (loadedModules) {\n return require(\"./ia_solver\")(loadedModules);\n })\n .then(function (ia_solver) {\n return require(\"./app\")(app, ia_solver);\n });\n}",
"static GetImporters() {}",
"_compile(content, filename, filename2) {\n\n content = internalModule.stripShebang(content);\n\n // create wrapper function\n var wrapper = Module.wrap(content);\n\n var compiledWrapper = vm.runInThisContext(wrapper, {\n filename: filename,\n lineOffset: 0,\n displayErrors: true\n });\n\n var inspectorWrapper = null;\n if (process._breakFirstLine && process._eval == null) {\n if (!resolvedArgv) {\n // we enter the repl if we're not given a filename argument.\n if (process.argv[1]) {\n resolvedArgv = Module._resolveFilename(process.argv[1], null, false);\n } else {\n resolvedArgv = 'repl';\n }\n }\n\n // Set breakpoint on module start\n if (filename2 === resolvedArgv) {\n delete process._breakFirstLine;\n inspectorWrapper = process.binding('inspector').callAndPauseOnStart;\n if (!inspectorWrapper) {\n const Debug = vm.runInDebugContext('Debug');\n Debug.setBreakPoint(compiledWrapper, 0, 0);\n }\n }\n }\n var dirname = path.dirname(filename);\n var require = internalModule.makeRequireFunction(this);\n var result;\n if (inspectorWrapper) {\n result = inspectorWrapper(compiledWrapper, this.exports, this.exports,\n require, this, filename, dirname, require.resolve);\n } else {\n result = compiledWrapper.call(this.exports, this.exports, require, this,\n filename, dirname, require.resolve);\n }\n return result;\n }",
"async function bootstrap() {\n\n // Load the WebAssembly Module\n // https://developer.mozilla.org/en-US/docs/WebAssembly/JavaScript_interface/instantiateStreaming\n const result = await WebAssembly.instantiateStreaming(\n fetch(\"feature-phone.wasm\"),\n importObject\n );\n\n // Store references to WebAssembly Functions and Memory exported by Zig\n wasm.init(result);\n\n // Start the Main Function\n main();\n}",
"function runModule() {\n const path = $('body').data('route');\n try {\n require(`./sections/${path}`).default($(document.body));\n } catch (err) {\n // Just ignores error for now.\n console.error(err);\n }\n}",
"function chunkWrapper(chunk) {\n // Each chunk can have only a single dependency, which is its parent\n // chunk. It is used only to retrieve the namespace object, which\n // is saved on to the exports object for the chunk so that any child\n // chunk(s) can obtain it.\n\n // JavaScript expressions for the amd, cjs and browser dependencies.\n let amdDepsExpr = '';\n let cjsDepsExpr = '';\n let scriptDepsExpr = '';\n // Arguments for the factory function.\n let factoryArgs = '';\n // Expression to get or create the namespace object.\n let namespaceExpr = `{}`;\n\n if (chunk.parent) {\n const parentFilename =\n JSON.stringify(`./${chunk.parent.name}${COMPILED_SUFFIX}.js`);\n amdDepsExpr = parentFilename;\n cjsDepsExpr = `require(${parentFilename})`;\n scriptDepsExpr = `root.${chunk.parent.scriptExport}`;\n factoryArgs = '__parent__';\n namespaceExpr = `${factoryArgs}.${NAMESPACE_PROPERTY}`;\n }\n\n // Code to save the chunk's exports object at chunk.scriptExport and\n // additionally save individual named exports as directed by\n // chunk.scriptNamedExports.\n const scriptExportStatements = [\n `root.${chunk.scriptExport} = factory(${scriptDepsExpr});`,\n ];\n for (var location in chunk.scriptNamedExports) {\n const namedExport = chunk.scriptNamedExports[location];\n scriptExportStatements.push( \n `root.${location} = root.${chunk.scriptExport}.${namedExport};`);\n }\n\n // Note that when loading in a browser the base of the exported path\n // (e.g. Blockly.blocks.all - see issue #5932) might not exist\n // before factory has been executed, so calling factory() and\n // assigning the result are done in separate statements to ensure\n // they are sequenced correctly.\n return `// Do not edit this file; automatically generated.\n\n/* eslint-disable */\n;(function(root, factory) {\n if (typeof define === 'function' && define.amd) { // AMD\n define([${amdDepsExpr}], factory);\n } else if (typeof exports === 'object') { // Node.js\n module.exports = factory(${cjsDepsExpr});\n } else { // Script\n ${scriptExportStatements.join('\\n ')}\n }\n}(this, function(${factoryArgs}) {\nvar ${NAMESPACE_VARIABLE}=${namespaceExpr};\n%output%\n${chunk.exports}.${NAMESPACE_PROPERTY}=${NAMESPACE_VARIABLE};\nreturn ${chunk.exports};\n}));\n`;\n}",
"function program(impl) {\n return function(flagDecoder) {\n return function(object, moduleName, debugMetadata) {\n object.start = function start(onAppReady) {\n return makeComponent(impl, onAppReady);\n };\n };\n };\n }",
"loadApp() {\n if (fs.existsSync(this.mainDir)) {\n eachDir(this.mainDir, (dirname) => {\n let dir = path.join(this.mainDir, dirname);\n let type = singularize(dirname);\n\n glob.sync('**/*', { cwd: dir }).forEach((filepath) => {\n let modulepath = withoutExt(filepath);\n if (filepath.endsWith('.js')) {\n let Class = require(path.join(dir, filepath));\n Class = Class.default || Class;\n this.container.register(`${ type }:${ modulepath }`, Class);\n } else if (filepath.endsWith('.json')) {\n let mod = require(path.join(dir, filepath));\n this.container.register(`${ type }:${ modulepath }`, mod.default || mod);\n }\n });\n });\n }\n }",
"function initModuleVarsFn () {\n var\n exe_list = [ 'git', 'patch' ],\n exe_count = exe_list.length,\n promise_list = [],\n idx, exe_key, bound_fn, promise_obj;\n\n // Bail if node version < versReqInt\n if ( Number( versList[0] ) < versReqInt ) {\n logFn( 'As of hi_score 1.2+ NodeJS v'\n + versReqInt + ' is required.'\n );\n logFn( 'NodeJS Version ' + versList.join('.') + ' is installed.' );\n logFn( 'Please upgrade NodeJS and try again.' );\n process.exit( 1 );\n }\n\n // Assign npm module vars\n fqProjDirname = pathObj.dirname( fqBinDirname );\n\n fqGitDirname = fqProjDirname + '/.git';\n fqModuleDirname = fqProjDirname + '/node_modules';\n fqPkgFilename = fqProjDirname + '/package.json';\n fqPatchFilename = fqProjDirname + '/patch/uglify-js-3.0.21.patch';\n\n fqUglyDirname = fqModuleDirname + '/uglifyjs';\n fqScopeFileStr = fqUglyDirname + '/lib/scope.js';\n\n // Assign executable path vars\n for ( idx = 0; idx < exe_count; idx++ ) {\n exe_key = exe_list[ idx ];\n bound_fn = storePathFn.bind( { exe_key : exe_key });\n promise_obj = makeWhichProm( exe_key );\n promise_obj.then( bound_fn ).catch( abortFn );\n promise_list.push( promise_obj );\n }\n\n promiseObj.all( promise_list )\n .then( function () { eventObj.emit( '01ReadPkgFile' ); } )\n .catch( abortFn );\n }",
"function importShader () {\n function createVertexShader (vert) {\n return createShader(require(`../shader/${vert}.vert`), 'vertex')\n }\n\n const noneVs = createVertexShader('nothing')\n\n function createProgram (name, frag, vert = noneVs, prg = prgs) {\n const fs = createShader(require(`../shader/${frag}.frag`), 'fragment')\n prg[name] = new Program(vert, fs)\n if (!prg[name]) throw new Error('program error')\n }\n\n try {\n // video\n createProgram('video', 'video')\n\n // Post Effect\n createProgram('postVideo', 'post/video')\n\n const postVs = createVertexShader('post/post')\n for (const name of POST_LIST) {\n createProgram(name, `post/${name}`, postVs, postPrgs)\n }\n\n // Particle\n createProgram('particleVideo', 'particle/video')\n createProgram('picture', 'particle/picture')\n createProgram('reset', 'particle/reset')\n createProgram('resetVelocity', 'particle/resetVelocity')\n createProgram('position', 'particle/position')\n createProgram('velocity', 'particle/velocity')\n createProgram('particleScene', 'particle/scene', createVertexShader('particle/scene'))\n\n // Pop\n createProgram('popVelocity', 'particle/pop_velocity')\n createProgram('popPosition', 'particle/pop_position')\n createProgram('popScene', 'particle/pop_scene', createVertexShader('particle/pop_scene'))\n\n // render\n createProgram('scene', 'scene', createVertexShader('scene'))\n } catch (error) {\n throw error\n }\n}",
"function register(loader) {\n if (typeof indexOf == 'undefined')\n indexOf = Array.prototype.indexOf;\n if (typeof __eval == 'undefined')\n __eval = eval;\n\n // define exec for easy evaluation of a load record (load.name, load.source, load.address)\n // main feature is source maps support handling\n var curSystem, curModule;\n function exec(load) {\n var loader = this;\n if (load.name == '@traceur') {\n curSystem = System;\n curModule = Module;\n }\n // support sourceMappingURL (efficiently)\n var sourceMappingURL;\n var lastLineIndex = load.source.lastIndexOf('\\n');\n if (lastLineIndex != -1) {\n if (load.source.substr(lastLineIndex + 1, 21) == '//# sourceMappingURL=')\n sourceMappingURL = toAbsoluteURL(load.address, load.source.substr(lastLineIndex + 22, load.source.length - lastLineIndex - 23));\n }\n\n __eval(load.source, loader.global, load.address, sourceMappingURL);\n\n // traceur overwrites System and Module - write them back\n if (load.name == '@traceur') {\n loader.global.traceurSystem = loader.global.System;\n loader.global.System = curSystem;\n //loader.global.Module = curModule;\n }\n }\n loader.__exec = exec;\n\n function dedupe(deps) {\n var newDeps = [];\n for (var i = 0; i < deps.length; i++)\n if (indexOf.call(newDeps, deps[i]) == -1)\n newDeps.push(deps[i])\n return newDeps;\n }\n\n // Registry side table\n // Registry Entry Contains:\n // - deps \n // - declare for register modules\n // - execute for dynamic modules, also after declare for register modules\n // - declarative boolean indicating which of the above\n // - normalizedDeps derived from deps, created in instantiate\n // - depMap array derived from deps, populated gradually in link\n // - groupIndex used by group linking algorithm\n // - module a raw module exports object with no wrapper\n // - evaluated indiciating whether evaluation has happend for declarative modules\n // After linked and evaluated, entries are removed\n var lastRegister;\n function register(name, deps, declare) {\n if (typeof name != 'string') {\n declare = deps;\n deps = name;\n name = null;\n }\n if (declare.length == 0)\n throw 'Invalid System.register form. Ensure setting --modules=instantiate if using Traceur.';\n\n if (!loader.defined)\n loader.defined = {};\n\n lastRegister = {\n deps: deps,\n declare: declare,\n declarative: true,\n };\n\n if (name)\n loader.defined[name] = lastRegister;\n }\n loader.defined = loader.defined || {};\n loader.register = register;\n\n function buildGroups(entry, loader, groups) {\n groups[entry.groupIndex] = groups[entry.groupIndex] || [];\n\n if (indexOf.call(groups[entry.groupIndex], entry) != -1)\n return;\n\n groups[entry.groupIndex].push(entry);\n\n for (var i = 0; i < entry.normalizedDeps.length; i++) {\n var depName = entry.normalizedDeps[i];\n var depEntry = loader.defined[depName];\n \n // not in the registry means already linked / ES6\n if (!depEntry)\n continue;\n \n // now we know the entry is in our unlinked linkage group\n var depGroupIndex = entry.groupIndex + (depEntry.declarative != entry.declarative);\n\n // the group index of an entry is always the maximum\n if (depEntry.groupIndex === undefined || depEntry.groupIndex < depGroupIndex) {\n \n // if already in a group, remove from the old group\n if (depEntry.groupIndex) {\n groups[depEntry.groupIndex].splice(groups[depEntry.groupIndex].indexOf(depEntry), 1);\n\n // if the old group is empty, then we have a mixed depndency cycle\n if (groups[depEntry.groupIndex].length == 0)\n throw new TypeError(\"Mixed dependency cycle detected\");\n }\n\n depEntry.groupIndex = depGroupIndex;\n }\n\n buildGroups(depEntry, loader, groups);\n }\n }\n\n function link(name, loader) {\n var startEntry = loader.defined[name];\n\n startEntry.groupIndex = 0;\n\n var groups = [];\n\n buildGroups(startEntry, loader, groups);\n\n var curGroupDeclarative = !!startEntry.declarative == groups.length % 2;\n for (var i = groups.length - 1; i >= 0; i--) {\n var group = groups[i];\n for (var j = 0; j < group.length; j++) {\n var entry = group[j];\n\n // link each group\n if (curGroupDeclarative)\n linkDeclarativeModule(entry, loader);\n else\n linkDynamicModule(entry, loader);\n }\n curGroupDeclarative = !curGroupDeclarative; \n }\n }\n\n function linkDeclarativeModule(entry, loader) {\n // only link if already not already started linking (stops at circular)\n if (entry.module)\n return;\n\n // declare the module with an empty depMap\n var depMap = [];\n\n var declaration = entry.declare.call(loader.global, depMap);\n \n entry.module = declaration.exports;\n entry.exportStar = declaration.exportStar;\n entry.execute = declaration.execute;\n\n var module = entry.module;\n\n // now link all the module dependencies\n // amending the depMap as we go\n for (var i = 0; i < entry.normalizedDeps.length; i++) {\n var depName = entry.normalizedDeps[i];\n var depEntry = loader.defined[depName];\n \n // part of another linking group - use loader.get\n if (!depEntry) {\n depModule = loader.get(depName);\n }\n // if dependency already linked, use that\n else if (depEntry.module) {\n depModule = depEntry.module;\n }\n // otherwise we need to link the dependency\n else {\n linkDeclarativeModule(depEntry, loader);\n depModule = depEntry.module;\n }\n\n if (entry.exportStar && indexOf.call(entry.exportStar, entry.normalizedDeps[i]) != -1) {\n // we are exporting * from this dependency\n (function(depModule) {\n for (var p in depModule) (function(p) {\n // if the property is already defined throw?\n Object.defineProperty(module, p, {\n enumerable: true,\n get: function() {\n return depModule[p];\n },\n set: function(value) {\n depModule[p] = value;\n }\n });\n })(p);\n })(depModule);\n }\n\n depMap[i] = depModule;\n }\n }\n\n // An analog to loader.get covering execution of all three layers (real declarative, simulated declarative, simulated dynamic)\n function getModule(name, loader) {\n var module;\n var entry = loader.defined[name];\n\n if (!entry)\n module = loader.get(name);\n\n else {\n if (entry.declarative)\n ensureEvaluated(name, [], loader);\n \n else if (!entry.evaluated)\n linkDynamicModule(entry, loader);\n module = entry.module;\n }\n\n return module.__useDefault ? module['default'] : module;\n }\n\n function linkDynamicModule(entry, loader) {\n if (entry.module)\n return;\n\n entry.module = {};\n\n // AMD requires execute the tree first\n if (!entry.executingRequire) {\n for (var i = 0; i < entry.normalizedDeps.length; i++) {\n var depName = entry.normalizedDeps[i];\n var depEntry = loader.defined[depName];\n if (depEntry)\n linkDynamicModule(depEntry, loader);\n }\n }\n\n // lookup the module name if it is in the registry\n var moduleName;\n for (var d in loader.defined) {\n if (loader.defined[d] != entry)\n continue;\n moduleName = d;\n break;\n }\n\n // now execute\n try {\n entry.evaluated = true;\n var output = entry.execute(function(name) {\n for (var i = 0; i < entry.deps.length; i++) {\n if (entry.deps[i] != name)\n continue;\n return getModule(entry.normalizedDeps[i], loader);\n }\n }, entry.module, moduleName);\n }\n catch(e) {\n throw e;\n }\n \n if (output)\n entry.module = output;\n }\n\n // given a module, and the list of modules for this current branch,\n // ensure that each of the dependencies of this module is evaluated\n // (unless one is a circular dependency already in the list of seen\n // modules, in which case we execute it)\n // then evaluate the module itself\n // depth-first left to right execution to match ES6 modules\n function ensureEvaluated(moduleName, seen, loader) {\n var entry = loader.defined[moduleName];\n\n // if already seen, that means it's an already-evaluated non circular dependency\n if (entry.evaluated || !entry.declarative)\n return;\n\n seen.push(moduleName);\n\n for (var i = 0; i < entry.normalizedDeps.length; i++) {\n var depName = entry.normalizedDeps[i];\n if (indexOf.call(seen, depName) == -1) {\n if (!loader.defined[depName])\n loader.get(depName);\n else\n ensureEvaluated(depName, seen, loader);\n }\n }\n\n if (entry.evaluated)\n return;\n\n entry.evaluated = true;\n entry.execute.call(loader.global);\n delete entry.execute;\n }\n\n var registerRegEx = /System\\.register/;\n\n var loaderFetch = loader.fetch;\n loader.fetch = function(load) {\n var loader = this;\n if (loader.defined && loader.defined[load.name]) {\n load.metadata.format = 'defined';\n return '';\n }\n return loaderFetch(load);\n }\n\n var loaderTranslate = loader.translate;\n loader.translate = function(load) {\n this.register = register;\n\n this.__exec = exec;\n\n load.metadata.deps = load.metadata.deps || [];\n\n // we run the meta detection here (register is after meta)\n return Promise.resolve(loaderTranslate.call(this, load)).then(function(source) {\n \n // dont run format detection for globals shimmed\n // ideally this should be in the global extension, but there is\n // currently no neat way to separate it\n if (load.metadata.init || load.metadata.exports)\n load.metadata.format = load.metadata.format || 'global';\n\n // run detection for register format\n if (load.metadata.format == 'register' || !load.metadata.format && load.source.match(registerRegEx))\n load.metadata.format = 'register';\n return source;\n });\n }\n\n\n var loaderInstantiate = loader.instantiate;\n loader.instantiate = function(load) {\n var loader = this;\n\n var entry;\n \n if (loader.defined[load.name])\n loader.defined[load.name] = entry = loader.defined[load.name];\n\n else if (load.metadata.execute) {\n loader.defined[load.name] = entry = {\n deps: load.metadata.deps || [],\n execute: load.metadata.execute,\n executingRequire: load.metadata.executingRequire // NodeJS-style requires or not\n };\n }\n else if (load.metadata.format == 'register') {\n lastRegister = null;\n \n loader.__exec(load);\n\n // for a bundle, take the last defined module\n // in the bundle to be the bundle itself\n if (lastRegister)\n loader.defined[load.name] = entry = lastRegister;\n }\n\n if (!entry)\n return loaderInstantiate.call(this, load);\n\n entry.deps = dedupe(entry.deps);\n\n // first, normalize all dependencies\n var normalizePromises = [];\n for (var i = 0; i < entry.deps.length; i++)\n normalizePromises.push(Promise.resolve(loader.normalize(entry.deps[i], load.name)));\n \n return Promise.all(normalizePromises).then(function(normalizedDeps) {\n\n entry.normalizedDeps = normalizedDeps;\n\n // create the empty dep map - this is our key deferred dependency binding object passed into declare\n entry.depMap = [];\n\n return {\n deps: entry.deps,\n execute: function() {\n // this avoids double duplication allowing a bundle to equal its last defined module\n if (entry.esmodule) {\n delete loader.defined[load.name];\n return entry.esmodule;\n }\n\n // recursively ensure that the module and all its \n // dependencies are linked (with dependency group handling)\n link(load.name, loader);\n\n // now handle dependency execution in correct order\n ensureEvaluated(load.name, [], loader);\n\n // remove from the registry\n delete loader.defined[load.name];\n\n var module = Module(entry.module);\n\n // if the entry is an alias, set the alias too\n for (var name in loader.defined) {\n if (loader.defined[name].execute != entry.execute)\n continue;\n loader.defined[name].esmodule = module;\n }\n // return the defined module object\n return module;\n }\n };\n });\n }\n}",
"function buildModules() {\n // loop through modules\n for (var i = 0, l = modules.length; i < l; i++) {\n var options = modules[i].options;\n // process styles\n var styleData;\n // loop through options\n for (var j = 0, m = options.length; j < m; j++) {\n if (options[j].isEnabled && options[j].head && options[j].head.css && (styleData = options[j].head.css) != null) {\n // loop through lines\n for (var k = 0, n = styleData.length; k < n; k++) {\n styles += '\\n ' + styleData[k];\n }\n styles += '\\n';\n }\n }\n\n // process head scripts\n var scriptData,\n fields = {};\n // loop through options\n for (var j = 0, m = options.length; j < m; j++) {\n if (options[j].isEnabled && options[j].head && options[j].head.js && (scriptData = options[j].head.js)) {\n // loop through lines\n for (var k = 0, n = scriptData.length; k < n; k++) {\n headScripts += '\\n ' + scriptData[k];\n }\n headScripts += '\\n';\n }\n if (options[j].fields && options[j].fields.length > 0) {\n // loop through fields\n for (var k = 0, n = options[j].fields.length; k < n; k++) {\n fields[options[j].fields[k].name] = options[j].fields[k].val;\n }\n }\n }\n _min.push(JSON.stringify(fields));\n\n // process body scripts\n var scriptData;\n // loop through options\n for (var j = 0, m = options.length; j < m; j++) {\n if (options[j].isEnabled && options[j].load && (scriptData = options[j].load.js)) {\n // loop through lines\n for (var k = 0, n = scriptData.length; k < n; k++) {\n bodyScripts += '\\n ' + scriptData[k];\n }\n bodyScripts += '\\n';\n }\n }\n\n // populate variables\n bodyScripts = bodyScripts.replace(/_min\\./g, '_min[' + i + '].');\n headScripts = headScripts.replace(/_min\\./g, '_min[' + i + '].');\n while (styles.indexOf('_min.') != -1) {\n styles = styles.replace(styles.substring(styles.indexOf('_min.'), styles.indexOf(' ', styles.indexOf('_min.'))), JSON.parse(_min[i])[styles.substring(styles.indexOf('_min.') + 5, styles.indexOf(' ', styles.indexOf('_min.')))]);\n }\n }\n headScripts = '\\n var _min = [' + _min + '];' + headScripts;\n}",
"function loadModule (moduleName, app, pool) {\n var fileName = __dirname + '/modules/' + moduleName;\n\n console.log('Loading module: [%s]', fileName);\n require(fileName)(app, pool);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Buff check: VIP Status | function τSST_detect_buff_vip() {
buffs_table.vip = localStorage[storage_key_prefix + 'buffs_table_vip'];
var vip_node = $('dt:contains("VIP Status:") + dd');
if (vip_node.length) {
if (vip_node.find(':contains("Get VIP status!")').length) {
buffs_table.vip = "non-VIP";
} else {
buffs_table.vip = "VIP";
}
}
// If the VIP status was just discovered for the first time, update our logs accordingly.
// If it has actually changed, note the fact for our callers.
if (buffs_table.vip != localStorage[storage_key_prefix + 'buffs_table_vip']) {
var first_discovery = false;
for (var stat in all_stats) {
var this_log = localStorage[storage_key_prefix + 'stat_logs_' + stat];
if (! this_log) {
first_discovery = true;
} else if (this_log.includes(vip_placeholder)) {
this_log = this_log.replace(vip_placeholder, buffs_table.vip);
localStorage.setItem(storage_key_prefix + 'stat_logs_' + stat, this_log);
first_discovery = true;
}
}
if (first_discovery) {
// Technically, this didn't change; this is just the first time we could detect it.
localStorage.setItem(storage_key_prefix + 'buffs_table_vip', buffs_table.vip);
} else {
// We already had a real value, so this has actually changed.
buffs_changed = true;
}
}
// Other than the above scenario, buff updates are stored only when actually updating a stat log.
} | [
"VIPStatusOfThisAccount() {\n let url = `/me/vipStatus`;\n return this.client.request('GET', url);\n }",
"async isBusy() {\n return new Promise((resolve, reject) => {\n this.rpc.stdin.write('busy' + os.EOL);\n this.rpc.stdout.once('data', (data) => {\n data = data.toString().trim();\n if ((typeof data == 'boolean' && data) || data == \"true\") {\n resolve(true)\n } else {\n resolve(false)\n }\n });\n });\n\n }",
"function τSST_detect_static_buffs() {\n // Available only in Player Details page (http://alpha.taustation.space/ - root page).\n τSST_detect_buff_genotype();\n τSST_detect_buff_vip(); // TODO: Does this show the GCT time when VIP will end? If so, add to \"...dynamic...()\" below.\n τSST_detect_buff_skills();\n\n // Available on most (any?) page.\n τSST_detect_buff_hotel_room();\n }",
"function status(req,res,next) {\n\n if ( req.url === \"/ping\" ) {\n res.end(\"ok\");\n } else {\n next();\n }\n }",
"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 retrieveStatus(){\n request(icecastUrl, function (error, response, body) {\n // If error, log it\n var mountpointList = JSON.parse(body).icestats.source;\n // Check for all three mountpoints\n checkStatus(mountpointList, 'listen');\n checkStatus(mountpointList, 'hub');\n checkStatus(mountpointList, 'harrow');\n });\n}",
"_getAVRVolumeStatus() {\n this._volumeCommand( \"volume_request\", \"\" );\n }",
"function isIpBlocked( )\n{\n //global config;\n result = false;\n ipaddress = _SERVER.REMOTE_ADDR; \n //foreach (config.BLOCKED_IPS as ip)\n //{\n // if (preg_match( \"/\"+ip+\"/\", ipaddress ))\n // {\n // error( \"Your ip address has been blocked from making changes!\" );\n // result = true;\n // break;\n // } \n //}\n return result;\n}",
"async getUdpInErrors()\n {\n return Promise.resolve()\n .then(() => getNetSnmpInfo4())\n .then((info) => +info.Udp.InErrors % COUNTER_WRAP_AT);\n }",
"function checkStatus() {\n if (supportsAvif !== null && supportsWebp !== null) {\n showOverlay();\n return;\n }\n }",
"async getIpInAddrErrors()\n {\n return Promise.resolve()\n .then(() => getNetSnmpInfo4())\n .then((info) => +info.Ip.InAddrErrors % COUNTER_WRAP_AT);\n }",
"checkActionStatus() {\n if (this.state >= SolairesAction.STATUS.DONE)\n return;\n if (this.state == SolairesAction.STATUS.ACK)\n SolairesAction.updateGMAck(false);\n }",
"function validateResponse ( packet ) {\n\tlet result = false;\n\n\t//0 0 129 128 0 1 0\n\tif (packet.length > 7 &&\n\t\tpacket[2] === 129 &&\n\t\tpacket[3] === 128 &&\n\t\tpacket[4] === 0 &&\n\t\tpacket[5] === 1 &&\n\t\tpacket[6] === 0 &&\n\t\tpacket[7] > 0\n\t) {\n\t\tresult = true;\n\t}\n\n\treturn result;\n}",
"function checkStatus() {\n return new Promise((resolve, reject) => {\n getStatusFromCache()\n .then(function(data) {\n resolve(data);\n })\n .catch(function(err) {\n resolve(scrapeStatus());\n });\n });\n}",
"_checkSendBuffer() {\n\n this._d(`${this.insertIndex} / ${this.deleteIndex}.`);\n\n if ( this.insertIndex === this.deleteIndex ) {\n\n // end buffer is 'empty' => nothing to do then wait till's flled again.\n this.isLoopRunning = false ;\n this._d(\"Send loop temp stopped - empty send buffer.\");\n } else {\n if ( this.sendAr[ this.deleteIndex ] === \"\" ) {\n\n // If the command to be send if empty consider it as\n // empty buffer and exit the data send loop.\n this.isLoopRunning = false ;\n this._d(\"Sendbuffer entry empty (stopping send loop)!.\");\n } else {\n let data = this.sendAr[ this.deleteIndex ];\n this.sendAr[ this.deleteIndex ] = \"\"; // clear used buffer.\n this.deleteIndex++;\n\n if ( this.deleteIndex >= this.MAXINDEX ) {\n this.deleteIndex = 0;\n }\n this._d(`Setting deleteIndex to ${this.deleteIndex}.`);\n\n this._sendToAvr( data );\n }\n }\n }",
"async getIcmpInDestUnreachs()\n {\n return Promise.resolve()\n .then(() => getNetSnmpInfo4())\n .then((info) => +info.Icmp.InDestUnreachs % COUNTER_WRAP_AT);\n }",
"function currentIP () {\n var options = {\n host: 'ip-api.com',\n port: 80,\n path: '/json'\n };\n\n // Make HTTP query to fetch IP data\n console.log('Making HTTP API call to check IP');\n\n http.get(options, function(response){\n var body = '';\n\n response.on('data', function(chunk){\n \t// Append chunk response\n body += chunk;\n });\n\n response.on('end', function() {\n \t// Parse returned JSON\n var parsed = JSON.parse(body);\n\n // Update latest IP\n console.log('IP API claims the public IP is ' + parsed.query);\n writeIP(parsed.query);\n });\n });\n}",
"static get STATUS_RUNNING () {\n return 0;\n }",
"validateActivityStatus() {\r\n let res = this.state.selectedData.every((livestock) => {\r\n return !(livestock.ActivitySystemCode == livestockActivityStatusCodes.Deceased ||\r\n livestock.ActivitySystemCode == livestockActivityStatusCodes.Killed ||\r\n livestock.ActivitySystemCode == livestockActivityStatusCodes.Lost);\r\n });\r\n if (!res) this.notifyToaster(NOTIFY_WARNING, { message: this.strings.INVALID_RECORD_LOST_STATUS });\r\n return res;\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the path of cmd.exe in windows | function getCmdPath() {
var _a;
return (_a = process.env['COMSPEC']) !== null && _a !== void 0 ? _a : `cmd.exe`;
} | [
"function Commander(cmd) {\n var command =\n (getOsType().indexOf('WIN') !== -1 && cmd.indexOf('.exe') === -1) ?\n cmd + '.exe' : cmd;\n var _file = null;\n\n // paths can be string or array, we'll eventually store one workable\n // path as _path.\n this.initPath = function(paths) {\n if (typeof paths === 'string') {\n var file = getFile(paths, command);\n _file = file.exists() ? file : null;\n } else if (typeof paths === 'object' && paths.length) {\n for (var p in paths) {\n try {\n var result = getFile(paths[p], command);\n if (result && result.exists()) {\n _file = result;\n break;\n }\n } catch (e) {\n // Windows may throw error if we parse invalid folder name,\n // so we need to catch the error and continue seaching other\n // path.\n continue;\n }\n }\n }\n if (!_file) {\n throw new Error('it does not support ' + command + ' command');\n }\n };\n\n this.run = function(args, callback) {\n var process = Cc['@mozilla.org/process/util;1']\n .createInstance(Ci.nsIProcess);\n try {\n log('cmd', command + ' ' + args.join(' '));\n process.init(_file);\n process.run(true, args, args.length);\n } catch (e) {\n throw new Error('having trouble when execute ' + command +\n ' ' + args.join(' '));\n }\n callback && callback();\n };\n\n /**\n * This function use subprocess module to run command. We can capture stdout\n * throught it.\n *\n * @param {Array} args Arrays of command. ex: ['adb', 'b2g-ps'].\n * @param {Object} options Callback for stdin, stdout, stderr and done.\n *\n * XXXX: Since method \"runWithSubprocess\" cannot be executed in Promise yet,\n * we need to keep original method \"run\" for push-to-device.js (nodejs\n * support). We'll file another bug for migration things.\n */\n this.runWithSubprocess = function(args, options) {\n log('cmd', command + ' ' + args.join(' '));\n var p = subprocess.call({\n command: _file,\n arguments: args,\n stdin: (options && options.stdin) || function(){},\n stdout: (options && options.stdout) || function(){},\n stderr: (options && options.stderr) || function(){},\n done: (options && options.done) || function(){},\n });\n p.wait();\n };\n}",
"function getFirefoxExe(firefoxDirName){\n if (process.platform !== 'win32') {\n return null;\n }\n\n\n var prefix;\n var prefixes = [process.env.PROGRAMFILES, process.env['PROGRAMFILES(X86)']];\n var suffix = '\\\\'+ firefoxDirName + '\\\\firefox.exe';\n\n for (var i = 0; i < prefixes.length; i++) {\n prefix = prefixes[i];\n if (fs.existsSync(prefix + suffix)) {\n return prefix + suffix;\n }\n }\n\n return 'C:\\\\Program Files' + suffix;\n }",
"function getQbExecutablePath() {\n var path = require( \"path\" );\n var modulePath = path.dirname( module.filename );\n var qbPath = path.resolve( modulePath + \"/../qb/bin/Release/qb.exe\" );\n return qbPath;\n}",
"function findPath(app)\n {\n var child = require('child_process').execFile('/bin/sh', ['sh']);\n child.stdout.str = '';\n child.stdout.on('data', function (chunk) { this.str += chunk.toString(); });\n if (process.platform == 'linux' || process.platform == 'freebsd')\n {\n child.stdin.write(\"whereis \" + app + \" | awk '{ print $2 }'\\nexit\\n\");\n }\n else\n {\n child.stdin.write(\"whereis \" + app + \"\\nexit\\n\");\n }\n child.waitExit();\n child.stdout.str = child.stdout.str.trim();\n if (process.platform == 'freebsd' && child.stdout.str == '' && require('fs').existsSync('/usr/local/bin/' + app)) { return ('/usr/local/bin/' + app); }\n return (child.stdout.str == '' ? null : child.stdout.str);\n }",
"dir() {\n if (this.program.dir) {\n if (Path.isAbsolute(this.program.dir)) {\n return this.program.dir;\n }\n return Path.resolve(process.cwd(), this.program.dir);\n }\n return process.cwd();\n }",
"_getWorkingDirectory() {\n const activeItem = atom.workspace.getActivePaneItem();\n if (activeItem\n && activeItem.buffer\n && activeItem.buffer.file\n && activeItem.buffer.file.path) {\n return atom.project.relativizePath(activeItem.buffer.file.path)[0];\n } else {\n const projectPaths = atom.project.getPaths();\n let cwd;\n if (projectPaths.length > 0) {\n cwd = projectPaths[0];\n } else {\n cwd = process.env.HOME;\n }\n return path.resolve(cwd);\n }\n }",
"function getFilePath() {\n let lastExecCommand = execSync('tail ' + getHistoryPath() + ' | grep imgcat | tail -n 1').toString();\n let home = execSync('echo $HOME | tr -d \"\\n\"').toString() + '/';\n let commands = lastExecCommand.split('imgcat');\n let absolutePath = commands.pop().replace('~/', home);\n return absolutePath;\n}",
"function getExecutablePath () {\n let possiblePaths = [\n '/Applications/Guild Wars 2.app',\n 'C:\\\\Program Files\\\\Guild Wars 2\\\\Gw2.exe',\n 'C:\\\\Program Files (x86)\\\\Guild Wars 2\\\\Gw2.exe'\n ]\n\n // Load the previously saved path at the first spot\n let savedPath = config.get('executablePath')\n if (savedPath) {\n possiblePaths.unshift(savedPath)\n }\n\n // Go through all the paths and filter the ones out that are existing\n // (This also checks if the path the user chose still exists)\n possiblePaths = possiblePaths.filter(path => {\n try {\n fs.statSync(path)\n return true\n } catch (noop) {\n return false\n }\n })\n\n // The user will have to choose his launcher path\n if (possiblePaths.length === 0) {\n config.delete('executablePath')\n return false\n }\n\n // Save the first existing path as our path\n config.set('executablePath', possiblePaths[0])\n return true\n}",
"function getEnvPath() {\n var paths;\n var os = getOsType();\n if (!os) {\n throw new Error('cannot not read system type');\n }\n var p = getEnv('PATH');\n var isMsys = getEnv('OSTYPE') ? true : false;\n if (os.indexOf('WIN') !== -1 && !isMsys) {\n paths = p.split(';');\n } else {\n paths = p.split(':');\n }\n return paths;\n}",
"function absPath(path)\r\n{\r\n expandedPath = WshShell.ExpandEnvironmentStrings(path);\r\n fso = WScript.CreateObject(\"Scripting.FileSystemObject\");\r\n return fso.GetAbsolutePathName(expandedPath);\r\n}",
"function getBinScript(name) {\n // Global install or npm@2 local install, dependencies in local node_modules\n let paths = glob.sync(`../node_modules/.bin/${name}`, {cwd: __dirname})\n if (paths.length > 0) return path.join(__dirname, paths[0])\n // Local npm@3 install, .bin and dependencies are siblings\n paths = glob.sync(`../../.bin/${name}`, {cwd: __dirname})\n if (paths.length > 0) return path.join(__dirname, paths[0])\n throw new Error(`Unable to find .bin script for ${name}`)\n}",
"function platform() {\n\tvar s = process.platform; // \"darwin\", \"freebsd\", \"linux\", \"sunos\" or \"win32\"\n\tif (s == \"darwin\") return \"mac\"; // Darwin contains win, irony\n\telse if (s.starts(\"win\")) return \"windows\"; // Works in case s is \"win64\"\n\telse return \"unix\";\n}",
"function getPlatformVariant() {\n var contents = '';\n\n if (process.platform !== 'linux') {\n return '';\n }\n\n try {\n contents = fs.readFileSync(process.execPath); // Buffer.indexOf was added in v1.5.0 so cast to string for old node\n // Delay contents.toStrings because it's expensive\n\n if (!contents.indexOf) {\n contents = contents.toString();\n }\n\n if (contents.indexOf('libc.musl-x86_64.so.1') !== -1) {\n return 'musl';\n }\n } catch (err) {} // eslint-disable-line no-empty\n\n\n return '';\n}",
"function loadExec() {\n fs = Npm.require('fs');\n exec = Npm.require('child_process').exec;\n cmd = Meteor.wrapAsync(exec);\n return cmd;\n}",
"function getHistoryPath() {\n let shell = execSync('echo $SHELL').toString();\n if (new RegExp('zsh').test(shell)) {\n return '~/.zsh_history';\n } else if (new RegExp('bash').test(shell)) {\n return '~/.bash_history';\n } else if (new RegExp('fish').test(shell)) {\n return '~/.local/share/fish/fish_history';\n }\n}",
"function execProm(cmd) { // string => Promise of { stdout: string, stderr: string }\n return new Promise((resolve, reject) => {\n exec(cmd, (err, stdout, stderr) => {\n if (err) {\n reject( { err, stdout, stderr });\n } else {\n resolve({ stdout, stderr });\n }\n });\n });\n}",
"function createDriveCommandWithPower (cmd, power) {\n return ip+\"/cmd/{'c':\"+cmd+\",'p':\"+power+\"}\";\n}",
"function _resolveClientDirectory() {\n try {\n // Default app dir is\n return process.env.PWD;\n\n } catch (errorSettingAppDir) {\n // Maybe this is being loaded in an IDE or \"node console\"\n return path.dirname(require.main.filename);\n }\n}",
"getCommandSpec(packageId, commandId) {\n return this.packages[packageId].commands[commandId];\n }",
"function running_command() {\n\treturn command_stack[command_stack.length - 1];\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Detect Cordova / PhoneGap / Ionic frameworks on a mobile device. Deliberately does not rely on checking `file://` URLs (as this fails PhoneGap in the Ripple emulator) nor Cordova `onDeviceReady`, which would normally wait for a callback. | function isMobileCordova() {
return (typeof window !== 'undefined' &&
// @ts-ignore Setting up an broadly applicable index signature for Window
// just to deal with this case would probably be a bad idea.
!!(window['cordova'] || window['phonegap'] || window['PhoneGap']) &&
/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA()));
} | [
"function chkMobile() {\r\n\treturn /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);\r\n}",
"function isMediaDevicesSuported(){return hasNavigator()&&!!navigator.mediaDevices;}",
"function DetectPalmOS()\n{\n if (uagent.search(devicePalm) > -1)\n location.href='http://www.kraftechhomes.com/home_mobile.php';\n else\n return false;\n}",
"function useTouch() {\n return isNativeApp() || $.browser.mobile || navigator.userAgent.match(/iPad/i) != null;\n}",
"function canEnumerateDevices(){return!!(isMediaDevicesSuported()&&navigator.mediaDevices.enumerateDevices);}",
"function IsPC() {\n var userAgentInfo = navigator.userAgent\n var Agents = [\"Android\", \"iPhone\", \"SymbianOS\", \"Windows Phone\", \"iPad\", \"iPod\"]\n var devType = 'PC'\n for (var v = 0; v < Agents.length; v++) {\n if (userAgentInfo.indexOf(Agents[v]) > 0) {\n // Determine the system platform used by the mobile end of the user\n if (userAgentInfo.indexOf('Android') > -1 || userAgentInfo.indexOf('Linux') > -1) {\n //Android mobile phone\n devType = 'Android'\n } else if (userAgentInfo.indexOf('iPhone') > -1) {\n //Apple iPhone\n devType = 'iPhone'\n } else if (userAgentInfo.indexOf('Windows Phone') > -1) {\n //winphone\n devType = 'winphone'\n } else if (userAgentInfo.indexOf('iPad') > -1) {\n //Pad\n devType = 'iPad'\n }\n break;\n }\n }\n docEl.setAttribute('data-dev-type', devType)\n }",
"function targetDevices(targetOS) {\n for (var key in _platformDeviceMap) {\n if (targetOS.contains(key))\n return _platformDeviceMap[key];\n }\n}",
"function checkFolder(path, device) {\n\tvar sep = air.File.separator;\n\t//If device is iphone, check if the folder has www folder\n\tvar iphoneCheck = new air.File(path + sep + 'www');\n\t//If device is android, check if the folder has assets/www\n\tvar androidCheck = new air.File(path + sep + 'assets' + sep + 'www');\n\tif(device == 'iphone')\n\t\treturn iphoneCheck.exists;\n\telse \n\t\treturn androidCheck.exists;\t\n}",
"function checkIfLoadingFromMobileBrowser() {\n if (!is_hybrid && basic.isMobile() && basic.cookies.get('show-download-mobile-app') != '1') {\n if (basic.getMobileOperatingSystem() == 'Android') {\n basic.showDialog('<div><h2 class=\"fs-24 lato-bold text-center padding-top-15 padding-bottom-25\">'+$('.translates-holder').attr('wallet-app-here')+'<br>'+$('.translates-holder').attr('free-download')+'</h2><figure itemscope=\"\" itemtype=\"http://schema.org/Organization\" class=\"text-center phone-container\"><img src=\"assets/images/download-android-app.png\" class=\"max-width-300 width-100\" itemprop=\"logo\" alt=\"Phone\"/><a class=\"inline-block max-width-150 absolute-content app-store-link\" href=\"https://play.google.com/store/apps/details?id=wallet.dentacoin.com\" target=\"_blank\" itemprop=\"url\"><img src=\"assets/images/google-play-badge.svg\" class=\"width-100\" itemprop=\"logo\" alt=\"Google play icon\"/></a><a class=\"inline-block max-width-150 absolute-content huawei-link\" href=\"https://appgallery.huawei.com/app/C105341527\" target=\"_blank\" itemprop=\"url\"><img src=\"assets/images/huawei-app-gallery-btn.svg\" class=\"width-100\" itemprop=\"logo\" alt=\"Download APK icon\"/></a><a class=\"inline-block max-width-150 absolute-content apk-link\" href=\"https://dentacoin.com/assets/files/dentacoin-wallet.apk\" download=\"\" itemprop=\"url\"><img src=\"assets/images/download-apk-file-btn.svg\" class=\"width-100\" itemprop=\"logo\" alt=\"Download APK icon\"/></a></figure></div>', 'download-mobile-app', null, null);\n\n $('.download-mobile-app .bootbox-close-button').click(function() {\n basic.cookies.set('show-download-mobile-app', 1);\n });\n } else if (basic.getMobileOperatingSystem() == 'iOS' || navigator.platform == 'MacIntel') {\n basic.showDialog('<div><h2 class=\"fs-24 lato-bold text-center padding-top-15 padding-bottom-25\">'+$('.translates-holder').attr('wallet-app-here')+'<br>'+$('.translates-holder').attr('free-download')+'</h2><figure itemscope=\"\" itemtype=\"http://schema.org/Organization\" class=\"text-center phone-container\"><img src=\"assets/images/download-ios-app.png\" class=\"max-width-300 width-100\" itemprop=\"logo\" alt=\"Phone\"/><a class=\"inline-block max-width-150 absolute-content\" href=\"https://apps.apple.com/us/app/dentacoin-wallet/id1478732657\" target=\"_blank\" itemprop=\"url\"><img src=\"assets/images/app-store.svg\" class=\"width-100\" itemprop=\"logo\" alt=\"App store icon\"/></a></figure></div>', 'download-mobile-app', null, null);\n\n $('.download-mobile-app .bootbox-close-button').click(function() {\n basic.cookies.set('show-download-mobile-app', 1);\n });\n }\n }\n}",
"function checkIfMobile() {\n var isMobile = navigator.userAgent.match(/Android/i) ||\n navigator.userAgent.match(/iPhone|iPad|iPod/i);\n if (isMobile) {\n var zmControls = getElement('ZmControls');\n if (zmControls) {\n zmControls.style.display = 'none';\n }\n }\n}",
"function getUserDevices(req) {\n\tvar cookies = parseCookies(req);\n\tif (typeof cookies.devices == \"undefined\")\n\t\treturn false\n\tvar devices = cookies.devices.split(\",\")\n\treturn devices\n}",
"function refreshPlatforms(platforms) {\n if(platforms === undefined) return;\n deleteDirSync(\"platforms\");\n\n if(platforms.indexOf(\"a\") !== -1)\n runShell(\"npx ionic cordova platform add android\");\n\n if(platforms.indexOf(\"i\") !== -1)\n if (OS.platform() === \"darwin\") runShell(\"npx ionic cordova platform add ios\");\n else consoleOut(`(set_brand.js) did not add ios-platform on the operating system \"${OS.platform()}\"`);\n}",
"get isNativePlugin() {}",
"function detectPlatform () {\n var type = os.type();\n var arch = os.arch();\n\n if (type === 'Darwin') {\n return 'osx-64';\n }\n\n if (type === 'Windows_NT') {\n return arch == 'x64' ? 'windows-64' : 'windows-32';\n }\n\n if (type === 'Linux') {\n if (arch === 'arm' || arch === 'arm64') {\n return 'linux-armel';\n }\n return arch == 'x64' ? 'linux-64' : 'linux-32';\n }\n\n return null;\n}",
"function DeviceHandler() {\n chrome.fileBrowserPrivate.onDeviceChanged.addListener(\n this.onDeviceChanged_.bind(this));\n}",
"function deviceHasTouchScreen() {\n let hasTouchScreen = false;\n if (\"maxTouchPoints\" in navigator) {\n hasTouchScreen = navigator.maxTouchPoints > 0;\n } else if (\"msMaxTouchPoints\" in navigator) {\n hasTouchScreen = navigator.msMaxTouchPoints > 0;\n } else {\n var mQ = window.matchMedia && matchMedia(\"(pointer:coarse)\");\n if (mQ && mQ.media === \"(pointer:coarse)\") {\n hasTouchScreen = !!mQ.matches;\n } else if ('orientation' in window) {\n hasTouchScreen = true; // deprecated, but good fallback\n } else {\n // Only as a last resort, fall back to user agent sniffing\n var UA = navigator.userAgent;\n hasTouchScreen = (\n /\\b(BlackBerry|webOS|iPhone|IEMobile)\\b/i.test(UA) ||\n /\\b(Android|Windows Phone|iPad|iPod)\\b/i.test(UA)\n );\n }\n }\n return hasTouchScreen;\n }",
"_isNativePlatform() {\n if ((this._isIOS() || this._isAndroid()) && this.config.enableNative) {\n return true;\n } else {\n return false;\n }\n }",
"function getDeviceTypes() {\n \n}",
"function onDeviceReady() {\n\t$(\"#status\").html(\"Status: Ready! 1\");\n}",
"set isNativePlugin(value) {}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
enemyMoveheight handles when when the enemies reaches the certain distance the player loses a life, a sound is played and the enemy is destroyed | function enemyMoveHeight() {
if(isHidden==true){return;}
if(enemy.offsetTop>=700){
lives--;
var audioLifeLost= new Audio("lifeLost.wav");
audioLifeLost.play();
LivesDiv.innerHTML="lives "+lives;
enemy.remove();
//when the play reaches 0 lives the function is called to end the game
if(lives<=0){
gameOver();
}
}
//enemy will keep moving until it has reacher 669px
else if(enemy.offsetTop<=699){
enemyPosition++;
enemy.style.top = enemyPosition + 'px';
}
} | [
"function weaponHit(e, m, ei, mi) {\n\n if(m.x <= (e.x + e.w) && (m.x + m.w) >= e.x && m.y <= (e.y + e.h) && (m.y + m.h) >= e.y) {\n enemyArray.splice(ei,1)\n weaponArray.splice(mi,1)\n new enemyExplosion(\"./sfx/enemyExplosion.wav\")\n score += 100\n\n for(let d=0; d < 15; d++) {\n let size = Math.floor(Math.random() * 3) + 1\n let dx = (Math.random() - 0.5) * 20;\n let dy = (Math.random() - 0.5) * 20;\n let color = colorArray[Math.floor(Math.random()*colorArray.length)]\n debrisArray.push(new enemyDestroyed(e.x, e.y , size, dx, dy, color))\n }\n \n for(let d=0; d < 15; d++) {\n let size = Math.floor(Math.random() * 1) + 1\n let dx = (Math.random() - 0.5) * 30;\n let dy = (Math.random() - 0.5) * 30;\n let color = colorArray2[Math.floor(Math.random()*colorArray.length)]\n debrisArray.push(new enemyDestroyed(e.x, e.y , size, dx, dy, color))\n }\n }\n}",
"function checkEnemiesOutOfBounds()\r\n{\r\n\tlivingEnemies.length=0;\r\n\r\n enemies.forEachAlive(function(bad){\r\n\r\n \r\n livingEnemies.push(bad);\r\n });\r\n\t\r\n\tfor(var i = 0; i < livingEnemies.length; i++)\r\n\t{\r\n\t\tif(livingEnemies[i].body.y > game.world.height)\r\n\t\t{\r\n\t\t\tlivingEnemies[i].kill();\r\n\t\t\tkillPlayer();\r\n\t\t}\r\n\t\t\r\n\t}\r\n}",
"death () {\r\n this.body.velocity.x = 0\r\n this.dying = true\r\n this.events.onOutOfBounds.add(this.kill, this)\r\n this.game.camera.shake(0.005, 100)\r\n }",
"function survival() {\n ui.setText(\"EnemyCounter\", \"\");\n if (game.enemiesAlive == 0 && !game.waveActive) {\n waveCooldown();\n } else if (game.waveActive) {\n if (game.enemiesAlive < 10) {\n gameWorld.createEnemy();\n }\n }\n}",
"function lost() {\n score = 0;\n scoreSpan.textContent = score;\n allEnemies.forEach(function(enemy) {\n enemy.speed = enemy.originalSpeed;\n });\n player.goBack();\n}",
"die() {\n this.dieSfx.play('die');\n this.scene.time.delayedCall(6000, (sounds)=> {\n sounds.forEach( (sound) => {\n sound.destroy();\n })\n }, [[this.dieSfx, this.takeDamageSfx, this.dealDamageSfx, this.shoutSfx]]);\n for(let i = this.minCoins; i < Math.random() * this.maxCoins + this.minCoins; i++) {\n let coin = new GameCoin({scene:this.scene, x:this.x, y:this.y});\n coin.body.setVelocityX(Math.random() * 100 - 50);\n coin.body.setVelocityY(Math.random() * 100 - 50);\n }\n if(this.nextMoveEvent) {\n this.nextMoveEvent.destroy();\n }\n if(this.senseEvents) {\n this.senseEvents.forEach( (event)=> {\n event.destroy();\n });\n }\n dataManager.emitter.emit(\"enemyDied\");\n this.destroy();\n }",
"decrementPlayerHealth() {\n if (!this.decrementHealthOnCollision) return\n\n this.player.health--\n if (this.player.health <= 0) {\n this.triggerGameOver()\n }\n }",
"function enemyPlayerCollision(player, enemy){\n enemy.kill();\n var live = lives.getFirstAlive();\n \n if (live){\n live.kill();\n }\n if (lives.countLiving()<1){\n endGame();\n }\n }",
"function EnemyOneDeath (deadEnemy : int) {\n\tif (deadEnemy == 1) {\n\t\tenemyCount --;\n\t\tenemyOneCount --;\n\t\tDebug.Log(\"Enemy One Count is \" + enemyOneCount);\n\t}\n}",
"function moveSomething(e) {\n\t\t\tfunction moveLeftRight(xVal){\n\t\t\t\tvar newX = xVal;\n\t\t\t\tboard.player.xPrev = board.player.x;\n\t\t\t\tboard.player.yPrev = board.player.y;\n\t\t\t\tboard.player.x = newX;\n\t\t\t\tboard.player.y = board.player.y;\n\t\t\t\tboard.position[newX][board.player.y] = 4;\n\t\t\t\tboard.position[board.player.xPrev][board.player.yPrev] = 0;\n\t\t\t\tboard.player.erasePrevious();\n\t\t\t\tboard.player.render();\n\t\t\t}\n\t\t\tfunction moveUpDown(yVal){\n\t\t\t\tvar newY = yVal;\n\t\t\t\tboard.player.xPrev = board.player.x;\n\t\t\t\tboard.player.yPrev = board.player.y;\n\t\t\t\tboard.player.x = board.player.x;\n\t\t\t\tboard.player.y = newY;\n\t\t\t\tboard.position[board.player.x][newY] = 4;\n\t\t\t\tboard.position[board.player.xPrev][board.player.yPrev] = 0;\n\t\t\t\tboard.player.erasePrevious();\n\t\t\t\tboard.player.render();\n\t\t\t}\n\t\t\tfunction enemiesMove(){\n\t\t\t\tif (!board.enemy1.enemyDead)\n\t\t\t\t\tenemy1Move.makeMove();\n\t\t\t\tif (!board.enemy2.enemyDead)\n\t\t\t\t\tenemy2Move.makeMove();\n\t\t\t\tif (!board.enemy3.enemyDead)\n\t\t\t\t\tenemy3Move.makeMove();\n\t\t\t}\n\t\t\tfunction checkForWin(){\n\t\t\t\tif (board.enemy1.enemyDead && board.enemy2.enemyDead && board.enemy3.enemyDead){\n\t\t\t\t\tconsole.log(\"You Win!!!!! *airhorn*\" )\n\t\t\t\t\tboard.player.eraseThis();\n\t\t\t\t\t//board.potion1.eraseThis();\n\t\t\t\t\t//board.potion2.eraseThis();\n\t\t\t\t\tctx.beginPath();\n\t\t\t\t\tctx.font = \"128px Georgia\";\n\t\t\t\t\tctx.fillStyle = \"#00F\";\n\t\t\t\t\tctx.fillText(\"You Win!!\", 40, 320);\n\t\t\t}\n\t\t\t}\n\t\t\tfunction restoreHealth(xVal,yVal){\n\t\t\t\tvar x = xVal;\n\t\t\t\tvar y = yVal;\n\t\t\t\tif (board.position[x][y] == 5){\n\t\t\t\t\tboard.player.restoreHealth();\n\t\t\t\t\tif(board.potion1.x == x && board.potion1.y == y)\n\t\t\t\t\t\tboard.potion1.eraseThis()\n\t\t\t\t\telse \n\t\t\t\t\t\tboard.potion2.eraseThis();\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif(!board.player.playerDead || board.enemy1.enemyDead && board.enemy2.enemyDead && board.enemy3.enemyDead){\n\t\t\tswitch(e.keyCode) {\n\t\t\t\tcase 37:\n\t\t\t\t\t// left key pressed\n\t\t\t\t\tvar newX = board.player.x - 1;\n\t\t\t\t\tif(board.player.x == 0)\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tif(board.position[newX][board.player.y] == 0 || board.position[newX][board.player.y] == 5)\n\t\t\t\t\t{\n\t\t\t\t\t\tconsole.log(\"Left was pressed...\\n\");\n\t\t\t\t\t\trestoreHealth(newX,board.player.y);\n\t\t\t\t\t\tmoveLeftRight(newX);\n\t\t\t\t\t\tenemiesMove();\n\t\t\t\t\t}\n\t\t\t\t\telse if(board.position[newX][board.player.y] == 3){\n\t\t\t\t\t\tconsole.log(\"Enemy is taking damage...\");\n\t\t\t\t\t\tif(board.enemy1.x == newX && board.enemy1.y == board.player.y){\n\t\t\t\t\t\t\tboard.enemy1.takeDamage();\n\t\t\t\t\t\t\tif(board.enemy1.enemyDead)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmoveLeftRight(newX);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(board.enemy2.x == newX && board.enemy2.y == board.player.y){\n\t\t\t\t\t\t\tboard.enemy2.takeDamage();\n\t\t\t\t\t\t\t\tif(board.enemy2.enemyDead)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmoveLeftRight(newX);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(board.enemy3.x == newX && board.enemy3.y == board.player.y){\n\t\t\t\t\t\t\tboard.enemy3.takeDamage();\n\t\t\t\t\t\t\t\tif(board.enemy3.enemyDead)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmoveLeftRight(newX);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tenemiesMove();\n\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\tbreak;\n\t\t\t\tcase 38:\n\t\t\t\t\t// up key \n\t\t\t\t\tvar newY = board.player.y - 1;\n\t\t\t\t\tif(board.player.y == 0)\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tif(board.position[board.player.x][newY] == 0 || board.position[board.player.x][newY] == 5)\n\t\t\t\t\t{\n\t\t\t\t\t console.log(\"Up was pressed...\\n\");\n\t\t\t\t\t\trestoreHealth(board.player.x,newY);\n\t\t\t\t\t\tmoveUpDown(newY);\n\t\t\t\t\t\tenemiesMove();\n\t\t\t\t\t}\n\t\t\t\t\telse if(board.position[board.player.x][newY] == 3){\n\t\t\t\t\t\tconsole.log(\"Enemy is taking damage...\");\n\t\t\t\t\t\tif(board.enemy1.x == board.player.x && board.enemy1.y == newY){\n\t\t\t\t\t\t\tboard.enemy1.takeDamage();\n\t\t\t\t\t\t\tif(board.enemy1.enemyDead){\n\t\t\t\t\t\t\t\tmoveUpDown(newY);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(board.enemy2.x == board.player.x && board.enemy2.y == newY){\n\t\t\t\t\t\t\tboard.enemy2.takeDamage();\n\t\t\t\t\t\t\tif(board.enemy2.enemyDead){\n\t\t\t\t\t\t\t\tmoveUpDown(newY);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(board.enemy3.x == board.player.x && board.enemy3.y == newY){\n\t\t\t\t\t\t\tboard.enemy3.takeDamage();\n\t\t\t\t\t\t\tif(board.enemy3.enemyDead){\n\t\t\t\t\t\t\t\tmoveUpDown(newY);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tenemiesMove();\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 39:\n\t\t\t\t\t// right key pressed\n\t\t\t\t\tvar newX = board.player.x + 1;\n\t\t\t\t\tif(board.player.x == 9)\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tif(board.position[newX][board.player.y] == 0 || board.position[newX][board.player.y] == 5)\n\t\t\t\t\t{\n\t\t\t\t\t\tconsole.log(\"Right was pressed...\\n\");\n\t\t\t\t\t\trestoreHealth(newX,board.player.y);\n\t\t\t\t\t\tmoveLeftRight(newX);\n\t\t\t\t\t\tenemiesMove();\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\telse if(board.position[newX][board.player.y] == 3){\n\t\t\t\t\t\tconsole.log(\"Enemy is taking damage...\");\n\t\t\t\t\t\t\tif(board.enemy1.x == newX && board.enemy1.y == board.player.y){\n\t\t\t\t\t\t\tboard.enemy1.takeDamage();\n\t\t\t\t\t\t\tif(board.enemy1.enemyDead){\n\t\t\t\t\t\t\t\tmoveLeftRight(newX);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(board.enemy2.x == newX && board.enemy2.y == board.player.y){\n\t\t\t\t\t\t\tboard.enemy2.takeDamage();\n\t\t\t\t\t\t\t\tif(board.enemy2.enemyDead){\n\t\t\t\t\t\t\t\tmoveLeftRight(newX);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(board.enemy3.x == newX && board.enemy3.y == board.player.y){\n\t\t\t\t\t\t\tboard.enemy3.takeDamage();\n\t\t\t\t\t\t\t\tif(board.enemy3.enemyDead){\n\t\t\t\t\t\t\t\tmoveLeftRight(newX);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tenemiesMove();\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 40:\n\t\t\t\t\t// down key pressed\n\t\t\t\t\tvar newY = board.player.y + 1;\n\t\t\t\t\tif(board.player.y == 9)\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tif(board.position[board.player.x][newY] == 0 || board.position[board.player.x][newY] == 5)\n\t\t\t\t\t{\n\t\t\t\t\t\tconsole.log(\"Down was pressed...\\n\");\n\t\t\t\t\t\trestoreHealth(board.player.x,newY);\n\t\t\t\t\t\tmoveUpDown(newY);\n\t\t\t\t\t\tenemiesMove();\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\telse if(board.position[board.player.x][newY] == 3){\n\t\t\t\t\t\tconsole.log(\"Enemy is taking damage...\");\n\t\t\t\t\t\t\tif(board.enemy1.x == board.player.x && board.enemy1.y == newY){\n\t\t\t\t\t\t\tboard.enemy1.takeDamage();\n\t\t\t\t\t\t\tif(board.enemy1.enemyDead){\n\t\t\t\t\t\t\t\tmoveUpDown(newY);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(board.enemy2.x == board.player.x && board.enemy2.y == newY){\n\t\t\t\t\t\t\tboard.enemy2.takeDamage();\n\t\t\t\t\t\t\tif(board.enemy2.enemyDead){\n\t\t\t\t\t\t\t\tmoveUpDown(newY);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(board.enemy3.x == board.player.x && board.enemy3.y == newY){\n\t\t\t\t\t\t\tboard.enemy3.takeDamage();\n\t\t\t\t\t\t\tif(board.enemy3.enemyDead){\n\t\t\t\t\t\t\t\tmoveUpDown(newY);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tenemiesMove();\n\t\t\t\t\t}\n\t\t\t\t\tbreak; \n\t\t\t}\n\t\t\t//console.log(\"heres our current player position in moveSomething \"+board.player.x + board.player.y);\n\t\t\t}\t//console.log(\"heres our previous player position in moveSomething \"+board.player.xPrev + board.player.yPrev);\t\t\n\t\t}",
"checkEnemyRemoval() {\n for (let enemyIndex = 0; enemyIndex < this.enemies.length; enemyIndex++) {\n let removeEnemy = false;\n const enemyToCheck = this.enemies[enemyIndex];\n if (enemyToCheck.pos.x <= -this.level.tileWidth && enemyToCheck.movement.x < 0) removeEnemy = true;\n if (enemyToCheck.pos.x >= this.level.widthPixels() && enemyToCheck.movement.x > 0) removeEnemy = true;\n if (removeEnemy) {\n this.enemies.splice(enemyIndex, 1);\n enemyIndex--;\n }\n }\n }",
"function basicEnemy(x, y, angle, speed){\n var newEnemy = new enemy(x, y, angle, speed);\n newEnemy.maxHealth = 10;\n newEnemy.health = 10;\n newEnemy.score = 10;\n\tnewEnemy.name = \"Alien Invader\";\n\tnewEnemy.weight = 50; // inflicts 50 damage if player crashes into it\n\tnewEnemy.height = 30;\n\t\n\t// color: blue color by default, adjust by setColor function\n\tnewEnemy.color = \"#0000FF\";\n\t\n\t// setColor function: to customize the color of this enemy:\n\t// PARAMETER: a color string (e.g. \"#FF0000\")\n\tnewEnemy.setColor = function(newColor){\n\t\tthis.color = newColor;\n\t}\n\n // balance: this variable is used to animate the enemy (see draw function)\n newEnemy.balance = -10;\n newEnemy.dBalance = (30/FPS); // change in balance per frame based on FPS\n\n\t// add a weapon to this enemy that shoots a single bullet at a random interval\n newEnemy.addWeapon(new enemyWeapon(Math.ceil(20 + getRandNum(30))))\n .onShootEvent = function(enemy){\n var bul1 = BulletFactory.enemyBullet(14, 0, \n enemy.getAngle(), \n 6, 10);\n rotatePoint(bul1, enemy.getAngle());\n translatePoint(bul1,enemy.getX(), enemy.getY());\n\n enemy.enemySys.addBullet(bul1);\n }\n\t\n\t// add a triangular collision object to this enemy\n newEnemy.addCollision(new standardCollision(25))\n .addObject(new cTriangle({x:15,y:0},{x:-10,y:10},{x:-10,y:-10}));\n \n\t// OVERRIDE\n\t// function called by enemy abstract class when enemy falls off screen:\n\t//\tThis function resets the enemy position to the top of the screen at a\n\t//\trandom X position.\n newEnemy.onOutOfScreen = function(){\n this.y = -30;\n this.x = getRandNum(areaWidth - 60) + 30;\n this.setSpeed(getRandNum(3) + 1);\n\t\tthis.normalSpeed = this.speed;\n }\n\n\t// OVERRIDE\n // Draw function called each frame to draw this enemy onto the canvas.\n\t//\tThis draws the enemies specific appearance and animations\n newEnemy.draw = function(ctx){\n // update enemy animation (using balance variable)\n if(this.balance>=10)\n this.balance=-10;\n else // update balance based on dBalance (change value)\n this.balance += this.dBalance;\n \n\t\t// save context (start new drawing stack)\n ctx.save();\n\t\t// move context to enemy's x and y position\n ctx.translate(this.getX(), this.getY());\n // rotate context\n ctx.rotate(this.angle);\n\t\t// set stroke (lines) to BLUE color\n ctx.strokeStyle = this.color;\n \n\t\t// start drawing enemy\n ctx.beginPath();\n ctx.moveTo(-13, -this.balance);\n ctx.lineTo(15, 0);\n ctx.closePath();\n ctx.stroke();\n \n ctx.fillStyle = \"#FFFAF0\";\n ctx.beginPath();\n ctx.moveTo(-10, 0);\n ctx.lineTo(15, 0);\n ctx.lineTo(-10, -10);//?\n ctx.closePath();\n ctx.fill();\n ctx.stroke();\n \n ctx.fillStyle = \"#CFAF8F\";\n ctx.beginPath();\n ctx.moveTo(-10, 0);\n ctx.lineTo(15, 0);\n ctx.lineTo(-10, 10);\n ctx.closePath();\n ctx.fill();\n ctx.stroke();\n \n ctx.beginPath();\n ctx.moveTo(-13, this.balance);\n ctx.lineTo(15, 0);\n ctx.closePath();\n \n ctx.stroke();\n \n //--------Collision circle-------\n /*\n ctx.strokeStyle = \"#FF00FF\";\n ctx.beginPath();\n ctx.arc(0, 0, 40,0,Math.PI*2,true);\n ctx.closePath();\n ctx.stroke();\n */\n //-------------------------------\n \n\t\t// restore the context draw stack (finish drawing this enemy)\n ctx.restore();\n }\n \n\t// when enemy dies, create a blue round explosion\n newEnemy.deathEffect = function(){\n this.enemySys.addEffect(this.enemySys.effectSys.basicBlueExplosion(this.getX(), this.getY()));\n }\n \n\t// when enemy is hit by a bullet, create a spark on the side that the bullet hit\n newEnemy.hitEffect = function(x, y){\n\t\t// create an angle\n var angle;\n\t\t// if bullet hit from the right, shift angle to the right side\n if(x > this.x)\n angle = Math.PI/3;\n\t\t// if bullet hit from the left, shift angle to the left side\n else if(x < this.x)\n angle = (2*Math.PI)/3;\n\t\t// otherwise, it hit in the middle so create the effect directed down\n else\n angle = (3*Math.PI)/2;\n\t\t// push the effect into the enemySys effect system\n this.enemySys.addEffect(this.enemySys.effectSys.basicSpark(x, y, angle));\n }\n\t\n\t// when enemy is burned by a laser, create a circular spart on the location of impact\n\tnewEnemy.burnEffect = function(x, y){\n\t\tthis.enemySys.addEffect(this.enemySys.effectSys.basicBurnEffect(x, y));\n\t}\n return newEnemy;\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}",
"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 MoveEnemies () {\n if (ENEMIES.length || ENEMIES_WAITING.length) {\n ENEMIES.map(function (enemy) { \n if (enemy.y < CANVAS_HEIGHT-enemy.height) {\n DrawEnemy(enemy); \n enemy.y++;\n } \n else {\n ENEMIES.shift();\n }\n });\n }\n else {\n console.log('No enemies left!');\n }\n }",
"onPlayerDeath(event) {\n const player = server.playerManager.getById(event.playerid);\n if (!player)\n return; // the |player| couldn't be found, this is an invalid death\n\n if (!this.playersInDeathMatch_.has(player))\n return;\n\n const killer = server.playerManager.getById(event.killerid);\n if (!killer)\n return;\n\n if (!this.playersInDeathMatch_.has(killer))\n return;\n\n const playerSnapshot = this.playerStats_.get(player);\n const playerStatistics = player.stats.diff(playerSnapshot);\n\n const killerSnapshot = this.playerStats_.get(killer);\n const killerStatistics = killer.stats.diff(killerSnapshot);\n\n const health = killer.health;\n const armour = killer.armour;\n\n killer.health = 100;\n killer.armour = Math.min(armour + health, 100);\n\n killer.sendMessage(Message.DEATH_MATCH_TOTAL_KILLED, killerStatistics.killCount);\n player.sendMessage(Message.DEATH_MATCH_TOTAL_DEATHS, playerStatistics.deathCount);\n\n this.addKillToTeamForPlayer(killer);\n }",
"function updateLives() {\n // detecting contact between the player and the paperAgenda\n if (isCollided(player._spriteRun, paperAgendas[0]) == true) {\n paperAgendas.splice(0, 1);\n if (playerLives > 0) {\n playerLives -= 1;\n } else {\n // when game ends, plays die audio\n endGame();\n dieAudio.play();\n }\n\n updateLivesHTML();\n }\n}",
"function timeAttack() {\n ui.setText(\"EnemyCounter\", \"\");\n if (game.enemiesAlive == 0 && !game.waveActive) {\n ui.setText(\"Timer\", Math.floor(game.countDown));\n waveCooldown();\n } else if (game.waveActive) {\n game.countDown = game.countDown - (1 / 60);\n ui.setText(\"Timer\", Math.floor(game.countDown));\n if (game.enemiesAlive < 10) {\n gameWorld.createEnemy();\n }\n }\n if (game.countDown <= 0) {\n gameWorld.player.death();\n }\n}",
"distributeEnemy(){\n this.x = -200; \n this.y = y_axis[Math.floor(Math.random() * y_axis.length)];\n this.speed = speedEnemy[Math.floor(Math.random() * y_axis.length)];\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get the keyboard shortcut | function getKeyboardShortcut(intent, speechCallback) {
var speechOutput = getSpeechOutput(intent.slots.OperationName.value);
speechCallback(":tell", speechOutput, getRepromptText("keyboard shortcut"));
} | [
"_keyboardShortcuts() {\n browser.commands.onCommand.addListener((command) => {\n if (command === 'action-accept-new') {\n this.app.modules.calls.callAction('accept-new')\n } else if (command === 'action-decline-hangup') {\n this.app.modules.calls.callAction('decline-hangup')\n } else if (command === 'action-dnd') {\n // Only toggle when calling options are enabled and webrtc is enabled.\n if (!this.app.helpers.callingDisabled() && this.app.state.settings.webrtc.enabled) {\n this.app.setState({availability: {dnd: !this.app.state.availability.dnd}})\n }\n } else if (command === 'action-hold-active') {\n this.app.modules.calls.callAction('hold-active')\n }\n })\n }",
"updateShortcut_() {\n this.removeAttribute('shortcutText');\n\n if (!this.command_ || !this.command_.shortcut ||\n this.command_.hideShortcutText) {\n return;\n }\n\n const shortcuts = this.command_.shortcut.split(/\\s+/);\n\n if (shortcuts.length === 0) {\n return;\n }\n\n const shortcut = shortcuts[0];\n const mods = {};\n let ident = '';\n shortcut.split('|').forEach(function(part) {\n const partUc = part.toUpperCase();\n switch (partUc) {\n case 'CTRL':\n case 'ALT':\n case 'SHIFT':\n case 'META':\n mods[partUc] = true;\n break;\n default:\n console.assert(!ident, 'Shortcut has two non-modifier keys');\n ident = part;\n }\n });\n\n let shortcutText = '';\n\n ['CTRL', 'ALT', 'SHIFT', 'META'].forEach(function(mod) {\n if (mods[mod]) {\n shortcutText += loadTimeData.getString('SHORTCUT_' + mod) + '+';\n }\n });\n\n if (ident === ' ') {\n ident = 'Space';\n }\n\n if (ident.length !== 1) {\n shortcutText += loadTimeData.getString('SHORTCUT_' + ident.toUpperCase());\n } else {\n shortcutText += ident.toUpperCase();\n }\n\n this.setAttribute('shortcutText', shortcutText);\n }",
"function GetDefaultKeyboardController() {\n return controllers.get(-1);\n}",
"async function updateShortcut() {\n await browser.commands.update({\n name: commandName,\n shortcut: document.querySelector('#shortcut').value\n });\n}",
"addShortcut(keys, callback) {\n Mousetrap.bind(keys, callback)\n }",
"function fixShortcut( name ) {\n\tif ( isMac ) {\n\t\tname = name.replace('Ctrl', 'Cmd');\n\t} else {\n\t\tname = name.replace('Cmd', 'Ctrl');\n\t}\n\treturn name;\n}",
"function getKeyCode(taste) {\r\n taste = taste.toLowerCase();\r\n var alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];\r\n var keycode = 0;\r\n for (a = 0; a < alphabet.length; a++) {\r\n var index = a + 65;\r\n if (alphabet[a] == taste) {keycode = index; break}\r\n }\r\n return keycode;\r\n}",
"function getElementByKeyCode( keyCode ) {\n return document .querySelector( `[data-key=\"${keyCode}\"]` );\n}",
"getFullLink(shortcut) {\n for (let i = 0; i < this.config.links.length; i++) {\n if (shortcut == this.config.links[i].command) {\n return this.config.links[i];\n }\n }\n return null;\n }",
"function getKey(e){\r\n\tif (e == null) { // ie\r\n\t\tkeycode = event.keyCode;\r\n\t} else { // mozilla\r\n\t\tkeycode = e.which;\r\n\t}\r\n\tkey = String.fromCharCode(keycode).toLowerCase();\r\n\t\r\n\tif(key == 'x'){ hideLightbox(); }\r\n}",
"_mnemonicChar(mnemonic, label = '') {\n const index = label.indexOf('&')\n if (index !== -1 && index + 1 < label.length) {\n return label.charAt(index + 1)\n } else if (mnemonic.trim()) {\n return mnemonic.trim()[0].toLowerCase()\n }\n return ''\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}",
"get keyName() {\n const prefix = this.guildIDs ? this.guildIDs.join(',') : 'global';\n return `${prefix}:${this.commandName}`;\n }",
"function addCmd(key, ctrlEqualsCmd) {\n if (!ctrlEqualsCmd) return key;\n var keyAr = _underscore2.default.isArray(key) ? key : [key];\n var newAr = keyAr.reduce(function (c, k) {\n var n = k.replace('ctrl+', 'meta+');\n if (n !== k) c.push(n);\n return c;\n }, keyAr.slice());\n return newAr.length === keyAr.length ? key : newAr;\n}",
"function writeAccelerator() {\n\tdocument.getElementById('accelerator').value = accelerator.ctrl ? 'CTRL ' : '';\n\tdocument.getElementById('accelerator').value += accelerator.alt ? 'ALT ' : '';\n\tdocument.getElementById('accelerator').value += accelerator.shift ? 'SHIFT ' : '';\n\tdocument.getElementById('accelerator').value += String.fromCharCode(accelerator.key);\n}",
"async function pressShortcut(t, shortcutUsingCtrl) {\n if (shortcutUsingCtrl === undefined) {\n throw (\n \"pressShortcut expecting a shortcut string like 'ctrl-a' but got undefined. \" +\n \"Did you forget to pass t?\"\n );\n }\n var shortcut;\n if (t.browser.os.name == \"macOS\") {\n shortcut = shortcutUsingCtrl.replace(\"ctrl\", \"meta\");\n } else {\n shortcut = shortcutUsingCtrl;\n }\n await t.pressKey(shortcut);\n}",
"function extendedOnKeyPress() {\r\n this._handleEscapeToHome()\r\n originalOnKeyPress()\r\n }",
"handleBoardKeyPress(e) {\n if (!this.state.helpModalOpen && !this.state.winModalOpen) {\n if (49 <= e.charCode && e.charCode <= 57) {\n this.handleNumberRowClick((e.charCode - 48).toString());\n // undo\n } else if (e.key === \"r\") {\n this.handleUndoClick();\n // redo\n } else if (e.key === \"t\") {\n this.handleRedoClick();\n // erase/delete\n } else if (e.key === \"y\") {\n this.handleEraseClick();\n // notes\n } else if (e.key === \"u\") {\n this.handleNotesClick();\n }\n }\n }",
"function letterPressed(event) {\n // Use the letter pressed for finding the button\n var myBtn = \"btn\" + event.code;\n \n if (modalIsOn) {\n modalOff();\n return;\n }\n \n // Make the function call if the space bar is clicked\n if (event.keyCode === 32) {\n //var currBtn = \"btn\" + getCode(currBtnValue);\n //document.getElementById(currBtn).click();\n if (oneSwitchGoing){\n document.getElementById(scanBoard[scanSpot]).click();\n --scanSpot;\n }\n } else if (event.keyCode >= 65 && event.keyCode <= 90) {\n document.getElementById(myBtn).click();\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
APPROACH Tabulation solution from the recursive solution below, we gather the recurrence relation let i be the sum value let j be the index in coins array, referring to the current coin if sum coins[i] 0, then result = (i, j 1) + (i j, j) with this recurrence relation, we can construct a 2d array, with sum as row, coins index as col Time: O(nm) where n is the size of coins array, m the size of sum Space: O(nm) | function dynamicProgramming(coins, sum) {
if (coins.length < 1) return 0
const table = [...Array(sum + 1)].map(e => Array(coins.length + 1).fill(0))
// when sum is 0, there's 1 way to fulfil it. simply by doing nothing
for (let i = 0; i < table[0].length; i++) {
table[0][i] = 1
}
for (let i = 1; i < table.length; i++) {
for (let j = 1; j < table[i].length; j++) {
table[i][j] = table[i][j-1]
if (i - coins[j-1] >= 0) {
table[i][j] += table[i-coins[j-1]][j]
}
}
}
console.log(table)
return table[table.length-1][table[0].length-1]
} | [
"function toCoins(amount, coins) {\r\n if (amount == 0) {\r\n return []\r\n } else {\r\n let reminder = amount;\r\n let output = [];\r\n for (let x=0; x < coins.length; x++) {\r\n if (reminder / coins[x] >= 1) {\r\n let howManyCoins = Math.floor(reminder / coins[x]);\r\n reminder = reminder % coins[x];\r\n for (let i=1; i <= howManyCoins; i++) {\r\n output.push(coins[x]);\r\n }\r\n }\r\n }\r\n return output;\r\n }\r\n}",
"function solution_1 (matrix) {\r\n let row1 = matrix[0];\r\n let total = row1.reduce((total, num) => total + num);\r\n if (matrix.length === 1) return total;\r\n let row2;\r\n for (let row = 1; row < matrix.length; ++row) {\r\n row2 = [matrix[row][0]];\r\n total += row2[0];\r\n for (let col = 1; col < row1.length; ++col) {\r\n if (matrix[row][col]) {\r\n const newNum = Math.min(row2[row2.length - 1], row1[col - 1], row1[col]) + 1;\r\n row2.push(newNum);\r\n total += newNum;\r\n } else {\r\n row2.push(0);\r\n }\r\n }\r\n row1 = row2;\r\n }\r\n return total;\r\n}",
"function getLeastCoins(n) {\n const coins = [25, 10, 5, 1];\n let res = [];\n\n let remain = n;\n for ( let c = 0; c < coins.length; c++) {\n let quotient = Math.floor(remain / coins[c]);\n remain = remain - quotient * coins[c];\n\n res.push(quotient);\n }\n\n let count = 0;\n for (let i = 0; i < 4; i++) {\n count += res[i];\n }\n\n console.log(res);\n return count;\n}",
"function twoSums(nums, target) {\n\n let idx1 = 0, idx2 = 1\n for (let i = 0; i < nums.length - 1; i++) {\n idx1 = i\n for (let j = i + 1; j < nums.length; j++) {\n idx2 = j\n if (nums[i] + nums[i + 1] == target) {\n return [idx1, idx2]\n }\n }\n }\n}",
"function c(N, K) {\n var C = [];\n for (let n=0; n<=N; n++) {\n C[n] = [1]\n C[0][n] = 0\n }\n for (let n=1; n<=N; n++) {\n for (let k=1; k<=N; k++) {\n let k0 = (k <= n-k) ? k : n-k\n if (n < k)\n C[n][k] = 0\n else if (n===k)\n C[n][k] = 1\n else\n C[n][k] = C[n][n-k] = C[n-1][k0-1] + C[n-1][k0]\n }\n }\n /*\n for(let n=0; n<=N; n++) {\n console.log(\"C[%d]=%j\", n, C[n])\n }\n */\n return C[N][K];\n}",
"solution(arr, x) {\n\n // Sort the array \n arr.sort();\n console.log(arr)\n // To store the closets sum \n let closestSum = 99999;\n\n // Fix the smallest number among \n // the three integers \n for (let i = 0; i < arr.length - 2; i++) {\n\n // Two pointers initially pointing at \n // the last and the element \n // next to the fixed element \n let left = i + 1, right = arr.length - 1;\n\n // While there could be more pairs to check \n while (left < right) {\n\n // Calculate the sum of the current triplet \n let currentSum = arr[i] + arr[left] + arr[right];\n\n // If the sum is more closer than \n // the current closest sum \n if (Math.abs(x - currentSum) < Math.abs(x - closestSum)) {\n closestSum = currentSum;\n }\n\n // If sum is greater then x then decrement \n // the second pointer to get a smaller sum \n if (currentSum > x) {\n right--;\n }\n\n // Else increment the first pointer \n // to get a larger sum \n else {\n left++;\n }\n }\n }\n\n // Return the closest sum found \n return closestSum;\n }",
"function minesweeper(matrix = []) {\n\n let mm = [];\n for (let i = 0; i < matrix.length; i++) {\n mm.push([])\n }\n\n for (let i = 0; i < matrix.length; i++) {\n for (let j = 0; j < matrix[i].length; j++) {\n if (matrix[i][j]) {\n mm[i][j] = 1;\n\n } else {\n // 00\n if (i == 0 && j == 0) {\n mm[i][j] = (matrix[i][j + 1]) + (matrix[i + 1][j]);\n\n }\n // 01\n else if (i == 0 && j > 0 && j !== matrix[i].length - 1) {\n mm[i][j] = (matrix[i][j - 1]) + (matrix[i][j + 1]) + (matrix[i + 1][j])\n }\n //02\n else if (i == 0 && j == matrix[i].length - 1) {\n mm[i][j] = (matrix[i][j - 1]) + (matrix[i + 1][j]);\n\n }\n\n // 20\n else if (i == matrix.length - 1 && j == 0) {\n mm[i][j] = (matrix[i - 1][j]) + (matrix[i][j + 1]);\n\n }\n\n // 21\n else if (i == matrix.length - 1 && j > 0 && j !== matrix[i].length - 1) {\n mm[i][j] = (matrix[i][j - 1]) + (matrix[i][j + 1]) + (matrix[i - 1][j])\n\n }\n // 22\n else if (i == matrix.length - 1 && j == matrix[i].length - 1) {\n mm[i][j] = (matrix[i][j - 1]) + (matrix[i - 1][j])\n\n }\n // 10\n else if (i > 0 && i !== matrix.length - 1 && j == 0) {\n mm[i][j] = (matrix[i - 1][j]) + (matrix[i + 1][j]) + (matrix[i][j + 1])\n\n }\n // 12\n else if (i > 0 && i !== matrix.length - 1 && j == matrix[i].length - 1) {\n mm[i][j] = (matrix[i - 1][j]) + (matrix[i + 1][j]) + (matrix[i][j - 1])\n } else {\n mm[i][j] = (matrix[i][j + 1]) + (matrix[i][j - 1]) + (matrix[i + 1][j]) + (matrix[i - 1][j])\n }\n mm[i][j] = mm[i][j] == 0 ? 1 : mm[i][j];\n\n\n }\n\n\n }\n\n }\n return mm;\n}",
"function pairwise(arr, arg){\n var sumOfIndex = [];\n\n for(var i = 0; i < arr.length; i++){\n for(var j = 1; j < arr.length; j++){\n if(i === j){\n break;\n } else if(i < j && arr[i] + arr[j] === arg && sumOfIndex.indexOf(+i) === -1 && sumOfIndex.indexOf(+j) === -1){\n console.log(arr[i]);\n console.log(arr[j]);\n sumOfIndex.push(+i, +j);\n break;\n }\n }\n }\n\n var sum = sumOfIndex.reduce(function(accumulator, currentValue){\n return accumulator + currentValue;\n }, 0);\n\n return sum;\n}",
"function findOptimalCombination(cities, i, j) {\n\n var m_profits = cities[i][j].profits_array;\n var e_profits = cities[i][j - 1].profits_array;\n var o_profits = cities[i][j - 2].profits_array;\n var g_profits = cities[i][j - 3].profits_array;\n var n_profits = cities[i][j - 4].profits_array;\n\n var biggest_sum = 0;\n var optimal_combination = [0, 0, 0, 0, 0];\n\n var new_sum;\n\n for (var m = 0; m < m_profits.length; m++) {\n\n for (var e = 0; e < e_profits.length; e++) {\n\n for (var o = 0; o < o_profits.length; o++) {\n\n for (var g = 0; g < g_profits.length; g++) {\n\n for (var n = 0; n < n_profits.length; n++) {\n\n new_sum = m_profits[m] + e_profits[e] + o_profits[o] + g_profits[g] + n_profits[n];\n\n if (\n (new_sum > biggest_sum) &&\n ((m != e || e == 4) && (m != o || o == 3) && (m != g || g == 2) && (m != n || n == 1)) &&\n ((e != o || o == 3) && (e != g || g == 2) && (e != n || n == 1)) &&\n ((o != g || g == 2) && (o != n || n == 1)) &&\n ((g != n || n == 1))\n ) {\n biggest_sum = new_sum;\n optimal_combination[4] = m;\n optimal_combination[3] = e;\n optimal_combination[2] = o;\n optimal_combination[1] = g;\n optimal_combination[0] = n;\n }\n\n }\n\n }\n\n }\n\n }\n\n }\n\n cities[i][j].optimal_combination = optimal_combination;\n\n}",
"function nonConstructibleChange(coins) {\n // Sort array\n const sortedCoins = coins.sort((a, b) => (a - b));\n let change = 0;\n // Find smallest sum that does not exist in array\n // Algo: If we have coins sorted - if next coin is greater than 1st coin + 1, we cannot make 1st coin + 1 change\n for (let i = 0; i < sortedCoins.length; i++) {\n if (sortedCoins[i] > (change + 1)) {\n return change + 1;\n }\n change += sortedCoins[i];\n }\n\n return change + 1;\n}",
"function luckBalance(k, contests) {\n let result = 0;\n contests.sort(function(a,b) {\n return b[0]-a[0];\n });\n console.log(contests);\n for(let i = 0; i < contests.length; i++){\n if(contests[i][1] == 0){\n result = result + contests[i][0];\n }\n else {\n if(k > 0){\n k--;\n result += contests[i][0];\n } else {\n result -= contests[i][0];\n }\n }\n }\n return result;\n}",
"function runningSum(nums) {\n let arr = [];\n for(let i = 0; i < nums.length; i++) {\n if(i===0) {\n arr.push(nums[i])\n } else {\n arr.push(nums[i] + arr[i - 1]);\n };\n };\n return arr;\n}",
"function sumUpDiagonals(arr){\n let sum = 0;\n for(let i=0; i<arr.length; i++){\n for(let j=i; j<i+1; j++){\n sum += arr[i][j];\n }\n for(let j=arr.length-1-i; j>arr.length-2-i; j--){\n sum += arr[i][j];\n }\n }\n return sum;\n}",
"function runningSum(nums) {\n const result = []\n \n nums.reduce((acc, curr) => {\n result.push(acc + curr)\n return acc + curr\n }, 0)\n \n return result;\n}",
"function solve0(matrix) {\n // Write your code here\n // Track the count\n let count = 0;\n // Loop through outer array\n for(let i=0; i<matrix.length; i++) {\n // Loop through inner array\n for(let j=0; j<matrix[i].length; j++){\n // Increment count if inner el is even\n if(matrix[i][j] % 2 === 0) {\n count ++\n }\n }\n }\n // console.log(count)\n return count\n}",
"function memoized_coin_change(lst_of_denominations, amount){\n // Your solution here\n const mem = [];\n const deno = reverse(lst_of_denominations);\n const len = length(deno);\n \n for(let i = 0; i <= amount; i = i + 1){\n mem[i] = -1;\n }\n \n mem[0] = 0;\n \n for(let i = deno; !is_empty_list(i); i = tail(i)){\n const cur = head(i);\n mem[cur] = 1;\n }\n \n for(let i = 0; i <= amount; i = i + 1){\n if(mem[i] !== -1){\n continue;\n } else {\n let smallest = amount + 1;\n for(let j = deno; !is_empty_list(j); j = tail(j)){\n const cur = i - head(j);\n if(cur < 0){\n continue;\n } else {\n if(mem[cur] !== -1){\n if(mem[cur] < smallest){\n smallest = mem[cur];\n } else { }\n } else { }\n }\n }\n if(smallest < amount + 1){\n mem[i] = smallest + 1;\n } else { }\n }\n }\n \n return mem[amount];\n}",
"function solve(w, h, data_array) {\n\tvar k = 0;\n\tvar city_xs = [];\n\tvar city_ys = [];\n\tvar city_is = [];\n\tfor (var y = 0; y < h; ++y) {\n\t\tfor (var x = 0; x <= w; ++x) {\n\t\t\tconst i = x + y * (w+1);\n\t\t\tif (data_array[i] == 1) {\n\t\t\t\t++k;\n\t\t\t\tcity_xs.push(x);\n\t\t\t\tcity_ys.push(y);\n\t\t\t\tcity_is.push(i);\n\t\t\t}\n\t\t}\n\t}\n\tif (k == 1) return data_array; // No changes required\n\n\tvar edges = buildEdges(w, h);\n\n\tconst mm = 1 << (k-1);\n\tconst mi = (w+1)*h;\n\tconst inf = 1000000000;\n\n\tvar dp = [[]]; // dummy unused first dimension\n\tfor (var mask = 1; mask < mm; ++mask) {\n\t\t// O(3^k n) part\n\t\tvar dists = []\n\t\tfor (var y = 0; y < h; ++y) {\n\t\t\tfor (var x = 0; x <= w; ++x) {\n\t\t\t\tconst i = x + y * (w+1);\n\t\t\t\tvar d = inf;\n\t\t\t\tfor (var submask = mask; submask != 0; submask = (submask - 1) & mask) {\n\t\t\t\t\tconst invmask = mask ^ submask;\n\t\t\t\t\tif (invmask == 0) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\td = Math.min(d, dp[submask][i] + dp[invmask][i]);\n\t\t\t\t}\n\t\t\t\tif ((data_array[i] == 0) && (d != inf)) {\n\t\t\t\t\td -= 1; // Refund one payment of the node\n\t\t\t\t}\n\t\t\t\tdists.push(d);\n\t\t\t}\n\t\t}\n\t\t\n\t\tif ((mask & (mask - 1)) == 0) {\n\t\t\tfor (var j = 0; j < k-1; ++j) {\n\t\t\t\tif (mask & (1 << j)) {\n\t\t\t\t\tdists[city_is[j]] = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// O(2^k n) part, so this doesn't affect the overall running time\n\t\tvar que = [];\n\t\tfor (var d = 0; d <= mi; ++d) {\n\t\t\tque.push([]);\n\t\t}\n\t\tfor (var i = 0; i <= mi; ++i) {\n\t\t\tif (dists[i] <= mi) {\n\t\t\t\tque[dists[i]].push(i);\n\t\t\t}\n\t\t}\n\t\tfor (var d = 0; d <= mi; ++d) {\n\t\t\tfor (var j = 0; j < que[d].length; ++j) {\n\t\t\t\t// Check if we have already handled this\n\t\t\t\tconst i = que[d][j];\n\t\t\t\tif (dists[i] < d) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// Update distances\n\t\t\t\tfor (var ti = 0; ti < edges[i].length; ++ti) {\n\t\t\t\t\tconst t = edges[i][ti];\n\t\t\t\t\tconst c = d + (data_array[t] == 0 ? 1 : 0);\n\t\t\t\t\tif (dists[t] > c) {\n\t\t\t\t\t\tdists[t] = c;\n\t\t\t\t\t\tque[c].push(t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Save the DP and continue\n\t\tdp.push(dists);\n\t}\n\n\t// Construct solution from the DP\n\tvar visited = [];\n\tfor (var mask = 0; mask < mm; ++mask) {\n\t\tvar row = [];\n\t\tfor (var i = 0; i < mi; ++i) {\n\t\t\trow.push(false);\n\t\t}\n\t\tvisited.push(row);\n\t}\n\n\tconst start_ind = city_is[k-1];\n\tbuildPaths(start_ind, mm-1, visited, edges, data_array, dp);\n\n\tvar best = [];\n\tfor (var i = 0; i < mi; ++i) {\n\t\tif (data_array[i] == 0) {\n\t\t\tvar check = false;\n\t\t\tfor (var mask = 0; mask < mm; ++mask) {\n\t\t\t\tif (visited[mask][i]) {\n\t\t\t\t\tcheck = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (check) {\n\t\t\t\tbest.push(2);\n\t\t\t} else {\n\t\t\t\tbest.push(0);\n\t\t\t}\n\t\t} else {\n\t\t\tbest.push(data_array[i]);\n\t\t}\n\t}\n\treturn best;\n}",
"function coinCombo(array, total) {\n var highestElement = Math.max(...array);\n var orderArray = array.sort();\n var coins = Math.floor(total / highestElement);\n var remainder = total % highestElement;\n orderArray.pop();\n if (remainder === 0) {\n return coins;\n } else {\n return coins + coinCombo(orderArray, remainder);\n }\n}",
"function alternateSqSum(arr){\n let newArr = []\n // happy coding :D\n for(let i = 0;i<arr.length;i++){\n if(i%2){\n newArr.push(arr[i]**2)\n }else{\n newArr.push(arr[i])\n }\n }return newArr.reduce((a,b)=>a+b,0)\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set event listeners for pagination page number buttons | setPageNumberButtinsEventListeners() {
var pageNumBtns = document.getElementsByClassName("pagination-button");
for (var i = 0; i < pageNumBtns.length; i++) {
let pageToGo = parseInt(pageNumBtns[i].innerHTML);
pageNumBtns[i].addEventListener('click', this.destPage.bind(this, pageToGo));
}
} | [
"function setTablePaginationHandlers(pagination){\n \n // Get table\n \n let table = $(pagination).siblings('.table-container').find('table.paginated');\n \n // Set event handlers for page number buttons\n \n $(pagination).find('button:not(.first, .prev, .next, .last)').each(function(){\n \n $(this).on('click', function(event){\n \n let pageNumber = parseInt($(this).html());\n setTablePagination(table, pageNumber);\n \n });\n \n });\n \n // Set event handlers for first, prev, next, and last buttons\n \n $(pagination).find('button.first').on('click', function(event){\n \n setTablePagination(table, 1);\n \n });\n \n $(pagination).find('button.prev').on('click', function(event){\n \n prevTablePage(table);\n \n });\n \n $(pagination).find('button.next').on('click', function(event){\n \n nextTablePage(table);\n \n });\n \n $(pagination).find('button.last').on('click', function(event){\n \n // Get list of table rows (includes header row, not filtered rows) and number of rows to show\n \n let tableRows = $(table).find('tr:not(.filtered)');\n let showNumber = parseInt($(table).siblings('.table-show').find('select').val());\n \n // Get number of pages needed\n \n let pages = Math.ceil((tableRows.length - 1) / showNumber);\n \n setTablePagination(table, pages);\n \n });\n \n}",
"function setupPagingNavigationEvents(p_name) {\n\n var l_next_obj = jQuery('#' + p_name + '_Pager_center').find('td[id=\"next_' + p_name + '_Pager\"]');\n var l_first_obj = jQuery('#' + p_name + '_Pager_center').find('td[id=\"first_' + p_name + '_Pager\"]');\n var l_last_obj = jQuery('#' + p_name + '_Pager_center').find('td[id=\"last_' + p_name + '_Pager\"]');\n var l_prev_obj = jQuery('#' + p_name + '_Pager_center').find('td[id=\"prev_' + p_name + '_Pager\"]');\n var l_pager_input = jQuery('span[id=\"sp_1_' + p_name + '_Pager\"]').siblings('input');\n\n l_pager_input\n .unbind('blur')\n .bind('blur', function() {\n if (grid_current_pages[p_name] != l_pager_input.val()) {\n pagingRecords(p_name);\n }\n });\n\n l_next_obj\n .unbind('click')\n .bind('click', function() {\n if ((l_pager_input.val() * 1) != (grid_page_totals[p_name] * 1)) {\n l_pager_input.val((l_pager_input.val() * 1) + 1);\n pagingRecords(p_name);\n }\n });\n\n l_last_obj\n .unbind('click')\n .bind('click', function() {\n l_pager_input.val(grid_page_totals[p_name]);\n pagingRecords(p_name);\n });\n\n l_prev_obj\n .unbind('click')\n .bind('click', function() {\n if ((l_pager_input.val() * 1) != 1) {\n l_pager_input.val(((l_pager_input.val() * 1) - 1));\n pagingRecords(p_name);\n }\n });\n\n l_first_obj\n .unbind('click')\n .bind('click', function() {\n l_pager_input.val(1);\n pagingRecords(p_name);\n });\n }",
"function initPaging() {\n vm.pageLinks = [\n {text: \"Prev\", val: vm.pageIndex - 1},\n {text: \"Next\", val: vm.pageIndex + 1}\n ];\n vm.prevPageLink = {text: \"Prev\", val: vm.pageIndex - 1};\n vm.nextPageLink = {text: \"Next\", val: vm.pageIndex + 1};\n }",
"setProductPerPageSelectionEventListener() {\n var selectSection = document.getElementById('select-page-limit');\n selectSection.addEventListener('change', this.setPageLimit.bind(this));\n }",
"function addPagination (list) {\n\n const noOfButtons = Math.ceil(list.length/itemsPerpage); // This dynamically creates a number value depending on the length of the data list and the value of itemsperPage\n buttonContainer.innerHTML = ''; // This clears the button ul container. Making sure there is nothing there before we append the buttons.\n\n for(let i =1; i <= noOfButtons; i++){ // This loop appends a list item and button to the DOM. The condition depends on the value of noOfButtons\n const button = `\n <li>\n <button type=\"button\">${i}</button>\n </li>\n `;\n buttonContainer.insertAdjacentHTML('beforeend', button); // Appending list items and buttons to the DOM.\n }\n const firstButton = document.querySelector('.link-list > li > button');\n firstButton.className = 'active'; // This sets the first button, which is 1, with a class of active. This indicates that the first page will be on view when it is loaded.\n \n buttonContainer.addEventListener('click', (e) =>{ // an event listener for the ulButton Container\n const pageNo = e.target.textContent; // this stores the textContent of the button the user has clicked on. I.e the number.\n if(e.target.tagName === 'BUTTON'){ // this if statement checks if the user has clicked on a button within the container\n const pagButtons = buttonContainer.querySelectorAll('li button'); // this stores all the buttons in a variable\n for(let i=0; i < pagButtons.length; i++){ // \n if(pagButtons[i].className === 'active'){ // This loop will remove all buttons with class of 'active'\n pagButtons[i].classList.remove('active');\n }\n }\n e.target.className = 'active'; // This will set whatever button the user has clicked as active\n showPage(list,parseInt(pageNo)); // the second arguement takes the number from the button the user has clicked on. \n }\n\n return console.log( parseInt(pageNo));\n });\n}",
"function pagerLinkHandler() {\n\t\t\tself.parent('form').find(settings.pagerContainer).find('a').each(function() {\n\t\t\t\t$(this).on('click', function(e) {\n\t\t\t\t\te.preventDefault();\n\t\t\t\t\tsetPage(getQueryParam($(this).attr('href'), 'page'));\n\t\t\t\t\t$(this).spinner('on');\n\t\t\t\t\tgetData();\n\t\t\t\t\treturn false;\n\t\t\t\t});\n\t\t\t});\n\t\t\t\n\t\t}",
"function paginator(){\n\t$('.paginator').click(function(e){\n\t\tvar id = $(this).attr('data-id');\n\t\tvar bid = $(this).attr('data-bid');\n\t\tvar rel = $(this).attr('data-rel');\n\t\tvar view = $(this).attr('data-view');\n\t\tshowLoader();\n\t\turl = encodeURI(\"index.php?page=\"+rel+\"&action=\"+bid+\"&pageNum=\"+id+\"&id=\"+view);\n\t\twindow.location.replace(url);\n\t});\n}",
"function page(){\n ///djahgjkhg \n\n $(\"#page\").pagination({\n pageIndex: 0,\n pageSize: 10,\n total: 100,\n debug: true,\n showInfo: true,\n showJump: true,\n showPageSizes: true,\n loadFirstPage: true,\n firstBtnText: '首页',\n lastBtnText: '尾页',\n prevBtnText: '上一页',\n nextBtnText: '下一页',\n totalName: 'total',\n jumpBtnText: '跳转',\n infoFormat: '{start} ~ {end}条,共{total}条',\n remote: {\n url:'allHistory.action' ,\n params: null,\n success: function(data) {\n htdata = data;\n var pageindex = $(\"#page\").pagination('getPageIndex');\n var pagesize = $(\"#page\").pagination('getPageSize');\n $(\"#eventLog\").empty();\n var start = pageindex * pagesize;\n var end = (pageindex + 1) * pagesize < htdata.historyList.length ? (pageindex + 1) * pagesize : htdata.historyList.length;\n updatePaper(start, end);\n }\n }\n });\n}",
"function setupPagingNavigationButtons(p_name, p_tpages, p_page) {\n var l_next_obj = jQuery('#' + p_name + '_Pager_center').find('td[id=\"next_' + p_name + '_Pager\"]');\n var l_first_obj = jQuery('#' + p_name + '_Pager_center').find('td[id=\"first_' + p_name + '_Pager\"]');\n var l_last_obj = jQuery('#' + p_name + '_Pager_center').find('td[id=\"last_' + p_name + '_Pager\"]');\n var l_prev_obj = jQuery('#' + p_name + '_Pager_center').find('td[id=\"prev_' + p_name + '_Pager\"]');\n\n if (p_tpages > 1) {\n if (p_page != p_tpages) {\n l_next_obj.removeClass('ui-state-disabled');\n l_last_obj.removeClass('ui-state-disabled');\n }\n if (p_page > 1) {\n l_prev_obj.removeClass('ui-state-disabled');\n l_first_obj.removeClass('ui-state-disabled');\n }\n }\n }",
"function generateEventForPages() {\n var classname = document.getElementsByClassName(\"pageButton\");\n\n for (var i = 0; i < classname.length; i++) {\n classname[i].addEventListener(\n \"click\",\n function(e) {\n current_page = e.toElement.innerHTML;\n textarea.value = result.mynotes[e.toElement.innerHTML].value;\n getActiveItems();\n this.classList.add(\"active\");\n },\n false\n );\n }\n }",
"function changePage(num) {\n const newPage = pageNum + num;\n if (newPage < 1 || newPage > pdfDoc.numPages) return;\n pageNum = newPage;\n setArrows(); //Hide and show arrow buttons according to the page number\n queueRenderPage(pageNum);\n}",
"function pageChange(event){\n\tvar elem = $(event.target),\n\t\tpageData = CLUB.pageData,\n\t\tselectedPage = pageData.selectedPage,\n\t\tnoOfPages = pageData.noOfPages;\n\tif(elem.hasClass('prev_page')) {\n\t\tif(selectedPage > 1) {\n\t\t\tselectedPage = selectedPage - 1;\n\t\t}\n\t} else if(elem.hasClass('next_page')) {\n\t\tif(selectedPage < noOfPages) {\n\t\t\tselectedPage = selectedPage + 1;\n\t\t}\n\t} else {\n\t\tselectedPage = Number(elem.text());\n\t}\n\tpageData.selectedPage = selectedPage;\n}",
"function Pager(){\n\tthis.routes = {};\n\n\tthis.ctx = new PageContext();\n\n\tthis.start();\n\n\tbindEvents();\n}",
"function setPageNumber() {\n\tvar selectedData = CLUB.selectedData,\n\t\tpageData = CLUB.pageData,\n\t\tpageSize = pageData.pageSize,\n\t\tselectedDataLength = selectedData.length,\n\t\tnoOfPages;\n\tif(selectedDataLength % pageSize) {\n\t\tnoOfPages = Math.floor(selectedDataLength / pageSize) + 1;\n\t} else {\n\t\tnoOfPages = Math.floor(selectedDataLength / pageSize);\n\t}\n\tpageData.noOfPages = noOfPages;\n\tpageData.selectedPage = 1;\n\tsetSelectedPageData();\n}",
"function paginationNavClick(event) {\n const linkButtons = document.querySelectorAll('.pagination ul li a');\n\n if (event.target.tagName === 'A') {\n for (let i = 0; i < linkButtons.length; i++) {\n if (linkButtons[i].innerText != event.target.innerText) {\n linkButtons[i].className = '';\n }\n else {\n event.target.className = 'active';\n }\n }\n studentDisplay(parseInt(event.target.innerText), studentTempList);\n }\n}",
"togglePaginationButtons() {\r\n let previousPageNum = this.state.currentPages[0];\r\n let nextPageNum = this.state.currentPages[2];\r\n if (previousPageNum != 0) {\r\n this.setState({disablePrev: false, disableFirst: false});\r\n } else {\r\n this.setState({disablePrev: true, disableFirst: true});\r\n }\r\n if (nextPageNum <= this.state.dataCount && nextPageNum > 1) {\r\n this.setState({disableNext: false, disableLast: false});\r\n } else {\r\n this.setState({disableNext: true, disableLast: true});\r\n }\r\n }",
"function detectArrowClicks() {\n document.getElementById('prev').addEventListener('click', function () {\n changePage(-1);\n });\n document.getElementById('next').addEventListener('click', function () {\n changePage(1);\n });\n}",
"set pageNum(pageNum) {\n this.setPageNum(pageNum);\n }",
"function appendPageLinks(list) {\n // determine how many pages for this student list \n var pages = Math.ceil(list.length/10);\n // create a page link section unobtrusively\n var link = '<div class=\"pagination\"><ul>';\n var pageArr = [];\n // “for” every page\n for (var i = 1; i <= pages; i++) {\n // add a page link to the page link section\n link += '<li><a href=\"#\">' + i + '</a></li>';\n pageArr.push(i);\n };\n link+='</ul></div>';\n\n // remove the old page link section from the site\n //$('.pagination ul li').remove();\n // append our new page link section to the site\n $('.page').append(link);\n // define what happens when you click a link\n $('.pagination ul li').click(function() {\n // Use the showPage function to display the page for the link clicked\n showPage($(this).text(),list);\n // mark that link as “active”\n $('.pagination ul li').removeClass('active');\n $(this).addClass('active');\n }); \n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
=================================================================== Script:ledOnOff() Purpose:function to switch LED on (red) or off (grey) Author:Mark Fletcher Date:21.11.2019 Input: event x LED row number yLED column number default = 'grey' rgb(128,128,128) Output: Notes: ================================================================== | function ledOnOff(event,x,y) {
//set brightness to off (0)
var brightness = 0;
//set current LED
var currentLED = document.getElementById('led('+x+','+y+')');
var LEDTest = window.getComputedStyle(currentLED, null).getPropertyValue('background-color');
//if LED off then switch on (turn red)
if (LEDTest == 'rgb(128, 128, 128)') {
currentLED.style.backgroundColor = 'red'; //rgb(255, 0, 0)
//set brightness to max (9)
brightness = 9;
}
//if LED not off then switch off (grey)
if (LEDTest != 'rgb(128, 128, 128)') {
currentLED.style.backgroundColor = 'grey'; //rgb(51, 51, 51)
//set brightness to off (0)
brightness = 0;
}
} | [
"function updateLeds() {\n if (led_state.Red===\"blink\") {\n GPIO.blink(pin_Red, blink_On, blink_Off);\n }else {\n GPIO.blink(pin_Red,0,0); //Turn off blinking\n let redlight=(led_state.Red==='1') ? 1:0 ; \n GPIO.write(pin_Red,redlight);\n }\n if (led_state.Blue===\"blink\") {\n GPIO.blink(pin_Blue, blink_On, blink_Off);\n }else {\n GPIO.blink(pin_Blue,0,0); //Turn off blinking\n let bluelight=(led_state.Blue==='1') ? 1:0 ; \n GPIO.write(pin_Blue,bluelight);\n }\n}",
"function drawStatusLED()\n {\n // Check faulted state\n var faultCount = Object.keys(fault_detector.getCurrentFaults()).length;\n if (faultCount > 0)\n {\n // Set LED to green\n image = document.getElementById('status_led');\n image.src = 'static/images/red_light.png';\n }\n else\n {\n image = document.getElementById('status_led');\n image.src = 'static/images/green_light.png';\n }\n }",
"function toggleLED(url, res) {\n var indexRegex = /(\\d)$/;\n var result = indexRegex.exec(url);\n var index = +result[1];\n \n var led = tessel.led[index];\n \n led.toggle(function (err) {\n if (err) {\n console.log(err);\n res.writeHead(500, {\"Content-Type\": \"application/json\"});\n res.end(JSON.stringify({error: err}));\n } else {\n res.writeHead(200, {\"Content-Type\": \"application/json\"});\n res.end(JSON.stringify({on: led.isOn}));\n }\n });\n}",
"function initializeLEDs() {\r\n \r\n greenLed.writeSync(0)\r\n redLed.writeSync(0)\r\n\r\n}",
"controlViaOnOff() {\n console.log(\"entrou ONOFF\")\n this.output = this.getTemp() < this.setpoint ? 1023 : 0;\n this.board.pwmWrite(19 , 0, 25, 10, this.output);\n }",
"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 flushLEDs()\r\n{\r\n\t// changedCount contains number of lights changed\r\n var changedCount = 0;\r\n\r\n // count the number of LEDs that are going to be changed by comparing pendingLEDs to activeLEDs array\r\n for(var i=0; i<80; i++)\r\n {\r\n if (pendingLEDs[i] != activeLEDs[i]) changedCount++;\r\n }\r\n\r\n // exit function if there are none to be changed\r\n if (changedCount == 0) return;\r\n\r\n //uncommenting this displays a count of the number of LEDs to be changed\r\n // //println(\"Repaint: \" + changedCount + \" LEDs\");\r\n\r\n for(var i = 0; i<80; i++)\r\n {\r\n if (pendingLEDs[i] != activeLEDs[i])\r\n { \r\n activeLEDs[i] = pendingLEDs[i];\r\n\r\n var colour = activeLEDs[i];\r\n\r\n if (i < 16) // Main Grid\r\n {\r\n var column = i & 0x7;\r\n var row = i >> 3;\r\n\r\n if (colour >=200 && colour < 328)//flashing colour numeration. need to substract 200 to get the appropriate final color\r\n {\r\n host.getMidiOutPort(1).sendMidi(0x92, 96 + row*16 + column, colour-200);\r\n }\r\n else\r\n {\r\n host.getMidiOutPort(1).sendMidi(0x9F, 96 + row*16 + column, colour);\r\n }\r\n }\r\n\r\n else if (i>=64 && i < 66) // Right buttons\r\n {\r\n host.getMidiOutPort(1).sendMidi(0x9F, 96 + 8 + (i - 64) * 16, colour);\r\n }\r\n }\r\n }\r\n}",
"changeLedsColor(binaryNumber) {\n\n let ledList = this.state.leds;\n let binaryString = binaryNumber.toString();\n\n let binaryDiff = 8 - binaryString.length;\n\n for (let i=0;i<binaryDiff;i++) {\n ledList[i].color = 'grey';\n }\n\n for (let i=0;i<binaryString.length;i++) {\n let ledIndex = i + binaryDiff;\n\n if (binaryString.charAt(i) === '1') {\n ledList[ledIndex].color = 'green';\n } else {\n ledList[ledIndex].color = 'grey';\n }\n }\n\n this.setState({leds: ledList});\n }",
"function drawLEDs() {\n\t//create LED rows\n\tfor (x=0; x<=4; x++) {\n \t//create LED columns\n \tfor (y=0; y<=4; y++) {\n \t//create LED id\n \tvar divId = '('+x+','+y+')';\n //create LED div\n \tdocument.write('<div id=\"led'+divId+'\" class=\"ledz\" onclick=\"ledOnOff'+divId+'\"></div>');\n }\n document.write('<br />');\n\t}\n}",
"function setRightLED(index, colour)\r\n{\r\n pendingLEDs[LED.SCENE + index] = colour;\r\n}",
"function turnOnLights() {\n lightsFadeIn(bulb1);\n lightsFadeIn(bulb2);\n lightsFadeIn(bulb3);\n lightsFadeIn(bulb4);\n lightsFadeIn(bulb5);\n lightsFadeIn(bulb6);\n lightsFadeIn(leftSpeaker);\n lightsFadeIn(rightSpeaker);\n lightsFadeIn(balloonsButton);\n lightsFadeIn(table);\n lightsFadeIn(cake);\n lightsFadeIn(floor);\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}",
"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 setPixelColor(event) {\n if (event.type === 'click') {\n event.target.style.backgroundColor = 'red';\n } else if (mousingDown) {\n event.target.style.backgroundColor = 'red';\n }\n }",
"setGreenLights() {\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_GREEN;});\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 getCurrentLed() {\n return led;\n}",
"function SetColor(stationId,startIndex,ledColor){\n if(!isNaN(stationId)){\n //update server's copy of the LED custer state\n colors[stationId][startIndex].r = ledColor.r;\n colors[stationId][startIndex].g = ledColor.g;\n colors[stationId][startIndex].b = ledColor.b;\n }\n\n var dataBuffer = new Uint8Array([startIndex,ledColor.r,ledColor.g,ledColor.b]);\n io.sockets.to(stationId).emit('setColor',dataBuffer);\n}",
"function setDrawingColor(event) {\n sketchController.color = this.value;\n}",
"function jkn_rdr_switch_on($id) {\n $hide = JKNRendererSwitch.cl_hide;\n jkn_rdr_switch_current().addClass($hide);\n $('#' + $id).removeClass($hide);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
checkout parameters (one per supported payment service) | function checkoutParameters(serviceName, merchantID, options) {
this.serviceName = serviceName;
this.merchantID = merchantID;
this.options = options;
} | [
"function Process() {\n var results = {};\n var arr = request.httpParameters.keySet().toArray();\n arr.filter(function (el) {\n results[el] = request.httpParameters.get(el).toLocaleString();\n return false;\n })\n\n var verificationObj = {\n ref: results.REF,\n returnmac: results.RETURNMAC,\n eci: results.ECI,\n amount: results.AMOUNT,\n currencycode: results.CURRENCYCODE,\n authorizationcode: results.AUTHORISATIONCODE,\n avsresult: results.AVSRESULT,\n cvsresult: results.CVVRESULT,\n fraudresult: results.FRAUDRESULT,\n externalreference: results.FRAUDRESULT,\n hostedCheckoutId: results.hostedCheckoutId\n\n }\n\n var order = session.getPrivacy().pendingOrder;\n var orderNo = session.getPrivacy().pendingOrderNo;\n var returnmac = session.getPrivacy().payment3DSCode;\n\n var cancelOrder = true;\n\n if (verificationObj.returnmac == returnmac) {\n var result = null;\n if(verificationObj.hostedCheckoutId != null){\n result = IngenicoPayments.getHostedPaymentStatus(verificationObj.hostedCheckoutId, true);\n }else if(verificationObj.ref){\n result = IngenicoPayments.getPaymentStatus(verificationObj.ref);\n }else{\n Logger.error(\"Missing verification reference - Params: \" + JSON.stringify(results) + \" VerificationObj: \" + JSON.stringify(verificationObj))\n }\n\n if(!result || result.error){\n Logger.warn(\"Error getting payment status: \" + JSON.stringify(result));\n app.getView({ redirect: URLUtils.url('COVerification-Confirmation', \"error=400\") }).render(\"checkout/3DSredirect\");\n return;\n }\n\n if(result.createdPaymentOutput){\n if(\"tokens\" in result.createdPaymentOutput && result.createdPaymentOutput && result.createdPaymentOutput.payment && result.createdPaymentOutput.payment.paymentOutput && result.createdPaymentOutput.payment.paymentOutput.cardPaymentMethodSpecificOutput){\n IngenicoOrderHelper.processHostedTokens(order.getCustomer(), result.createdPaymentOutput.tokens, result.createdPaymentOutput.payment.paymentOutput.cardPaymentMethodSpecificOutput)\n }\n result = result.createdPaymentOutput.payment;\n }\n \n var updatedOrderOK = UpdateOrder.updateOrderFromCallback(orderNo, result);\n\n if (result && result.status) {\n switch (result.status) {\n case ReturnStatus.REDIRECTED:\n case ReturnStatus.CAPTURE_REQUESTED:\n case ReturnStatus.PENDING_CAPTURE:\n case ReturnStatus.PENDING_PAYMENT:\n case ReturnStatus.AUTHORIZATION_REQUESTED: \n case ReturnStatus.PAID:\n case ReturnStatus.CAPTURED:\n cancelOrder = false;\n app.getView({ redirect: URLUtils.url('COVerification-Confirmation') }).render(\"checkout/3DSredirect\");\n return;\n case ReturnStatus.PENDING_FRAUD_APPROVAL:\n case ReturnStatus.PENDING_APPROVAL:\n cancelOrder = false;\n app.getView({ redirect: URLUtils.url('COVerification-Confirmation') }).render(\"checkout/3DSredirect\");\n return;\n case ReturnStatus.REJECTED:\n case ReturnStatus.REVERSED:\n case ReturnStatus.REJECTED_CAPTURE:\n case ReturnStatus.CANCELLED:\n case ReturnStatus.CHARGEBACKED: // Should never get this status back during checkout process.\n app.getView({ redirect: URLUtils.url('COVerification-COSummary') }).render(\"checkout/3DSredirect\");\n return; \n default:\n break;\n } \n }\n }\n}",
"buildPaymentRequest(cart) {\n // Supported payment instruments\n const supportedInstruments = [{\n supportedMethods: (PAYMENT_METHODS)\n }];\n\n // Payment options\n const paymentOptions = {\n requestShipping: true,\n requestPayerEmail: true,\n requestPayerPhone: true\n };\n\n let shippingOptions = [];\n let selectedOption = null;\n\n let details = this.buildPaymentDetails(cart, shippingOptions, selectedOption);\n\n // Initialize\n let request = new window.PaymentRequest(supportedInstruments, details, paymentOptions);\n\n // When user selects a shipping address, add shipping options to match\n request.addEventListener('shippingaddresschange', e => {\n e.updateWith(_ => {\n // Get the shipping options and select the least expensive\n shippingOptions = this.optionsForCountry(request.shippingAddress.country);\n selectedOption = shippingOptions[0].id;\n let details = this.buildPaymentDetails(cart, shippingOptions, selectedOption);\n return Promise.resolve(details);\n });\n });\n\n // When user selects a shipping option, update cost, etc. to match\n request.addEventListener('shippingoptionchange', e => {\n e.updateWith(_ => {\n selectedOption = request.shippingOption;\n let details = this.buildPaymentDetails(cart, shippingOptions, selectedOption);\n return Promise.resolve(details);\n });\n });\n\n return request;\n }",
"checkout(cart) {\n let request = this.buildPaymentRequest(cart);\n let response;\n // Show UI then continue with user payment info\n return request.show()\n .then(r => {\n response = r;\n // Extract just the details we want to send to the server\n var data = this.copy(response, 'methodName', 'details', 'payerEmail',\n 'payerPhone', 'shippingOption');\n data.address = this.copy(response.shippingAddress, 'country', 'region',\n 'city', 'dependentLocality', 'addressLine', 'postalCode',\n 'sortingCode', 'languageCode', 'organization', 'recipient', 'careOf',\n 'phone');\n return data;\n })\n .then(sendToServer)\n .then(() => {\n response.complete('success');\n })\n .catch(e => {\n if (response) response.complete(`fail: ${e}`);\n });\n }",
"options(params) {\n if(!params) {\n return {\n provider: _currentProvider,\n customProvider: customProvider,\n depth: depth,\n weight: weight,\n spamSeed: spamSeed,\n message: message,\n tag: tag,\n numberOfTransfersInBundle: numberOfTransfersInBundle,\n isLoadBalancing: optionsProxy.isLoadBalancing\n }\n }\n if(params.hasOwnProperty(\"provider\")) {\n _currentProvider = params.provider\n initializeIOTA()\n }\n if(params.hasOwnProperty(\"customProvider\")) {\n customProvider = params.customProvider\n initializeIOTA()\n }\n if(params.hasOwnProperty(\"depth\")) { depth = params.depth }\n if(params.hasOwnProperty(\"weight\")) { weight = params.weight }\n if(params.hasOwnProperty(\"spamSeed\")) { spamSeed = params.spamSeed }\n if(params.hasOwnProperty(\"message\")) { message = params.message }\n if(params.hasOwnProperty(\"tag\")) { tag = params.tag }\n if(params.hasOwnProperty(\"numberOfTransfersInBundle\")) { numberOfTransfersInBundle = params.numberOfTransfersInBundle }\n if(params.hasOwnProperty(\"isLoadBalancing\")) { optionsProxy.isLoadBalancing = params.isLoadBalancing }\n if(params.hasOwnProperty(\"onlySpamHTTPS\")) { onlySpamHTTPS = params.onlySpamHTTPS }\n }",
"async getAllPaymentOptions () {\n return this._api.request('InvoiceService.getAllPaymentOptions')\n }",
"paymentMethodOptions() {\n const {settings, invoices, setProp} = this.props;\n const selectedPaymentMethod = invoices.get('paymentMethod');\n const achAvailable = settings.getIn(['achInfo', 'accountNumber']);\n const ccAvailable = settings.get(['ccInfo', 'number']);\n // Determine payment options\n const paymentOptions = [];\n if (achAvailable) {\n paymentOptions.push({value: 'bank-account', name: 'Bank account'});\n // ACH only, select it\n if (!ccAvailable && selectedPaymentMethod === 'credit-card') {\n setProp('bank-account', 'paymentMethod');\n }\n }\n if (settings.get('getCcInfoSuccess')) {\n paymentOptions.push({value: 'credit-card', name: 'Credit card'});\n // CC only, select it\n if (!ccAvailable && selectedPaymentMethod === 'bank-account') {\n setProp('credit-card', 'paymentMethod');\n }\n }\n return Immutable.fromJS(paymentOptions);\n }",
"function getGoogleTransactionInfo() {\n return {\n countryCode: 'US',\n currencyCode: 'USD',\n totalPriceStatus: 'FINAL',\n // set to cart total\n totalPrice: '500.00'\n };\n}",
"function buy() { // eslint-disable-line no-unused-vars\n document.getElementById('msg').innerHTML = '';\n\n if (!window.PaymentRequest) {\n print('Web payments are not supported in this browser');\n return;\n }\n\n let details = {\n total: {label: 'Total', amount: {currency: 'USD', value: '0.50'}},\n };\n\n let networks = ['visa', 'mastercard', 'amex', 'discover', 'diners', 'jcb',\n 'unionpay', 'mir'];\n let payment = new PaymentRequest( // eslint-disable-line no-undef\n [\n {\n supportedMethods: ['https://android.com/pay'],\n data: {\n merchantName: 'Web Payments Demo',\n allowedCardNetworks: ['AMEX', 'MASTERCARD', 'VISA', 'DISCOVER'],\n merchantId: '00184145120947117657',\n paymentMethodTokenizationParameters: {\n tokenizationType: 'GATEWAY_TOKEN',\n parameters: {\n 'gateway': 'stripe',\n 'stripe:publishableKey': 'pk_live_lNk21zqKM2BENZENh3rzCUgo',\n 'stripe:version': '2016-07-06',\n },\n },\n },\n },\n {\n supportedMethods: networks,\n },\n {\n supportedMethods: ['basic-card'],\n data: {\n supportedNetworks: networks,\n supportedTypes: ['debit', 'credit', 'prepaid'],\n },\n },\n \n ],\n details,\n {\n requestShipping: true,\n requestPayerName: true,\n requestPayerPhone: true,\n requestPayerEmail: true,\n shippingType: 'shipping',\n });\n\n payment.addEventListener('shippingaddresschange', function(evt) {\n evt.updateWith(new Promise(function(resolve) {\n fetch('/ship', {\n method: 'POST',\n headers: new Headers({'Content-Type': 'application/json'}),\n body: addressToJsonString(payment.shippingAddress),\n })\n .then(function(options) {\n if (options.ok) {\n return options.json();\n }\n cannotShip('Unable to calculate shipping options.', details,\n resolve);\n })\n .then(function(optionsJson) {\n if (optionsJson.status === 'success') {\n canShip(details, optionsJson.shippingOptions, resolve);\n } else {\n cannotShip('Unable to calculate shipping options.', details,\n resolve);\n }\n })\n .catch(function(error) {\n cannotShip('Unable to calculate shipping options. ' + error, details,\n resolve);\n });\n }));\n });\n\n payment.addEventListener('shippingoptionchange', function(evt) {\n evt.updateWith(new Promise(function(resolve) {\n for (let i in details.shippingOptions) {\n if ({}.hasOwnProperty.call(details.shippingOptions, i)) {\n details.shippingOptions[i].selected =\n (details.shippingOptions[i].id === payment.shippingOption);\n }\n }\n\n canShip(details, details.shippingOptions, resolve);\n }));\n });\n\n let paymentTimeout = window.setTimeout(function() {\n window.clearTimeout(paymentTimeout);\n payment.abort().then(function() {\n print('Payment timed out after 20 minutes.');\n }).catch(function() {\n print('Unable to abort, because the user is currently in the process ' +\n 'of paying.');\n });\n }, 20 * 60 * 1000); /* 20 minutes */\n\n payment.show()\n .then(function(instrument) {\n window.clearTimeout(paymentTimeout);\n\n if (instrument.methodName !== 'https://android.com/pay') {\n simulateCreditCardProcessing(instrument);\n return;\n }\n\n let instrumentObject = instrumentToDictionary(instrument);\n instrumentObject.total = details.total;\n let instrumentString = JSON.stringify(instrumentObject, undefined, 2);\n fetch('/buy', {\n method: 'POST',\n headers: new Headers({'Content-Type': 'application/json'}),\n body: instrumentString,\n })\n .then(function(buyResult) {\n if (buyResult.ok) {\n return buyResult.json();\n }\n complete(instrument, 'fail', 'Error sending instrument to server.');\n }).then(function(buyResultJson) {\n print(instrumentString);\n complete(instrument, buyResultJson.status, buyResultJson.message);\n });\n })\n .catch(function(error) {\n print('Could not charge user. ' + error);\n });\n}",
"buildPaymentDetails(cart, shippingOptions, shippingOptionId) {\n // Start with the cart items\n let displayItems = cart.cart.map(item => {\n return {\n label: `${item.quantity}x ${item.title}`,\n amount: {currency: 'USD', value: String(item.total)},\n selected: false\n };\n });\n let total = cart.total;\n\n let displayedShippingOptions = [];\n if (shippingOptions.length > 0) {\n let selectedOption = shippingOptions[shippingOptionId];\n displayedShippingOptions = shippingOptions.map(option => {\n return {\n id: option.id,\n label: option.label,\n amount: {currency: 'USD', value: String(option.price)},\n selected: option === selectedOption\n };\n });\n if (selectedOption) total += selectedOption.price;\n }\n\n let details = {\n displayItems: displayItems,\n total: {\n label: 'Total due',\n amount: {currency: 'USD', value: String(total)}\n },\n shippingOptions: displayedShippingOptions\n };\n\n return details;\n }",
"function paymentFactory() {\n\tvar payment = {\n\t\tcNumber: \"\",\n\t\tcType: \"\",\n\t\tCName: \"\",\n\t\tcExp: \"\",\n\t\tcCvv: \"\"\n\t}\n\treturn payment;\n}",
"function FormatParamVoucher()\n{\n var params = '';\n params += POSTinitP;\n for (var i = 0; i < arguments.length; i++) {\n params += jsP[i] + arguments[i];\n }\n return params;\n}",
"function setupPaymentMethods17() {\n const queryParams = new URLSearchParams(window.location.search);\n if (queryParams.has('message')) {\n showRedirectErrorMessage(queryParams.get('message'));\n }\n\n $('input[name=\"payment-option\"]').on('change', function(event) {\n\n let selectedPaymentForm = $('#pay-with-' + event.target.id + '-form .adyen-payment');\n\n // Adyen payment method\n if (selectedPaymentForm.length > 0) {\n\n // not local payment method\n if (!('localPaymentMethod' in\n selectedPaymentForm.get(0).dataset)) {\n\n resetPrestaShopPlaceOrderButtonVisibility();\n return;\n }\n\n let selectedAdyenPaymentMethodCode = selectedPaymentForm.get(\n 0).dataset.localPaymentMethod;\n\n if (componentButtonPaymentMethods.includes(selectedAdyenPaymentMethodCode)) {\n prestaShopPlaceOrderButton.hide();\n } else {\n prestaShopPlaceOrderButton.show();\n }\n } else {\n // In 1.7 in case the pay button is hidden and the customer selects a non adyen method\n resetPrestaShopPlaceOrderButtonVisibility();\n }\n });\n }",
"function processPayment(paymentData) {\n var countryNameFromGoogle = \"\";\n try {\n countryNameFromGoogle = countriesData.filter(function (c) {\n return c.ShortCode === paymentData.paymentMethodData.info.billingAddress.countryCode.toLowerCase()})[0].Name;\n } catch (error) {\n console.error(error);\n\n if (Logger) {\n Logger.Error({ message: \"Getting google pay cc country\", exception: error });\n }\n }\n\n var data = {\n \"CreditCard\": {\n \"Token\": paymentData.paymentMethodData.tokenizationData.token,\n \"Type\": GetCardType(paymentData.paymentMethodData.info.cardNetwork),\n \"LastDigits\": paymentData.paymentMethodData.info.cardDetails,\n \"TokenType\": 2, // GooglePay\n \"CardHolderFirstName\": typeof paymentData.paymentMethodData.info.billingAddress !== \"undefined\" ? paymentData.paymentMethodData.info.billingAddress.name.split(\" \")[0] : \"\",\n \"CardHolderLastName\": typeof paymentData.paymentMethodData.info.billingAddress !== \"undefined\" ? paymentData.paymentMethodData.info.billingAddress.name.split(\" \")[1] : \"\",\n \"CardHolderAddress\": typeof paymentData.paymentMethodData.info.billingAddress !== \"undefined\" ? paymentData.paymentMethodData.info.billingAddress.address1 : \"\",\n \"CardHolderCity\": typeof paymentData.paymentMethodData.info.billingAddress !== \"undefined\" ? paymentData.paymentMethodData.info.billingAddress.locality : \"\",\n \"CardHolderCountry\": countryNameFromGoogle,\n \"CardHolderState\": typeof paymentData.paymentMethodData.info.billingAddress !== \"undefined\" ? paymentData.paymentMethodData.info.billingAddress.administrativeArea : \"\",\n \"CardHolderZip\": typeof paymentData.paymentMethodData.info.billingAddress !== \"undefined\" ? paymentData.paymentMethodData.info.billingAddress.postalCode : \"\",\n \"CardHolderPhone\": typeof paymentData.paymentMethodData.info.billingAddress !== \"undefined\" ? paymentData.paymentMethodData.info.billingAddress.phoneNumber : \"\"\n },\n \"GooglePay\": {\n \"OrderId\": PageParams.GooglePayMerchantOrderId,\n \"ReportGroup\": PageParams.GooglePayMerchantReportGroup\n }\n };\n\n elements.form.valid = true;\n\n submitForm(data, elements, \"GooglePay\");\n}",
"function createPaymentOptions() {\n\teditCashHistoryFundRowId = null;\n\tresetCashSection();\n\tshowTotalPaymentAndDue(); /* Disable the guest user more info and create account box */\n\tvar paymentOptionTypes = JSON.parse(localStorage.getItem(\"fundingSourceTypes\"));\n\tvar cashPaymentOptions = new Array();\n\tfor(var paymentOptionIndex in paymentOptionTypes) {\n\t\tvar paymentOptionType = paymentOptionTypes[paymentOptionIndex];\n\t\tvar paymentOptionSourcesJsonType = paymentOptionType.jsonType;\n\t\tvar paymentOptionTenderType = paymentOptionType.tenderType;\n\t\tif(paymentOptionSourcesJsonType === jsonTypeConstant.PROMOCREDIT){\n\t\t\tif(parseBoolean(localStorage.getItem(\"registerUser\"))) {\n\t\t\t\tvar visiblePromoCodeInputId = getVisiblePromoCodeBoxId();\n\t\t\t\t$(\"#\" + visiblePromoCodeInputId).val(\"\");\n\t\t\t\t$(\"#promoCodeSection\").show();\n\t\t\t} else {\n\t\t\t\t$(\"#discountAndPromoCodeReg\").show();\n\t\t\t\t$(\"#promoCodeBox\").show();\n\t\t\t}\n\t\t\t$(\"#errorPromoCodeRes\").hide();\n\t\t\t$(\"#summuryPromoCode\").hide();\n\t\t\t$('#checkoutPromoCodeAmount').hide();\n\t\t\tvar visiblePromoCodeInputId = getVisiblePromoCodeBoxId();\n\t\t\t$(\"#\" + visiblePromoCodeInputId).removeClass(\"error_red_border\");\n\t\t\tsubmitBtnEnableUI('checkoutApply');\n\t\t\tvalidationTracking = UNVALIDATED;\n\t\t\tlastPromoCode = \"\";\n\t\t\tregisterEventsForPromoCode();\n\t\t}\n\t\t/* if payment method is cash (create cash options) else create card option */\n\t\tif (paymentOptionTenderType && paymentOptionTenderType.toUpperCase() === tenderTypeConstant.CASH) {\n\t\t\tcashPaymentOptions.push(paymentOptionType);\n\t\t}\n\t}\n\tif (cashPaymentOptions.length > 0) {\n\t\t$(\"#checkoutCreditsCoverAllAmountDue\").hide();\n\t\t$(\"#cardPaymentOptionsContainer\").show();\n\t\t$(\"#cashDataMainContainer\").show(); /* Show CASH ribbon on screen */\n\t\tcreateCashPaymentOption(cashPaymentOptions.sort(sortByFundingSourceType));\n\t}\n\texpandSingleFundingSource();\n\t\n}",
"function getConfigPricingFromResourceQuery(ownerid, elements, callback) {\n var configJson = {};\n\n // Identify configurable vs\n if((elements.uri).match('vs/') && (elements.uri).match('/configurable')){\n configJson.volumeStorageUri = elements.uri;\n if(elements.parameters && elements.parameters.sizeInGBytes){\n configJson.size = elements.parameters.sizeInGBytes;\n }\n }else if((elements.uri).match('saas/') && (elements.uri).match('/configurable')){\n configJson.uri = elements.uri;\n if(elements.parameters && elements.parameters.sizeInGBytes){\n configJson.size = elements.parameters.sizeInGBytes;\n }\n }else {\n if(elements.uri){\n configJson.instanceTypeUri = elements.uri;\n }\n if(elements.parameters && elements.parameters.imageUri){\n configJson.imageUri = elements.parameters.imageUri;\n }\n if(elements.parameters && elements.parameters.ram){\n configJson.ram = elements.parameters.ram;\n }\n if(elements.parameters && elements.parameters.cpuCount){\n configJson.cpuCount = elements.parameters.cpuCount;\n }\n if(elements.parameters && elements.parameters.localStorage){\n configJson.localStorage = elements.parameters.localStorage;\n }\n trace.info(configJson);\n }\n\n jsonObject = JSON.stringify(configJson);\n\n // prepare the header\n //TODO Implement new Auth Model\n var postheaders = {\n 'Content-Type' : 'application/json',\n 'Content-Length' : Buffer.byteLength(jsonObject, 'utf8')\n //\"Authorization\": \"Basic \" + new Buffer(ownerid + \":\" + ownerid).toString(\"base64\")\n };\n\n postheaders[authConfig.bypassHeaderName] = 'billing'+':'+authConfig.billing;\n postheaders['ownerId'] = ownerid;\n\n // the post options\n var optionspost = {\n host : config.resourceServiceHost,\n port : config.resourceServicePort,\n path : '/apiv1.0/resourceQuery/validate',\n method : 'POST',\n headers : postheaders\n };\n\n // do the POST call to resource service\n restservices.postCall(optionspost,jsonObject).then(function (resourceServiceresult) {\n return callback(resourceServiceresult);\n\n }).catch(function onReject(err) {\n trace.error('Rejected', err);\n if(err.stack)\n trace.debug('Error Occurred in : '+ err.stack);\n return callback(null);\n\n }).catch(function(error){\n trace.error('Catch Error:', error);\n if(error.stack)\n trace.debug('Error Occurred in : '+ error.stack);\n return callback(null);\n });\n}",
"function getAllCommonParameters() {\n\treturn getCommonParameters()+\" AND ${parameters['totalArea']}\";\n}",
"get getParamsMapbox() {\n return {\n 'access_token': process.env.MAPBOX_KEY,\n 'limit': 5,\n 'language': 'es'\n };\n }",
"function updatePaymentInfo () {\n\n switch (document.querySelector(\"#payment\").value) {\n\n case \"credit card\":\n document.querySelector (\"#credit-card\").style.display = \"\";\n document.querySelector (\"#paypal\").style.display = \"none\";\n document.querySelector (\"#bitcoin\").style.display = \"none\";\n break;\n\n case \"paypal\":\n document.querySelector (\"#credit-card\").style.display = \"none\";\n document.querySelector (\"#paypal\").style.display = \"\";\n document.querySelector (\"#bitcoin\").style.display = \"none\";\n break;\n\n case \"bitcoin\":\n document.querySelector (\"#credit-card\").style.display = \"none\";\n document.querySelector (\"#paypal\").style.display = \"none\";\n document.querySelector (\"#bitcoin\").style.display = \"\";\n break;\n\n default: // this should never happen\n alert (\"internal error: no payment option detected\");\n break;\n }\n }",
"function navigatePaymentCalculator(url)\n{\n var amt;\n var params;\n \n try\n {\n amt = $j('#calc-price').val();\n if (amt.length > 0)\n params = 'calc-price=' + amt;\n }\n catch (ex) { }\n \n try\n {\n amt = $j('#calc-ttt').val();\n if (amt.length > 0)\n {\n if (params != null)\n params = params + '&calc-ttt=' + amt;\n else\n params = 'calc-ttt=' + amt;\n }\n }\n catch (ex) { }\n \n if (params != null)\n window.location = url + '?' + params;\n else\n window.location = url;\n}",
"function submitPaymentJSON() {\n var order = Order.get(request.httpParameterMap.order_id.stringValue);\n if (!order.object || request.httpParameterMap.order_token.stringValue !== order.getOrderToken()) {\n app.getView().render('checkout/components/faults');\n return;\n }\n session.forms.billing.paymentMethods.clearFormElement();\n var requestObject = JSON.parse(request.httpParameterMap.requestBodyAsString);\n var form = session.forms.billing.paymentMethods;\n for (var requestObjectItem in requestObject) {\n var asyncPaymentMethodResponse = requestObject[requestObjectItem];\n var terms = requestObjectItem.split('_');\n if (terms[0] === 'creditCard') {\n var value = terms[1] === 'month' || terms[1] === 'year' ? Number(asyncPaymentMethodResponse) : asyncPaymentMethodResponse;\n form.creditCard[terms[1]].setValue(value);\n } else if (terms[0] === 'selectedPaymentMethodID') {\n form.selectedPaymentMethodID.setValue(asyncPaymentMethodResponse);\n }\n }\n if (app.getController('COBilling').HandlePaymentSelection('cart').error || handlePayments().error) {\n app.getView().render('checkout/components/faults');\n return;\n }\n app.getView().render('checkout/components/payment_methods_success');\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
convertToPyret : [listof Programs], pinfo > JSON generate pyret parse tree, preserving location information follows provide and import will never be used | function convertToPyret(programs, pinfo){
_pinfo = pinfo;
return { name: "program"
, kids: [ {name: "prelude"
, kids: [/* TBD */]
, pos: blankLoc}
, {name: "block"
, kids: programs.map(function(p){return {name:"stmt", kids:[p.toPyret()], pos: p.location};})
, pos: programs.location}]
, pos: programs.location};
} | [
"function rehype2json() {\n this.Compiler = node => {\n const rootNode = getRootNode(node)\n visit(rootNode, removePositionFromNode)\n return JSON.stringify(rootNode)\n }\n}",
"function updatePrimaryPackageJson(packageJson) {\n if (packageJson.type !== undefined) {\n throw Error('The primary \"package.json\" file of the package sets the \"type\" field ' +\n 'that is controlled by the packager. Please unset it.');\n }\n const newPackageJson = Object.assign({}, packageJson);\n newPackageJson.type = 'module';\n // The `package.json` file is made publicly accessible for tools that\n // might want to query information from the Angular NPM package.\n insertExportMappingOrError(newPackageJson, './package.json', { default: './package.json' });\n // Capture all entry-points in the `exports` field using the subpath export declarations:\n // https://nodejs.org/api/packages.html#packages_subpath_exports.\n for (const [moduleName, entryPoint] of Object.entries(metadata.entryPoints)) {\n const subpath = isSecondaryEntryPoint(moduleName) ? `./${getEntryPointSubpath(moduleName)}` : '.';\n const esm2020IndexOutRelativePath = getEsm2020OutputRelativePath(entryPoint.index);\n const fesm2020OutRelativePath = getFlatEsmOutputRelativePath(entryPoint.fesm2020Bundle);\n const fesm2015OutRelativePath = getFlatEsmOutputRelativePath(entryPoint.fesm2015Bundle);\n const typesOutRelativePath = getTypingOutputRelativePath(entryPoint.typings);\n // Insert the export mapping for the entry-point. We set `default` to the FESM 2020\n // output, and also set the `types` condition which will be respected by TS 4.5.\n // https://github.com/microsoft/TypeScript/pull/45884.\n insertExportMappingOrError(newPackageJson, subpath, {\n types: normalizePath(typesOutRelativePath),\n esm2020: normalizePath(esm2020IndexOutRelativePath),\n es2020: normalizePath(fesm2020OutRelativePath),\n // We also expose a non-standard condition that would allow consumers to resolve\n // to the `ES2015` output outside of NodeJS, if desired.\n // TODO(devversion): remove/replace this if NodeJS v12 is no longer supported.\n es2015: normalizePath(fesm2015OutRelativePath),\n // We declare the `node` condition and point to the ES2015 output as we currently still\n // support NodeJS v12 which does not fully support ES2020 output. We chose ES2015 over\n // ES2020 because we wan async/await downleveled as this allows for patching withZoneJS.\n // TODO(devversion): remove/replace this if NodeJS v12 is no longer supported.\n node: normalizePath(fesm2015OutRelativePath),\n // Note: The default conditions needs to be the last one.\n default: normalizePath(fesm2020OutRelativePath),\n });\n }\n return newPackageJson;\n }",
"function parseNodeModulePackageJson(name) {\n const mod = require(`../node_modules/${name}/package.json`);\n\n // Take this opportunity to cleanup the module.bin entries\n // into a new Map called 'executables'\n const executables = mod.executables = new Map();\n\n if (Array.isArray(mod.bin)) {\n // should not happen, but ignore it if present\n } else if (typeof mod.bin === 'string') {\n executables.set(name, stripBinPrefix(mod.bin));\n } else if (typeof mod.bin === 'object') {\n for (let key in mod.bin) {\n executables.set(key, stripBinPrefix(mod.bin[key]));\n }\n }\n\n return mod; \n}",
"function jsonify(pipeline, pipeinfo) {\n\n //print(\"json pipeline is \" + pipeline);\n var stream = new java.io.ByteArrayOutputStream();\n cocoon.processPipelineTo( pipeline, pipeinfo, stream );\n var theVal = stream.toString() + \"\";\n\t\t\n\t//print(\"serviceVal is \" + theVal);\n var checkpos = -1;\n\t/* \tthis probably doesn't have to be in a try/catch block\n\t\tbut i had a problem with one range where it was an odd\n\t\tcharacter. \n\t*/\t\n\ttry {\n\t\tcheckpos = theVal.indexOf(prob1);\n\t\tif (checkpos != -1)\n\t\t\ttheVal = fixCollection(theVal,prob1);\n\t\tcheckpos = theVal.indexOf(prob2);\n \tif (checkpos != -1)\n \ttheVal = theVal.substring(0,checkpos);\n\t\tcheckpos = theVal.indexOf(prob3);\n\t\tif (checkpos != -1) {\n\t\t\ttheVal = theVal.replace(/,\\{\\\"url/g,'},{\\\"url') + \"\";\n\t\t\ttheVal = theVal.replace(/\\\"\\]/g,'\\\"}]');\n\t\t\t//print(\"now -> \" + theVal + \"<-\");\n\t\t}\n\t} catch (problem) {\n\t\tprint(\"nasty char issue \" + problem);\n\t}\n\n\tvar theEval = jsonEval(theVal);\n\n\treturn theEval;\n\n}//jsonify",
"runWithModuleList(compilationResult, modules, callback) {\n let reports = []; // Also provide convenience analysis via the AST walker.\n\n const walker = new remix_astwalker_1.AstWalker();\n\n for (const k in compilationResult.sources) {\n walker.walkFull(compilationResult.sources[k].ast, node => {\n modules.map(item => {\n if (item.mod.visit !== undefined) {\n try {\n item.mod.visit(node);\n } catch (e) {\n reports.push({\n name: item.name,\n report: [{\n warning: 'INTERNAL ERROR in module ' + item.name + ' ' + e.message,\n error: e.stack\n }]\n });\n }\n }\n });\n return true;\n });\n } // Here, modules can just collect the results from the AST walk,\n // but also perform new analysis.\n\n\n reports = reports.concat(modules.map(item => {\n let report = null;\n\n try {\n report = item.mod.report(compilationResult);\n } catch (e) {\n report = [{\n warning: 'INTERNAL ERROR in module ' + item.name + ' ' + e.message,\n error: e.stack\n }];\n }\n\n return {\n name: item.name,\n report: report\n };\n }));\n callback(reports);\n }",
"function reformat(obj) {\n var stack = [];\n\n obj.forEach((value, key) => {\n if (stack.length === 0) {\n stack.push(build(value));\n } else {\n var stackArray = value.stack.split('\\n');\n var parent = stackArray[3].trim();\n if (!parent.match('.js:') === true) { // its a command not a file, try next one.\n parent = stackArray[4].trim();\n }\n\n if ((!!parent.match(nodeModules) === true) ||\n (!!parent.match('emitTwo') == true) && (!!parent.match('events.js') == true) || // Node http\n (!!parent.match('Server.emit') == true) && (!!parent.match('events.js') == true) || // Node http\n (!!parent.match(value.filename) === true)) {\n stack.push(build(value));\n } else {\n return recurse(stack, value, parent);\n }\n }\n });\n\n return stack;\n }",
"function getVersions(res)\n { //powershell -command \"& {&Get-ItemPropertyValue 'D:\\unityVersions\\unity1 - Copy (4)\\Editor\\Uninstall.exe' -name 'VersionInfo' | ConvertTo-Json}\"\n return new promise(function(resolve,reject){\n\n var asyncOperations = res.unity.length;\n var result = [];\n\n res.unity.forEach(function(element){\n\n if(fs.existsSync(element+\"Uninstall.exe\")){\n\n var command = 'powershell -command \"& {&Get-ItemPropertyValue -Path \\''+ element + \"Uninstall.exe\" +'\\' -name \\'VersionInfo\\' | ConvertTo-Json}\"';\n //console.log(command);\n child.exec(command,function(error, ls,stderr){\n\n if(error) {console.error(error);reject(error);} //this is the error on our side\n //this is the error that will be outputed if command is invalid or sm sht\n if(stderr) {\n console.error(stderr);\n console.warn(\"Command that was executed when error happened:\\n\" + command);\n reject(stderr);\n }\n\n ls = ls.toString();\n ls = ls.replace(/\\n|\\r/g, \"\");\n if(ls==\"\") {\n toastr.warn(\"info about unity was returned empty (unity will not be visible as installed)\\n \"+ element);\n asyncOperations--;\n if(asyncOperations <= 0){\n\n resolve(result);\n }else{\n return\n }\n\n };\n ls = JSON.parse(ls);\n\n\n result.push({\n parentPath:element,\n path:ls.FileName,\n version: ls.ProductName,\n modules:[\n /*{\n name:\"Android\"\n path:\"...Editor\"\n version:\"N/A\"\n }*/\n ]\n });\n\n asyncOperations--;\n if(asyncOperations <= 0){\n\n resolve(result);\n }\n })\n\n }\n else{\n toastr.error(element+\"Uninstall.exe does not exists\");\n }\n\n });\n })\n\n }",
"function getParserList() {\n\n if (parserList === undefined) {\n\n var bundleParsers = [], files, bundlePath;\n\n // Application bundled\n bundlePath = path.resolve(path.join(__dirname, \"parser\"));\n files = fs.readdirSync(bundlePath);\n files.forEach(\n function (fileName) {\n\n var parser, parserPath;\n\n if (path.extname(fileName) === \".js\") {\n\n parserPath = path.join(bundlePath, fileName);\n try {\n parser = require(parserPath);\n } catch(ex) {\n console.error(\"Could not find parser %s. File not found or open error\", ex);\n }\n if (parser !== undefined && parser.disabled !== true && typeof parser.parsePage === \"function\") {\n\n fileName = path.basename(fileName, \".js\");\n parsers[fileName] = parser;\n\n bundleParsers.push(\n {\n name: fileName,\n label: parser.label,\n description: parser.description,\n isBundled: true\n }\n );\n }\n }\n }\n );\n\n // User\n // TODO : Charger les parsers du dossier utilisateur\n\n\n parserList = bundleParsers;\n }\n\n return parserList;\n}",
"getProblemsByName(leetcodeName){\n\t\tconsole.log(\"Try to Get ProblemInfo from: \", leetcodeName);\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst pyprog = spawn('python3', ['./LeetCode_scraper.py', leetcodeName]);\n\t\t\t\n\t\t\tpyprog.stdout.on('data', function(data) {\n\t\t\t\tlet problemInfoArr = data.toString().split('\\n');\n\t\t\t\tconsole.log(\"Get success\", problemInfoArr);\n\t\t\t\tproblemInfoArr[1] = problemInfoArr[1].replace(/'/g, '\"'); \n\t\t\t\tlet recent_problem = '';\n\t\t\t\ttry {\n \t\t\t\t\trecent_problem = JSON.parse(problemInfoArr[1]);\n\t\t\t\t}\n\t\t\t\tcatch(error) {\n \t\t\t\t\tconsole.error(error);\n\t\t\t\t}\n\t\t\t\tlet problemInfo = {\n\t\t\t\t\t'problem' : problemInfoArr[0],\n\t\t\t\t\t'recent_problem' : recent_problem\n\t\t\t\t};\n \t\t\n \t\tresolve(problemInfo);\n \t\t});\n \t\tpyprog.stderr.on('data', (data) => {\n\t\t\t\tconsole.log(\"Get failed\", data.toString());\n \t\t\treject(data.toString());\n\n \t\t});\n\n\t\t});\n\t}",
"consoleParsePtypes(input) { return Parser.parse(input, { startRule: 'PTYPES' }); }",
"generate() {\n var ast = this.ast;\n\n this.print(ast);\n this.catchUp();\n\n return {\n code: this.buffer.get(this.opts),\n tokens: this.buffer.tokens,\n directives: this.directives\n };\n }",
"function toRholang(par) {\n const src = x => JSON.stringify(x);\n\n function recur(p) {\n if (p.exprs) {\n if (p.exprs.length !== 1) {\n throw new Error('not implemented');\n }\n const ex = p.exprs[0];\n if (ex.expr_instance === 'g_bool') {\n return src(ex.g_bool);\n }\n if (ex.expr_instance === 'g_int') {\n return src(ex.g_int);\n }\n if (ex.expr_instance === 'g_string') {\n return src(ex.g_string);\n }\n if (ex.expr_instance === 'e_list_body') {\n const items = ex.e_list_body.ps.map(recur).join(', ');\n return `[${items}]`;\n }\n throw new Error(`not RHOCore? ${ex}`);\n } else if (p.sends) {\n const ea = s => `@${recur(s.chan.quote)}!(${s.data.map(recur).join(', ')})`;\n return p.sends.map(ea).join(' | ');\n } else {\n // TODO: check that everything else is empty\n return 'Nil';\n }\n }\n\n return recur(par);\n}",
"function mergePackageJsonWithYarnEntry(entries, mod) {\n const entry = findMatchingYarnEntryByNameAndVersion(entries, mod);\n if (!entry) {\n throw new Error(\"No matching node_module found for this module\", mod);\n }\n\n // Use the bazelified name as the module name\n mod.original_name = mod.name\n mod.name = entry.name\n // Store everything else here\n mod.yarn = entry;\n}",
"function makeProg(mappings, o) {\n console.log(\"make prog o\", o);\n\n if (o.type === 'SimplicialComplex') {\n\treturn scToSub(mappings, o);\n } else if (o.type === 'MeshSubset') {\n\treturn subsetToSub(mappings, o);\n }\n}",
"function getLab3JSON(){\n let exp = {};\n exp[EXP_JSON_TITLE] = \"Lab 3\";\n exp[EXP_JSON_CREATOR] = \"Gen Chem\";\n\n let equips = [];\n let scale = 0;\n let cylinder = 1;\n let flask = 2;\n let boat = 3;\n let rod = 4;\n let eyeDropper = 5;\n let refractometer = 6;\n let refractometerLens = 7;\n let water = 0;\n let salt = 1;\n equips.push(makeTestEquipmentJSON(ID_EQUIP_SCALE, 1));\n equips.push(makeTestEquipmentJSON(ID_EQUIP_GRADUATED_50mL, 1));\n equips.push(makeTestEquipmentJSON(ID_EQUIP_FLASK_125mL, 1));\n equips.push(makeTestEquipmentJSON(ID_EQUIP_WEIGH_BOAT, 1));\n equips.push(makeTestEquipmentJSON(ID_EQUIP_STIR_ROD, 1));\n equips.push(makeTestEquipmentJSON(ID_EQUIP_EYE_DROPPER, 1));\n equips.push(makeTestEquipmentJSON(ID_EQUIP_REFRACTOMETER, 1));\n equips.push(makeTestEquipmentJSON(ID_EQUIP_REFRACTOMETER_LENS, 1));\n exp[EXP_JSON_EQUIPMENT] = sortArrayByKey(equips, EXP_JSON_EQUIP_OBJ_ID, false);\n\n let chems = [];\n chems.push(makeTestChemicalJSON(COMPOUND_WATER_ID, 50, 1));\n chems.push(makeTestChemicalJSON(COMPOUND_TABLE_SALT_ID, 1.7, 1));\n exp[EXP_JSON_CHEMICALS] = sortArrayByKey(chems, [EXP_JSON_CHEM_ID, EXP_JSON_CHEM_MASS, EXP_JSON_CHEM_CONCENTRATION], true);\n\n let steps = [];\n var s = 0;\n // Part A\n steps.push(makeTestInstructionJSON(s++, scale, true, flask, true, ID_FUNC_SCALE_TO_TAKE_WEIGHT));\n steps.push(makeTestInstructionJSON(s++, scale, true, flask, true, ID_FUNC_SCALE_REMOVE_OBJECT));\n steps.push(makeTestInstructionJSON(s++, cylinder, true, water, false, ID_FUNC_CONTAINER_ADD_TO));\n steps.push(makeTestInstructionJSON(s++, cylinder, true, flask, true, ID_FUNC_CONTAINER_POUR_INTO));\n steps.push(makeTestInstructionJSON(s++, scale, true, boat, true, ID_FUNC_SCALE_TO_TAKE_WEIGHT));\n steps.push(makeTestInstructionJSON(s++, scale, true, null, true, ID_FUNC_SCALE_ZERO_OUT));\n steps.push(makeTestInstructionJSON(s++, boat, true, salt, false, ID_FUNC_CONTAINER_ADD_TO));\n steps.push(makeTestInstructionJSON(s++, scale, true, null, true, ID_FUNC_SCALE_REMOVE_OBJECT));\n steps.push(makeTestInstructionJSON(s++, boat, true, flask, true, ID_FUNC_CONTAINER_POUR_INTO));\n steps.push(makeTestInstructionJSON(s++, rod, true, flask, true, ID_FUNC_STIR_ROD_STIR));\n steps.push(makeTestInstructionJSON(s++, scale, true, null, true, ID_FUNC_SCALE_CLEAR_ZERO));\n steps.push(makeTestInstructionJSON(s++, scale, true, flask, true, ID_FUNC_SCALE_TO_TAKE_WEIGHT));\n steps.push(makeTestInstructionJSON(s++, scale, true, null, true, ID_FUNC_SCALE_REMOVE_OBJECT));\n\n // Part B\n steps.push(makeTestInstructionJSON(s++, flask, true, eyeDropper, true, ID_FUNC_CONTAINER_POUR_INTO));\n steps.push(makeTestInstructionJSON(s++, eyeDropper, true, refractometerLens, true, ID_FUNC_EYE_DROPPER_DROP));\n steps.push(makeTestInstructionJSON(s++, eyeDropper, true, refractometerLens, true, ID_FUNC_EYE_DROPPER_DROP));\n steps.push(makeTestInstructionJSON(s++, refractometer, true, refractometerLens, true, ID_FUNC_REFRACTOMETER_SET_LENS));\n steps.push(makeTestInstructionJSON(s++, flask, true, null, true, ID_FUNC_CONTAINER_EMPTY_IN_TRASH));\n\n // set the instruction list\n exp[EXP_JSON_INSTRUCTIONS] = sortArrayByKey(steps, EXP_JSON_INS_STEP_NUM, false);\n\n return exp;\n}",
"function ProgramParser() {\n \t\t\n \t\t this.parse = function(kind) {\n \t\t \tswitch (kind) { \t\n \t\t \t\tcase \"declaration\": return Declaration();\n \t\t \t\tbreak;\n\t \t\t\tdefault: return Program();\n\t \t\t}\n\t \t}\n \t\t\n \t\t// Import Methods from the expression Parser\n \t\tfunction Assignment() {return expressionParser.Assignment();}\n \t\tfunction Expr() {return expressionParser.Expr();}\n \t\tfunction IdentSequence() {return expressionParser.IdentSequence();}\n \t\tfunction Ident(forced) {return expressionParser.Ident(forced);}\t\t\n \t\tfunction EPStatement() {return expressionParser.Statement();}\n\n\n\t\tfunction whatNext() {\n \t\t\tswitch (lexer.current.content) {\n \t\t\t\tcase \"class\"\t\t: \n \t\t\t\tcase \"function\"\t \t: \n \t\t\t\tcase \"structure\"\t:\n \t\t\t\tcase \"constant\" \t:\n \t\t\t\tcase \"variable\" \t:\n \t\t\t\tcase \"array\"\t\t: \treturn lexer.current.content;\t\n \t\t\t\tbreak;\n \t\t\t\t\t\n \t\t\t\tdefault\t\t\t\t:\treturn lexer.lookAhead().content;\n \t\t\t}\n\t\t}\n\n// \t\tDeclaration\t:= {Class | Function | VarDecl | Statement} \n\t\tfunction Declaration() {\n\t\t\tswitch (whatNext()) {\n \t\t\t\t\t\n \t\t\t\t\tcase \"class\"\t: return Class();\n \t\t\t\t\tbreak;\n \t\t\t\t\t\n \t\t\t\t\tcase \"function\" : return Function();\n \t\t\t\t\tbreak;\n \t\t\t\t\n \t\t\t\t\tcase \"structure\" : return StructDecl();\n \t\t\t\t\tbreak;\n \t\t\t\t\t\n \t\t\t\t\tcase \"array\"\t: return ArrayDecl();\n \t\t\t\t\tbreak;\n \t\t\t\t\n \t\t\t\t\tcase \"constant\" :\n \t\t\t\t\tcase \"variable\" : return VarDecl();\n \t\t\t\t\tbreak;\n \t\t\t\t\tdefault\t\t\t: return false;\n \t\t\t }\n\t\t}\n\n// \t\tProgram\t:= {Class | Function | VarDecl | Structure | Array | Statement} \n//\t\tAST: \"program\": l: {\"function\" | \"variable\" ... | Statement} indexed from 0...x\n\t\tthis.Program=function() {return Program()};\n \t\tfunction Program() {\n \t\t\tdebugMsg(\"ProgramParser : Program\");\n \t\t\tvar current;\n \t\t\tvar ast=new ASTListNode(\"program\");\n \t\t\t\n \t\t\tfor (;!eof();) {\n \t\t\t\t\n \t\t\t\tif (!(current=Declaration())) current=Statement();\n \t\t\t\t\n \t\t\t\tif (!current) break;\n \t\t\t\t\n \t\t\t\tast.add(current);\t\n \t\t\t} \t\t\t\n \t\t\treturn ast;\n \t\t}\n \t\t\n //\t\tClass:= \"class\" Ident [\"extends\" Ident] \"{\" [\"constructor\" \"(\" Ident Ident \")\"] CodeBlock {VarDecl | Function}\"}\"\n//\t\tAST: \"class\" : l: name:Identifier,extends: ( undefined | Identifier),fields:VarDecl[0..i], methods:Function[0...i]\n\t\tfunction Class() {\n\t\t\tdebugMsg(\"ProgramParser : Class\");\n\t\t\tlexer.next();\n\n\t\t\tvar name=Ident(true);\t\t\t\n\t\t\t\n\t\t\tvar extend={\"content\":undefined};\n\t\t\tif(test(\"extends\")) {\n\t\t\t\tlexer.next();\n\t\t\t\textend=Ident(true);\n\t\t\t}\n\t\t\t\n\t\t\tcheck (\"{\");\n\t\t\tvar scope=symbolTable.openScope();\n\t\t\t\n\t\t\tvar methods=[];\n\t\t\tvar fields=[];\n\t\t\t\n\t\t\tif (test(\"constructor\")) {\n\t\t\t\tlexer.next();\n\t\t \t\t//var retType={\"type\":\"ident\",\"content\":\"_$any\",\"line\":lexer.current.line,\"column\":lexer.current.column};\n\t\t\t\tvar constructName={\"type\":\"ident\",\"content\":\"construct\",\"line\":lexer.current.line,\"column\":lexer.current.column};\n\t\t\t\tmethods.push(FunctionBody(name,constructName));\n\t\t\t}\n\t\t\t\n\t\t\tvar current=true;\n\t\t\twhile(!test(\"}\") && current && !eof()) {\n\t\t\t\t \t\n\t\t \tswitch (whatNext()) {\n \t\t\t\t\t\n \t\t\t\t\tcase \"function\"\t: methods.push(Function()); \n \t\t\t\t\tbreak;\n \t\t\t\t\t\n \t\t\t\t\tcase \"constant\":\n \t\t\t\t\tcase \"variable\" : fields.push(VarDecl(true));\n \t\t\t\t\tbreak;\n \t\t\t\t\tdefault\t\t\t: current=false;\n \t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tcheck(\"}\");\n\t\t\t\n\t\t\tmode.terminatorOff();\n\n\t\t\tsymbolTable.closeScope();\n\t\t\tsymbolTable.addClass(name.content,extend.content,scope);\n\t\t\t\n\t\t\treturn new ASTUnaryNode(\"class\",{\"name\":name,\"extends\":extend,\"scope\":scope,\"methods\":methods,\"fields\":fields});\n\t\t}\n\t\t\n //\t\tStructDecl := \"structure\" Ident \"{\" VarDecl {VarDecl} \"}\"\n //\t\tAST: \"structure\" : l: \"name\":Ident, \"decl\":[VarDecl], \"scope\":symbolTable\n \t\tfunction StructDecl() {\n \t\t\tdebugMsg(\"ProgramParser : StructDecl\");\n \t\t\t\n \t\t\tlexer.next(); \n \t\t\t\n \t\t\tvar name=Ident(true); \n \t\t\t\n \t\t\tcheck(\"{\");\n \t\t\tmode.terminatorOn();\n \t\t\t\n \t\t\tvar decl=[];\n \t\t\t\n \t\t\tvar scope=symbolTable.openScope();\t\n \t\t\tdo {\t\t\t\t\n \t\t\t\tdecl.push(VarDecl(true));\n \t\t\t} while(!test(\"}\") && !eof());\n \t\t\t\n \t\t\tmode.terminatorOff();\n \t\t\tcheck (\"}\");\n \t\t\t\n \t\t\tsymbolTable.closeScope();\n \t\t\tsymbolTable.addStruct(name.content,scope);\n \t\t\t\n \t\t\treturn new ASTUnaryNode(\"structure\",{\"name\":name,\"decl\":decl,\"scope\":scope});\n \t\t} \n \t\t\n //\tarrayDecl := \"array\" Ident \"[\"Ident\"]\" \"contains\" Ident\n //\t\tAST: \"array\" : l: \"name\":Ident, \"elemType\":Ident, \"indexTypes\":[Ident]\n \t\tfunction ArrayDecl() {\n \t\t\tdebugMsg(\"ProgramParser : ArrayDecl\");\n \t\t\t\n \t\t\tlexer.next(); \n \t\t\t\n \t\t\tvar name=Ident(true);\n \t\t\t\n \t\t\tcheck(\"[\");\n \t\t\t\t\n \t\t\tvar ident=Ident(!mode.any);\n \t\t\tif (!ident) ident=lexer.anyLiteral();\n \t\t\t\t\n \t\t\tvar indexType=ident;\n \t\t\t\t\n \t\t\tvar bound=ident.content;\n \t\t\t\t\n \t\t\tcheck(\"]\");\n \t\t\t\t\n \t\t\tvar elemType; \t\n \t\t\tif (mode.any) {\n \t\t\t\tif (test(\"contains\")) {\n \t\t\t\t\tlexer.next();\n \t\t\t\t\telemType=Ident(true);\n \t\t\t\t}\n \t\t\t\telse elemType=lexer.anyLiteral();\n \t\t\t} else {\n \t\t\t\tcheck(\"contains\");\n \t\t\t\telemType=Ident(true);\n \t\t\t}\n \t\t\t\n \t\t\tcheck (\";\");\n \t\t\tsymbolTable.addArray(name.content,elemType.content,bound);\n \t\t\t\n \t\t\treturn new ASTUnaryNode(\"array\",{\"name\":name,\"elemType\":elemType,\"indexType\":indexType});\n \t\t} \n \t\t\n//\t\tFunction := Ident \"function\" Ident \"(\" [Ident Ident {\"[\"\"]\"} {\",\" Ident Ident {\"[\"\"]\"}) } \")\" CodeBlock\n//\t\tAST: \"function\":\tl: returnType: (Ident | \"_$\"), name:name, scope:SymbolTable, param:{name:Ident,type:Ident}0..x, code:CodeBlock \n\t\tthis.Function=function() {return Function();}\n \t\tfunction Function() {\n \t\t\tdebugMsg(\"ProgramParser : Function\");\n \t\t\n \t\t\tvar retType;\n \t\t\tif (mode.decl) retType=Ident(!(mode.any));\n \t\t\tif (!retType) retType=lexer.anyLiteral();\n \t\t\t\n \t\t\tcheck(\"function\");\n \t\t\t\n \t\t\tvar name=Ident(true);\n \t\t\t\n \t\t\treturn FunctionBody(retType,name);\n \t\t}\n \t\t\n \n \t\t// The Body of a function, so it is consistent with constructor\n \t\tfunction FunctionBody(retType,name)\t{\n \t\t\tvar scope=symbolTable.openScope();\n \t\t\t\n \t\t\tif (!test(\"(\")) error.expected(\"(\");\n \t\t\n var paramList=[];\n var paramType=[];\n var paramExpected=false; //Indicates wether a parameter is expected (false in the first loop, then true)\n do {\n \t\t\tlexer.next();\n \t\t\t\n \t\t\t/* Parameter */\n \t\t\tvar pName,type;\n \t\t\tvar ident=Ident(paramExpected);\t// Get an Identifier\n \t\t\tparamExpected= true;\n \t\t\t\n \t\t\t// An Identifier is found\n \t\t\tif (ident) {\n \t\t\t\t\n \t\t\t\t// When declaration is possible\n \t\t\t\tif (mode.decl) {\n \t\t\t\t\t\n \t\t\t\t\t// One Identifier found ==> No Type specified ==> indent specifies Param Name\n \t\t\t\t\tif (!(pName=Ident(!(mode.any)))) {\n \t\t\t\t\t\ttype=lexer.anyLiteral();\n \t\t\t\t\t\tpName=ident;\n \t\t\t\t\t} else type=ident; // 2 Identifier found\n \t\t\t\t} else {\t// Declaration not possible\n \t\t\t\t\ttype=lexer.anyLiteral();\n \t\t\t\t\tpName=ident;\n \t\t\t\t}\t\n\n\t\t\t\t\t// Store Parameter\n\t\t\t\t\tparamType.push(type); \n \t\tparamList.push({\"name\":pName,\"type\":type});\n \t\t \n \t\t \tsymbolTable.addVar(pName.content,type.content);\n \t\t} \n \t\t} while (test(\",\") && !eof());\n\n \tcheck(\")\");\n \t\t\t \t\t\t\n \t\t\tvar code=CodeBlock();\n \t\t\t\n \t\t\tsymbolTable.closeScope();\n \t\t\t\n \t\t\tsymbolTable.addFunction(name.content,retType.content,paramType);\n \t\t\treturn new ASTUnaryNode(\"function\",{\"name\":name,\"scope\":scope,\"param\":paramList,\"returnType\":retType,\"code\":code});\n \t\t}\n \t\t\t\n\t\t\n //\t\tVarDecl := Ident (\"variable\" | \"constant\") Ident [\"=\" Expr] \";\" \n //\t\tAST: \"variable\"|\"constant\": l : type:type, name:name, expr:[expr]\n \t\tthis.VarDecl = function() {return VarDecl();}\n \t\tfunction VarDecl(noInit) {\n \t\t\tdebugMsg(\"ProgramParser : VariableDeclaration\");\n \t\t\tvar line=lexer.current.line;\n \t\t\tvar type=Ident(!mode.any);\n \t\t\tif (!type) type=lexer.anyLiteral();\n \t\t\t\n \t\t\tvar constant=false;\n \t\t\tvar nodeName=\"variable\";\n \t\t\tif (test(\"constant\")) {\n \t\t\t\tconstant=true; \n \t\t\t\tnodeName=\"constant\";\n \t\t\t\tlexer.next();\n \t\t\t}\n \t\t\telse check(\"variable\"); \n \t\t\t \t\t\t\n \t\t\tvar name=Ident(true);\n \t\t\tsymbolTable.addVar(name.content,type.content,constant);\n\n\t\t\tvar expr=null;\n\t\t\tif(noInit==undefined){\n\t\t\t\tif (test(\"=\")) {\n\t\t\t\t\tlexer.next();\n\t\t\t\t\texpr=Expr();\n\t\t\t\t\tif (!expr) expr=null;\n\t\t\t\t}\n\t\t\t} \n\t\n\t\t\tcheck(\";\");\n\t\t\tvar ast=new ASTUnaryNode(nodeName,{\"type\":type,\"name\":name,\"expr\":expr});\n\t\t\tast.line=line;\n\t\t\treturn ast;\n \t\t}\n \t\t\t\t\n//\t\tCodeBlock := \"{\" {VarDecl | Statement} \"}\" \n//\t\tCodeblock can take a newSymbolTable as argument, this is needed for functions that they can create an scope\n//\t\tcontaining the parameters.\n//\t\tIf newSymbolTable is not specified it will be generated automatical\n// At the End of Codeblock the scope newSymbolTable will be closed again\t\t\n//\t\tAST: \"codeBlock\" : l: \"scope\":symbolTable,\"code\": code:[0..x] {code}\n \t\tfunction CodeBlock() {\n \t\t\tdebugMsg(\"ProgramParser : CodeBlock\");\n\t\t\t\n\t\t\tvar scope=symbolTable.openScope();\n\t\t\tvar begin=lexer.current.line;\n\t\t\tcheck(\"{\");\n \t\t\t\n \t\t\tvar code=[];\n \t\t\tvar current;\n\n \t\t\twhile(!test(\"}\") && !eof()) {\n \t\t\t\tswitch (whatNext()) {\n \t\t\t\t\tcase \"constant\":\n \t\t\t\t\tcase \"variable\": current=VarDecl();\n \t\t\t\t\tbreak;\n \t\t\t\t\tdefault: current=Statement();\t\t\t\t\t\n \t\t\t\t}\n\n \t\t\t\tif(current) {\n \t\t\t\t\tcode.push(current);\n \t\t\t\t} else {\n \t\t\t\t\terror.expected(\"VarDecl or Statement\"); break;\n \t\t\t\t}\n \t\t\t}\t\n \t\t\t\n \t\t\tvar end=lexer.current.line;\n \t\t\tcheck(\"}\");\n \t\t\tsymbolTable.closeScope();\n \t\t\treturn new ASTUnaryNode(\"codeBlock\",{\"scope\":scope,\"code\":code,\"begin\":begin,\"end\":end});\n \t\t}\n \t\t\n//\t\tStatement\t:= If | For | Do | While | Switch | JavaScript | (Return | Expr | Assignment) \";\"\n \t\tfunction Statement() {\n \t\t\tdebugMsg(\"ProgramParser : Statement\");\n \t\t\tvar ast;\n \t\t\tvar line=lexer.current.line;\n \t\t\t\n \t\t\tswitch (lexer.current.content) {\n \t\t\t\tcase \"if\"\t \t\t: ast=If(); \n\t \t\t\tbreak;\n \t\t\t\tcase \"do\"\t \t\t: ast=Do(); \n \t\t\t\tbreak;\n \t\t\t\tcase \"while\" \t\t: ast=While(); \t\t\n \t\t\t\tbreak;\n \t\t\t\tcase \"for\"\t\t\t: ast=For();\n \t\t\t\tbreak;\n \t\t\t\tcase \"switch\"\t\t: ast=Switch(); \t\n \t\t\t\tbreak;\n \t\t\t\tcase \"javascript\"\t: ast=JavaScript(); \n \t\t\t\tbreak;\n \t\t\t\tcase \"return\"\t\t: ast=Return(); \n \t\t\t\t\t\t\t\t\t\t check(\";\");\n \t\t\t\tbreak;\n \t\t\t\tdefault\t\t\t\t: ast=EPStatement(); \n \t\t\t\t\t check(\";\");\n \t\t\t}\n \t\t\tast.line=line;\n \t\t\tast.comment=lexer.getComment();\n \t\t\tlexer.clearComment(); \t\t\t\n \t\t\treturn ast;\t\n \t\t}\n \t\t\n//\t\tIf := \"if\" \"(\" Expr \")\" CodeBlock [\"else\" CodeBlock]\n//\t\tAST : \"if\": l: cond:Expr, code:codeBlock, elseBlock:(null | codeBlock)\n \t\tfunction If() {\n \t\t\tdebugMsg(\"ProgramParser : If\");\n \t\t\t\n \t\t\tlexer.next();\n \t\t\tcheck(\"(\");\n \t\t\t\n \t\t\tvar expr=Expr();\n \t\t\n \t\t\tcheck(\")\");\n \t\t\t\n \t\t\tvar code=CodeBlock();\n \t\t\t\n \t\t\tvar elseCode;\n \t\t\tif (test(\"else\")) {\n \t\t\t\tlexer.next();\n \t\t\t\telseCode=CodeBlock();\n \t\t\t}\n \t\t\treturn new ASTUnaryNode(\"if\",{\"cond\":expr,\"code\":code,\"elseBlock\":elseCode});\n \t\t}\n \t\t\n// \t\tDo := \"do\" CodeBlock \"while\" \"(\" Expr \")\" \n//\t\tAST: \"do\": l:Expr, r:CodeBlock \n \t\tfunction Do() {\t\n \t\t\tdebugMsg(\"ProgramParser : Do\");\n \t\t\t\n \t\t\tlexer.next();\n \t\t\tvar code=CodeBlock();\n \t\t\t\n \t\t\tcheck(\"while\");\n \t\t\t\n \t\t\tcheck(\"(\");\n \t\t\t\n \t\t\tvar expr=Expr();\n \t\t\tcheck(\")\");\n \t\t\t\n \t\t\t\n \t\t\tcheck(\";\");\n\n \t\t\treturn new ASTBinaryNode(\"do\",expr,code);\n \t\t}\n \t\t\n// \t\tWhile := \"while\" \"(\" Expr \")\" \"{\" {Statement} \"}\" \n//\t\tAST: \"while\": l:Expr, r:codeBlock\n \t\tfunction While(){ \t\t\t\n \t\t\tdebugMsg(\"ProgramParser : While\");\n \t\t\t\n \t\t\t//if do is allowed, but while isn't allowed gotta check keyword in parser\n \t\t\tif (preventWhile) error.reservedWord(\"while\",lexer.current.line);\n \t\t\t\n \t\t\tlexer.next();\n \t\t\tcheck(\"(\");\n \t\t\t\n \t\t\tvar expr=Expr();\n \t\n \t\t\tcheck(\")\");\n \t\t\t\n \t\t\tvar code = CodeBlock();\n \t\t\t\t \t\t\t\n \t\t\treturn new ASTBinaryNode(\"while\",expr,code);\n \t\t}\n \t\t\n//\t\tFor := \"for\" \"(\"(\"each\" Ident \"in\" Ident | Ident Assignment \";\" Expr \";\" Assignment )\")\"CodeBlock\n//\t\tAST: \"foreach\": l: elem:Ident, array:Ident, code:CodeBlock \n//\t\tAST: \"for\": l: init:Assignment, cond:Expr,inc:Assignment, code:CodeBlock\n \t\tfunction For() { \t\t\t\n \t\t\tdebugMsg(\"ProgramParser : For\");\n \t\t\t\n \t\t\tlexer.next();\n \t\t\t\n \t\t\tcheck(\"(\");\n \t\t\t\n \t\t\tif (test(\"each\")) {\n \t\t\t\tlexer.next();\n \t\t\t\tvar elem=IdentSequence();\n \t\t\t\tcheck(\"in\");\n \t\t\t\tvar arr=IdentSequence();\n \t\t\t\t\n \t\t\t\tcheck(\")\");\n \t\t\t\t\n \t\t\t\tvar code=CodeBlock();\n \t\t\t\t\n \t\t\t\treturn new ASTUnaryNode(\"foreach\",{\"elem\":elem,\"array\":arr,\"code\":code});\n \t\t\t\t\n \t\t\t} else {\n \t\t\t\tvar init=Assignment();\n \t\t\t\tif (!init) error.assignmentExpected();\n \t\t\t\t\n \t\t\t\tcheck(\";\");\n \t\t\t\t\n \t\t\t\tvar cond=Expr();\n \t\t\t\n \t\t\t\n \t\t\t\tcheck(\";\");\n \t\t\t\n \t\t\t\tvar increment=Assignment();\n \t\t\t\tif (!increment) error.assignmentExpected();\n \t\t\t \n \t\t\t\tcheck(\")\");\n \t\t\t\tvar code=CodeBlock();\t\n \t\t\t\n \t\t\t\treturn new ASTUnaryNode(\"for\",{\"init\":init,\"cond\":cond,\"inc\":increment,\"code\":code});\n \t\t\t}\t\n \t\t}\n \t\t\n//\t\tSwitch := \"switch\" \"(\" Ident \")\" \"{\" {Option} [\"default\" \":\" CodeBlock] \"}\"\t\n// AST: \"switch\" : l \"ident\":IdentSequence,option:[0..x]{Option}, default:CodeBlock\n \t\tfunction Switch() {\t\t\t\n \t\t\tdebugMsg(\"ProgramParser : Switch\");\n \t\t\t\n \t\t\tlexer.next();\n \t\t\t\n \t\t\tcheck(\"(\");\n\n \t\t\tvar ident=IdentSequence();\n \t\t\tif (!ident) error.identifierExpected();\n \t\t\t\n \t\t\tcheck(\")\");\n \t\t\t\n \t\t\tcheck(\"{\");\n \t\t\t\n \t\t\tvar option=[];\n \t\t\tvar current=true;\n \t\t\tfor (var i=0;current && !eof();i++) {\n \t\t\t\tcurrent=Option();\n \t\t\t\tif (current) {\n \t\t\t\t\toption[i]=current;\n \t\t\t\t}\n \t\t\t}\n \t\t\tcheck(\"default\");\n \t\t\t\n \t\t\tcheck(\":\");\n \t\t\t\n \t\t\tvar defBlock=CodeBlock();\n \t\t \t\t\t\n \t\t\tcheck(\"}\");\n \t\t\t\n \t\t\treturn new ASTUnaryNode(\"switch\", {\"ident\":ident,\"option\":option,\"defBlock\":defBlock});\n \t\t}\n \t\t\n//\t\tOption := \"case\" Expr {\",\" Expr} \":\" CodeBlock\n// AST: \"case\" : l: [0..x]{Expr}, r:CodeBlock\n \t\tfunction Option() {\n \t\t\tif (!test(\"case\")) return false;\n \t\t\t\n \t\t\tdebugMsg(\"ProgramParser : Option\");\n \t\t\t\n \t\t\tvar exprList=[];\n \t\t\tvar i=0;\n \t\t\tdo {\n \t\t\t\tlexer.next();\n \t\t\t\t\n \t\t\t\texprList[i]=Expr();\n \t\t\t\ti++; \n \t\t\t\t\n \t\t\t} while (test(\",\") && !eof());\n \t\t\t\n \t\t\tcheck(\":\");\n \t\t\t\n \t\t\tvar code=CodeBlock();\n \t\t\t\n \t\t\treturn new ASTBinaryNode(\"case\",exprList,code);\n \t\t}\n \t\t\n// JavaScript := \"javascript\" {Letter | Digit | Symbol} \"javascript\"\n//\t\tAST: \"javascript\": l: String(JavascriptCode)\n \t\tfunction JavaScript() {\n \t\t\tdebugMsg(\"ProgramParser : JavaScript\");\n\t\t\tcheck(\"javascript\");\n\t\t\tcheck(\"(\")\n\t\t\tvar param=[];\n\t\t\tvar p=Ident(false);\n\t\t\tif (p) {\n\t\t\t\tparam.push(p)\n\t\t\t\twhile (test(\",\") && !eof()) {\n\t\t\t\t\tlexer.next();\n\t\t\t\t\tparam.push(Ident(true));\n\t\t\t\t}\t\n\t\t\t}\n \t\t\tcheck(\")\");\n \t\t\t\t\t\n \t\t\tvar js=lexer.current.content;\n \t\t\tcheckType(\"javascript\");\n \t\t\t\t\t\t\n \t\t\treturn new ASTUnaryNode(\"javascript\",{\"param\":param,\"js\":js});\n \t\t}\n \t\t\n// \t\tReturn := \"return\" [Expr] \n//\t\tAST: \"return\" : [\"expr\": Expr] \n \t\tfunction Return() {\n \t\t\tdebugMsg(\"ProgramParser : Return\");\n \t\t\tvar line=lexer.current.line;\n \t\t\t\n \t\t\tlexer.next();\n \t\t\t\n \t\t\tvar expr=Expr();\n \t\t\tvar ast=new ASTUnaryNode(\"return\",expr);\n \t\t\tast.line=line;\n \t\t\treturn ast;\n \t\t}\n\t}",
"function extractPresetOutput(){\n\toutlet(7, JSON.stringify(output));\n}",
"function searchPrettify(result: any) {\n const list: Array<any> = result.list\n const term: string = result.term\n return list\n .map((pkg: any) => {\n let type = pkg.type\n switch (type) {\n case 'node-package':\n type = chalk.green('js')\n break\n case 'perl-package':\n type = chalk.red('pl')\n break\n case 'python-package':\n type = chalk.yellow('py')\n break\n case 'r-package':\n type = chalk.blue('r')\n break\n default:\n type = chalk.red(' ')\n }\n let descr = pkg.description ? pkg.description : ''\n descr = ellipsize(descr, 60)\n descr = chalk.gray(\n descr.replace(new RegExp(term.replace('*', ''), 'ig'), (match: any) => {\n return chalk.underline(match)\n })\n )\n return sprintf('%-13s %-30s %-10s %s', type, pkg.name, pkg.version, descr)\n })\n .join('\\n')\n}",
"_generate(ast) {}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Brainstormer form, making variables/values upon "submit" | function createFormHandler(e) {
e.preventDefault()
// Add innerHTML apending to Brainstormer in this section
const characterInput = document.querySelector("#user-edit-character").value
const setupInput = document.querySelector("#user-edit-setup").value
const twistInput = document.querySelector("#user-edit-twist").value
const genreInput = document.querySelector("#user-edit-genre_id").value
postIdea(characterInput, setupInput, twistInput, genreInput)
} | [
"function setInputAndSubmit(aForm, aField, aValue)\n{\n setInput(aForm, aField, aValue);\n aForm.submit();\n}",
"_updateForm() {\n var form = this._getForm();\n form.find('#name').val(this.contact.name);\n form.find('#surname').val(this.contact.surname);\n form.find('#email').val(this.contact.email);\n form.find('#country').val(this.contact.country);\n }",
"function html_injection_get() {\n var form = document.getElementById(\"html_injection_get_form\");\n document.getElementById('html_injection_get').innerHTML = 'Hello, ' + document.getElementById('firstname').value + ' ' + document.getElementById('lastname').value;\n\n form.addEventListener('submit', handleForm);\n}",
"function fillForm(form, data){\n for(let I of Object.keys(data)){\n\tlet input = form.querySelector(printf('input[name=\"%1\"]', I));\n\tif(input.type == 'checkbox' || input.type == 'radio')\n\t input.checked = data[I];\n\telse\n\t input.value = data[I];\n }\n}",
"function fillForm() {\n var prod = JSON.parse(this.responseText);\n\n var inputs = document.getElementsByTagName(\"input\");\n inputs[0].value = prod.productId;\n inputs[1].value = prod.title;\n inputs[2].value = prod.description;\n inputs[3].value = prod.price;\n inputs[4].value = prod.tag;\n inputs[5].value = prod.imgPath;\n \n}",
"function processBrainstormUsingForm(formObject) {\n Logger.log(\"In the brainstorm, processing the form.\");\n // blob will be encoded as a string\n Logger.log(formObject);\n var formBlob = formObject.brainstorm;\n Logger.log(formBlob);\n // returns keywords\n var keywords = analyzeText(formBlob);\n Logger.log(keywords);\n //keywords = [\"banana\"];\n var urls = [];\n Logger.log(\"Sending keywords to image API.\");\n keywords.forEach(function(query) {\n Logger.log(query);\n var result = searchImages(query);\n urls.push(result);\n });\n Logger.log(urls);\n return urls;\n //return \"https://picjumbo.com/wp-content/uploads/fresh-bananas-on-glossy-table-and-red-background_free_stock_photos_picjumbo_DSC08378.jpg\";\n}",
"function afterSubmit() {\n getAllQuotes()\n form.reset()\n form.elements[0].focus()\n}",
"function handleSubmit(event) {\n event.preventDefault(); // When event happens page refreshed, this function prevents the default reaction\n const currentValue = input.value;\n paintGreeting(currentValue);\n saveName(currentValue);\n}",
"function handleFormSubmit() {\n\t// Get values of inputs\n\t// Pass values to addNewPost()\n var inputName = document.getElementById(\"input-username\").value;\n var inputCaption = document.getElementById(\"input-caption\").value;\n var inputPicture = document.getElementById(\"input-picture\").value;\n addNewPost(inputName, inputPicture, inputCaption);\n}",
"function submitAndRebuildForm() {\n\t\n\tvar compNegocio=null;\n\tvar elBody=null;\n\t\n\tvar numFormularios = document.forms.length\n\tvar numCompForm = document.forms[0].length;\n\tvar numCompFormSecundarios = 0;\n\tvar formPrincipal=null;\n\tvar actionFormPrincipal=null;\n\tvar nuevoFormulario=null;\n\tvar formularioSecundario=null;\n\tvar formActual=null;\n\tvar nuevoCustomForm=null;\n\t\n\ttry{\n\t// Obtenemos el numero de componentes de la pagina actual.\n\t\n\tcompNegocio = document.getElementsByTagName(\"controlnegocio\");\n\tif (self.frames.length > 0) {\n\t\ttry{\n\t\t\t// Referencia al formulario de la pagina\n\t\t\tformPrincipal = document.forms[0];\n\t\t\t// Recuperamos el action del formulario principal\n\t\t\tvar actionFormPrincipal = formPrincipal.action;\n\t\t\t// Definimos la variable en la que vamos a escribir el resultado de la concatenacion de todos los componentes de la pagina\n\t\t\tvar nuevoFormulario = \"<form name=Prueba method=POST action= \" + actionFormPrincipal + \">\";\n\t\t\t// Recorremos los componentes del formulario y reescribimos el document de la pagina con campos ocultos.\n\t\t\tvar contadorFormularios = 0;\n\t\t\tnuevoFormulario = nuevoFormulario + construyeTrozoForm(numCompForm,formPrincipal,\"\")\n\n\t\t\tif (numFormularios > 1) {\n\t\t\t\tvar nombreFormulario = \"\";\n\t\t\t\tvar nombreComponente = \"\";\n\t\t\t\tvar formularioSecundario;\n\t\t\t\tfor (contadorFormularios = 1; contadorFormularios < numFormularios; contadorFormularios++) {\n\t\t\t\t\tformularioSecundario = document.forms[contadorFormularios];\n\t\t\t\t\tnumCompForm = formularioSecundario.length;\n\t\t\t\t\tnombreFormulario = formularioSecundario.name;\n\t\t\t\t\tnombreComponente = formPrincipal.elements[nombreFormulario].value;\n\t\t\t\t\tnuevoFormulario = nuevoFormulario + construyeTrozoForm(numCompForm,nombreFormulario,nombreComponente)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Recorremos cada uno de los frames internos de la pagina principal y anyadimos al nuevo formulario los componentes de estos frames\n\t\t\tvar contadorInterno = 0;\n\t\t\tvar numElemFrame = 0;\n\t\t\tvar claveFrame = \"\";\n\t\t\t\n\t\t\tvar numFormFrames = 0;\n\t\t\tvar contadorFormFrames = 0;\n\t\t\tfor (contador = 0; contador < compNegocio.length; contador++) {\n\t\t\t\tnumFormFrames = self.frames[contador].document.forms.length;\n\t\t\t\tif (numFormFrames > 0) {\n\t\t\t\t\tfor (contadorFormFrames = 0; contadorFormFrames < numFormFrames; contadorFormFrames++) {\n\t\t\t\t\t\tclaveFrame = compNegocio[contador].getAttribute(\"name\");\n\t\t\t\t\t\tformActual = self.frames[claveFrame].document.forms[contadorFormFrames];\n\t\t\t\t\t\tnumCompForm = formActual.length;\n\t\t\t\t\t\tnumCompFormSecundarios = formActual.length;\n\t\t\t\t\t\tnuevoFormulario = nuevoFormulario + construyeTrozoForm(numCompForm,formActual,claveFrame)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Cerramos el tag del formulario\n\t\t\tnuevoFormulario = nuevoFormulario + \"</form>\";\n\t\t\t// Escribimos el formulario en el document.\n\t\t\t// Modificado para solucionar un problema en Netscape con XSL\n\t\t\t// no funciona el document.write al usar XSLs\n\t\t\telBody = document.getElementsByTagName(\"BODY\")[0];\n\t\t\tnuevoCustomForm = document.createElement(\"CUSTOMFORM\");\n\t\t\tnuevoCustomForm.innerHTML = nuevoFormulario;\n\t\t\telBody.appendChild(nuevoCustomForm);\n\t\t\tdocument.forms[\"Prueba\"].submit();\n\t\t}catch(err){\n\t\t\tdocument.forms[0].submit();\n\t\t}\n\t}\n\telse {\n\t\tdocument.forms[0].submit();\n\t}\n\t}finally{\n\t\tcompNegocio=null;\n\t\telBody=null;\n\t\tnumFormularios = 0;\n\t\tnumCompForm = 0;\n\t\tnumCompFormSecundarios = 0;\n\t\tformPrincipal=null;\n\t\tactionFormPrincipal=null;\n\t\tnuevoFormulario=null;\n\t\tformularioSecundario=null;\n\t\tformActual=null;\n\t\tnuevoCustomForm=null;\n\t}\n}",
"function submit() {\n\tif(!is_valid_value()) {\n\t\t// should return some error code\n\t\t$('#error_msg').html('invalid input, try again')\n\t\tsetTimeout(function() {\n\t\t\t$('#error_msg').html('')\n\t\t}, 1000)\n\t\t$('#valueInput').val('').focus()\n return\n }\n\n // Otherwise, let's roll\n store_block_data(\"value submitted\", get_data('username'), url,\n $(\"#valueInput\").val());\n \n store.refresh()\n find_website(url).block_start_time = new Date().getTime();\n store.save()\n\n\tshow_block_stuff();\n\tsubmit_clicked = true;\n}",
"function formFieldPopulation(){\n\t\tvar detailsObject = JSON.parse(localStorage.getItem('details'));\n\t\tif(detailsObject != null){\n\t\t\tconsole.log(detailsObject.firstname);\n\t\t\t$('#firstname').val(detailsObject.firstname);\n\t\t\t$('#lastname').val(detailsObject.lastname);\n\t\t\t$('#email').val(detailsObject.email);\n\t\t\t$('#phone').val(detailsObject.phone);\n\t\t\tconsole.log(detailsObject);\n\t\t}\n\t}",
"function submitPlayers(form){\n\tplayers[0] = form.player1.value;\n\tplayers[1] = form.player2.value;\n\tplayers[2] = form.player3.value;\n\tplayers[3] = form.player4.value;\n\t$(document).ready(function(){\n\t\t$(\".players\").hide();\n\t\t$(\"#hands\").show();\n\t\t$(\"#round1\").show();\n\t\tsetPlayer(players[turn]);\n\t});\n}",
"function storeFormValsTemporarily()\n{\n var myForm = arguments[0];\n var formElementValues = convertFormElements(myForm);\n pageControl.setConvertedFormElements(formElementValues);\n}",
"submitFormWith (data) {\n for (let key in data) {\n this.type(data[data], key)\n }\n\n this.wrapper.find('button#submit').trigger('submit')\n }",
"function cronJobCreateForm() {\n log(COL_TIMESTAMP, new Date())\n // Check for scheduled lessons from Wed to Wed\n var from = new Date();\n from.setDate(from.getDate() - from.getDay() + 3); // Get Wednesday of current week\n Logger.log('from %s', from.toString())\n var until = new Date(from);\n until.setDate(from.getDate() + 7); // Get a week from 'from' date\n Logger.log('until %s', until.toString());\n var dates = getScheduledDates(from, until);\n if (dates.length == 0) {\n log(COL_DATESTRING, '(not scheduled)');\n return;\n } else {\n log(COL_DATESTRING, dates2Str(dates, DATES_DELIMITER));\n }\n // Create form\n createForm(dates);\n}",
"function addFields () {\n\t\n\t$(\"#contestantsForm\").append('<input type=\"text\" /><br/><input type=\"text\" /><br/>');\n}",
"async function processForm(evt) {\n evt.preventDefault();\n // get data from form\n const name = document.querySelector(\"#name\").value;\n const year = document.querySelector(\"#year\").value;\n const email = document.querySelector(\"#email\").value;\n const color = document.querySelector(\"#color\").value;\n console.log(\"form values: \", name, year, email, color);\n\n const formData = {name, year, email, color};\n // const formData = {\"name\": name, \"year\": year, \"email\": email, \"color\": color};\n // const formData = {name: name, year: year, email: email, color: color};\n console.log(\"formData: \", formData);\n\n // make AJAX call to our Flask API\n const res = await axios.post(`${BASE_URL}`, formData);\n\n console.log(\"post request result: \", res);\n\n return res;\n}",
"function doSetup(submitName, errName) \n{\n\tvar e;\n\n\tif (null != submitName &&\n\t\t null != (e = document.getElementById(submitName))) \n\t\tif (e.hasAttribute('gamelab-submit-pending')) {\n\t\t\te.setAttribute('gamelab-submit-default', e.value);\n\t\t\te.value = e.getAttribute('gamelab-submit-pending');\n\t\t}\n\n\tif (null != errName) {\n\t\tdoHide(errName + 'Form');\n\t\tdoHide(errName + 'System');\n\t\tdoHide(errName + 'State');\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Closes the bubble set by "the hamster". Assumes that div ID for the bubble is "bubble_main" | function CloseBubble()
{
document.getElementById("bubble_main").style.visibility = "hidden";
} | [
"function closeSpeechBubble() {\n if (scripted) {\n scripted = false;\n }\n speed = 0;\n tempAud.pause();\n tempAud.currentTime = 0;\n setTimeout(function() {\n $(\"#talkbubble\").css(\"animation\", \"shrinkBubble .5s\");\n $(\".slide-right\").attr('class', 'slide-back');\n $(\"#bubbleText\").hide();\n bubbleClose.play();\n speaking = false;\n }, 2000);\n }",
"function closeDiv(element) {\r\n\telement.style.display='none';\t\t\t\t\t\r\n}",
"function popBubble(bubble) {\n bubble.animate({ height: 0, width: 0 }, 100, function() {\n bubble.remove();\n bubblesLeft--;\n });\n}",
"function closeMaindemo(event){\r\n\t\t$('#social-PopUp').fadeOut();\r\n\t\t$('#social-PopUp-main').fadeOut();\r\n\t}",
"function close_popup(popup) {\r\n popup.style.display = \"none\";\r\n}",
"function closeElement(element) {\r\n element.remove();\r\n}",
"function closePopup(popupId)\n{\n\tvar popupTarget = 0; \n\tif ( popupId == 1 ) { popupTarget = primaryTermsPopup; \t\t}\n\tif ( popupId == 2 ) { popupTarget = secondaryTermsPopup; \t}\n\t\n\tif ( popupTarget != 0 )\n\t{\n\t\t//Restore all possibly hidden brs.\n\t\tvar brsToReveal = document.getElementById(popupTarget.divNameFg).getElementsByTagName('br');\n\t\tfor ( var i = 0; i < brsToReveal.length; i++ )\n\t\t{\n\t\t\tshow(brsToReveal[i]);\n\t\t}\n\t}\n\t\n\thide( popups[popupId] );\n}",
"function closingMsg(){\n \n var closerText = document.getElementsByClassName('closingMsg');\n var changeText = closerText[0];\n\n changeText.textContent = 'That\\'s a great choice!'\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 closePopUp() {\n document.getElementById(\"loggerModalWrapper\").style.display = \"none\";\n }",
"function hide_popup()\n{\n\t$('.overlay').hide();\n\t$(\"#tooltip\").toggle();\n}",
"function closeModal() {\n\twinningMessage.style.display = 'none';\n}",
"function close() {\n\tcongratModalEl.style.display = 'none';\t\n}",
"function closeUpdateUserInfoMenu() {\n console.log(\"Is closing\");\n\n // Remove the update backdrop and update menu from the view\n $(\"div\").remove('#update-user-info-backdrop');\n $(\"div\").remove('#update-user-info-menu');\n}",
"function handleBubbleClick(bubble) {\n bubble.speed += ACCELERATION;\n bubble.points--;\n if (bubble.points === 0) {\n popBubble(bubble);\n }\n bubble.text(bubble.points);\n}",
"function w3_close() {\n mySidebar.style.display = \"none\";\n }",
"function hidePopup () {\n $('#popup').css('z-index', -20000);\n $('#popup').hide();\n $('#popup .popup-title').text('');\n $('#popup .popup-content').text('');\n $('.hide-container').hide();\n $('.container').css('background', '#FAFAFA');\n }",
"function closeEditGroupPopup(){\n\t$(\".tag-manage-outer\").css(\"display\",\"none\");\n}",
"function closeLyrics() {\n lyricsBackdrop.classList.remove('visible');\n document.body.classList.remove('no-scroll');\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The window has regained focus after having lost it. If the last element that had the focus obtained the focus via the keyboard, set our keyboard input flag. That previouslyfocused element is about to receive a focus event, and the handler for that can then treat the situation as if the focus was obtained via the keyboard. That helps a keyboard user reacquire the focused element when returning to the window. | function windowFocused() {
focusedWithKeyboard = previousFocusedWithKeyboard;
} | [
"function returnFocus() {\n if( focused )\n focused.focus();\n }",
"_handleFocusChange() {\n this.__focused = this.contains(document.activeElement);\n }",
"trapFocus () {\n let $focusablePanelBodyElements = this.$detailPanelBody\n .find('a[href], area[href], input, select, textarea, button, iframe, object, embed, [tabindex], *[contenteditable]')\n .not('[tabindex=-1], [disabled], :hidden, [aria-hidden]'),\n $focusableElements = this.$detailPanel\n .find('a[href], area[href], input, select, textarea, button, iframe, object, embed, [tabindex], *[contenteditable]')\n .not('[tabindex=-1], [disabled], :hidden, [aria-hidden]');\n\n // If the panel body contains a focusable element we should focus that rather than the close button\n if ($focusablePanelBodyElements.length > 0) {\n $focusablePanelBodyElements.first().trigger('focus');\n } else {\n this.$detailPanel.find('[data-table-detail-close-panel]').trigger('focus');\n }\n\n this.boundKeydownListener = this.keydownListener.bind(this, $focusableElements);\n this.$html.on('keydown', this.boundKeydownListener);\n }",
"function patchElementFocus(element) {\n element.focus = function () { return dispatch_events_1.dispatchFakeEvent(element, 'focus'); };\n element.blur = function () { return dispatch_events_1.dispatchFakeEvent(element, 'blur'); };\n }",
"function GameFocus(DP){\n\tdocument.activeElement.blur();\n\twindow.Mobile.GestureHandler.prototype.fakeCanvasFocus();\n\tkeyActions=keyActionsGame;\n}",
"_evtFocusOut(event) {\n const relatedTarget = event.relatedTarget;\n // Bail if the window is losing focus, to preserve edit mode. This test\n // assumes that we explicitly focus things rather than calling blur()\n if (!relatedTarget) {\n return;\n }\n // Bail if the item gaining focus is another cell,\n // and we should not be entering command mode.\n const index = this._findCell(relatedTarget);\n if (index !== -1) {\n const widget = this.widgets[index];\n if (widget.editorWidget.node.contains(relatedTarget)) {\n return;\n }\n }\n // Otherwise enter command mode if not already.\n if (this.mode !== 'command') {\n this.mode = 'command';\n // Switching to command mode currently focuses the notebook element, so\n // refocus the relatedTarget so the focus actually switches as intended.\n if (relatedTarget) {\n relatedTarget.focus();\n }\n }\n }",
"async function exitFocus() {\n xapi.Command.UserInterface.Extensions.Panel.Update({ PanelId: 'focus_on_me', Visibility: 'Auto' })\n xapi.Command.UserInterface.Message.Alert.Display({ Title: 'System Lost Focus', Text: 'Access to Webex Assistant and Ultrasound Pairing disabled', Duration: 5 })\n await GMM.write('inFocus', false)\n xapi.Config.Audio.Ultrasound.MaxVolume.set(0)\n xapi.Config.VoiceControl.Wakeword.Mode.set('Off')\n console.log({ Message: 'System Exited Focus' })\n}",
"didFocus () {\n\n }",
"get focusChanged() {\n return (this.flags & 1) /* Focus */ > 0\n }",
"handleBlur() {\n this._focussed = false;\n }",
"add_focus() {\n this.element.focus();\n }",
"function IsWindowFocused(flags = 0) {\r\n return bind.IsWindowFocused(flags);\r\n }",
"_containsFocus() {\n const activeElement = _getFocusedElementPierceShadowDom();\n return activeElement && this._element.nativeElement.contains(activeElement);\n }",
"focusWindow(n){\n if(this.win.n == n){\n this.$emit('focusWindow', n)\n this.focusInput()\n }\n }",
"onElementFocusIn(e){\n e.preventDefault();\n\n this.$parent.classList.add(this.className.focused);\n\n return false;\n }",
"focusNextWindow () {\n if (this.mailboxesWindow.isFocused()) {\n if (this.contentWindows.length) {\n this.contentWindows[0].focus()\n }\n } else {\n const focusedIndex = this.contentWindows.findIndex((w) => w.isFocused())\n if (focusedIndex === -1 || focusedIndex + 1 >= this.contentWindows.length) {\n this.mailboxesWindow.focus()\n } else {\n this.mailboxesWindow[focusedIndex + 1].focus()\n }\n }\n }",
"_checkGameFocus() {\n \tif (!document.hasFocus()) {\n \t\tGAME_SOUNDS.gameTheme.pause();\n \t\tthis._gameThemePaused = true;\n \t} else {\n \t\tif (this._gameThemePaused && !this._gameCompleted) {\n \t\t\tGAME_SOUNDS.gameTheme.play();\n \t\t\tthis._gameThemePaused = false;\n \t\t}\n \t}\n }",
"function SetKeyboardFocusHere(offset = 0) {\r\n bind.SetKeyboardFocusHere(offset);\r\n }",
"function verifyFocusIsNotTrapped(cyWrapper) {\n cyWrapper.should('be.focused');\n\n // focus can be transitioned freely when trap is unmounted\n let previousFocusedEl;\n cy.focused()\n .then(([lastlyFocusedEl]) => {\n return (previousFocusedEl = lastlyFocusedEl);\n })\n .tab();\n\n cy.focused().should(([nextFocusedEl]) =>\n expect(nextFocusedEl).not.equal(previousFocusedEl)\n );\n }",
"function FocusTrap(props) {\n const {\n children,\n disableAutoFocus = false,\n disableEnforceFocus = false,\n disableRestoreFocus = false,\n getTabbable = defaultGetTabbable,\n isEnabled = defaultIsEnabled,\n open\n } = props;\n const ignoreNextEnforceFocus = react.useRef(false);\n const sentinelStart = react.useRef(null);\n const sentinelEnd = react.useRef(null);\n const nodeToRestore = react.useRef(null);\n const reactFocusEventTarget = react.useRef(null);\n // This variable is useful when disableAutoFocus is true.\n // It waits for the active element to move into the component to activate.\n const activated = react.useRef(false);\n const rootRef = react.useRef(null);\n // @ts-expect-error TODO upstream fix\n const handleRef = useForkRef(children.ref, rootRef);\n const lastKeydown = react.useRef(null);\n react.useEffect(() => {\n // We might render an empty child.\n if (!open || !rootRef.current) {\n return;\n }\n activated.current = !disableAutoFocus;\n }, [disableAutoFocus, open]);\n react.useEffect(() => {\n // We might render an empty child.\n if (!open || !rootRef.current) {\n return;\n }\n const doc = ownerDocument(rootRef.current);\n if (!rootRef.current.contains(doc.activeElement)) {\n if (!rootRef.current.hasAttribute('tabIndex')) {\n if (false) {}\n rootRef.current.setAttribute('tabIndex', '-1');\n }\n if (activated.current) {\n rootRef.current.focus();\n }\n }\n return () => {\n // restoreLastFocus()\n if (!disableRestoreFocus) {\n // In IE11 it is possible for document.activeElement to be null resulting\n // in nodeToRestore.current being null.\n // Not all elements in IE11 have a focus method.\n // Once IE11 support is dropped the focus() call can be unconditional.\n if (nodeToRestore.current && nodeToRestore.current.focus) {\n ignoreNextEnforceFocus.current = true;\n nodeToRestore.current.focus();\n }\n nodeToRestore.current = null;\n }\n };\n // Missing `disableRestoreFocus` which is fine.\n // We don't support changing that prop on an open FocusTrap\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [open]);\n react.useEffect(() => {\n // We might render an empty child.\n if (!open || !rootRef.current) {\n return;\n }\n const doc = ownerDocument(rootRef.current);\n const contain = nativeEvent => {\n const {\n current: rootElement\n } = rootRef;\n\n // Cleanup functions are executed lazily in React 17.\n // Contain can be called between the component being unmounted and its cleanup function being run.\n if (rootElement === null) {\n return;\n }\n if (!doc.hasFocus() || disableEnforceFocus || !isEnabled() || ignoreNextEnforceFocus.current) {\n ignoreNextEnforceFocus.current = false;\n return;\n }\n if (!rootElement.contains(doc.activeElement)) {\n // if the focus event is not coming from inside the children's react tree, reset the refs\n if (nativeEvent && reactFocusEventTarget.current !== nativeEvent.target || doc.activeElement !== reactFocusEventTarget.current) {\n reactFocusEventTarget.current = null;\n } else if (reactFocusEventTarget.current !== null) {\n return;\n }\n if (!activated.current) {\n return;\n }\n let tabbable = [];\n if (doc.activeElement === sentinelStart.current || doc.activeElement === sentinelEnd.current) {\n tabbable = getTabbable(rootRef.current);\n }\n if (tabbable.length > 0) {\n var _lastKeydown$current, _lastKeydown$current2;\n const isShiftTab = Boolean(((_lastKeydown$current = lastKeydown.current) == null ? void 0 : _lastKeydown$current.shiftKey) && ((_lastKeydown$current2 = lastKeydown.current) == null ? void 0 : _lastKeydown$current2.key) === 'Tab');\n const focusNext = tabbable[0];\n const focusPrevious = tabbable[tabbable.length - 1];\n if (typeof focusNext !== 'string' && typeof focusPrevious !== 'string') {\n if (isShiftTab) {\n focusPrevious.focus();\n } else {\n focusNext.focus();\n }\n }\n } else {\n rootElement.focus();\n }\n }\n };\n const loopFocus = nativeEvent => {\n lastKeydown.current = nativeEvent;\n if (disableEnforceFocus || !isEnabled() || nativeEvent.key !== 'Tab') {\n return;\n }\n\n // Make sure the next tab starts from the right place.\n // doc.activeElement refers to the origin.\n if (doc.activeElement === rootRef.current && nativeEvent.shiftKey) {\n // We need to ignore the next contain as\n // it will try to move the focus back to the rootRef element.\n ignoreNextEnforceFocus.current = true;\n if (sentinelEnd.current) {\n sentinelEnd.current.focus();\n }\n }\n };\n doc.addEventListener('focusin', contain);\n doc.addEventListener('keydown', loopFocus, true);\n\n // With Edge, Safari and Firefox, no focus related events are fired when the focused area stops being a focused area.\n // e.g. https://bugzilla.mozilla.org/show_bug.cgi?id=559561.\n // Instead, we can look if the active element was restored on the BODY element.\n //\n // The whatwg spec defines how the browser should behave but does not explicitly mention any events:\n // https://html.spec.whatwg.org/multipage/interaction.html#focus-fixup-rule.\n const interval = setInterval(() => {\n if (doc.activeElement && doc.activeElement.tagName === 'BODY') {\n contain(null);\n }\n }, 50);\n return () => {\n clearInterval(interval);\n doc.removeEventListener('focusin', contain);\n doc.removeEventListener('keydown', loopFocus, true);\n };\n }, [disableAutoFocus, disableEnforceFocus, disableRestoreFocus, isEnabled, open, getTabbable]);\n const onFocus = event => {\n if (nodeToRestore.current === null) {\n nodeToRestore.current = event.relatedTarget;\n }\n activated.current = true;\n reactFocusEventTarget.current = event.target;\n const childrenPropsHandler = children.props.onFocus;\n if (childrenPropsHandler) {\n childrenPropsHandler(event);\n }\n };\n const handleFocusSentinel = event => {\n if (nodeToRestore.current === null) {\n nodeToRestore.current = event.relatedTarget;\n }\n activated.current = true;\n };\n return /*#__PURE__*/(0,jsx_runtime.jsxs)(react.Fragment, {\n children: [/*#__PURE__*/(0,jsx_runtime.jsx)(\"div\", {\n tabIndex: open ? 0 : -1,\n onFocus: handleFocusSentinel,\n ref: sentinelStart,\n \"data-testid\": \"sentinelStart\"\n }), /*#__PURE__*/react.cloneElement(children, {\n ref: handleRef,\n onFocus\n }), /*#__PURE__*/(0,jsx_runtime.jsx)(\"div\", {\n tabIndex: open ? 0 : -1,\n onFocus: handleFocusSentinel,\n ref: sentinelEnd,\n \"data-testid\": \"sentinelEnd\"\n })]\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return true or false if there are too many phantoms running | function checkPhantomStatus() {
if (phantomChildren.length < maxInstances) {
return true;
}
return false;
} | [
"function OneShotLimitReached()\n{\n\treturn (crashesStarted + gearShiftsStarted) > oneShotLimit;\n}",
"end() {\n\t\treturn this.prog.length === 0;\n\t}",
"getCanReplicate() {\n return this.getMaximumReplications() === 1 ? false :\n this.getCurrentReplications() <= this.getMaximumReplications();\n }",
"_noMoreActivePlayers() {\n const nextActivePlayer = getNextActivePlayerFromIndex(\n this.players,\n this.activePlayerIndex\n );\n return nextActivePlayer === this.activePlayer;\n }",
"moreQuestionsAvailable() {\n\treturn (this.progress.qAnswered < this.progress.qTotal);\n }",
"isComplete (packs) {\n return packs.every(pack => {\n return Pathfinder.isLifecycleValid (pack, packs)\n })\n }",
"function _canPromote() {\n return (remainingSeconds <= 0);\n }",
"isBusy() {\n return this.totalTasks() >= this.options.maxPoolSize;\n }",
"function hasMultipleInstancesOfName( name ){\n\treturn usedNames[ name ] > 1;\n}",
"hasMultipleConnections() {\n let result = false;\n this.getConnections().forEach(connection => {\n this.getConnections().forEach(_connection => {\n if (_connection.id !== connection.id) {\n if (_connection.source.node === connection.source.node) {\n if (_connection.target.node === connection.target.node) {\n result = true;\n }\n }\n }\n })\n });\n return result;\n }",
"overflown() {\n let _this = this;\n\n return this.result.split('\\n').some((line) => {\n return line.length > _this.config['max-len'];\n });\n }",
"containsLongRules() {\n return this.productions.find(p => p.right.length > 2) !== undefined;\n }",
"function animationRunning(){\r\n\treturn animations.length > 0;\r\n}",
"receivedCall(args, times) {\n const minRequired = times || 1;\n if (args.length === 0 && this.hasEmptyCalls(minRequired)) {\n return true;\n }\n const setupArgs = this.convertArgsToArguments(args);\n let matchCount = 0;\n for (const call of this.calls) {\n const isMatch = this.argumentsMatch(setupArgs, call);\n if (isMatch === true) {\n matchCount++;\n if (matchCount >= minRequired) {\n return true;\n }\n }\n }\n return false;\n }",
"isPartialWorkset () {\n return (Mdf.worksetParamCount(this.worksetCurrent) !== Mdf.paramCount(this.theModel)) &&\n (!this.worksetCurrent?.BaseRunDigest || !this.isExistInRunTextList({ ModelDigest: this.digest, RunDigest: this.worksetCurrent?.BaseRunDigest }))\n }",
"hasReachedMaxLimit (list, maxLimit) {\n\t\treturn list && list.length === maxLimit;\n\t}",
"function isAnswersCountValidOnSubmit() {\n var countValues = 0;\n for( var i=0; i < $scope.form.masterAnswers.length; i++ ) {\n if ($scope.form.masterAnswers[i].checked == true) {\n countValues++;\n }\n }\n if (countValues < 2) {\n return false;\n }else {\n return true;\n }\n }",
"function allVideoIdsReady() {\n if (!useVideoJs()) {\n return (nrOfPlayersReady == videoIds.length); // TODO\n } else {\n for (var i = 0; i < videoIds.length; ++i) {\n if (!videoIdsReady[videoIds[i]]) {\n return false;\n }\n }\n return true;\n }\n }",
"function procExists(host) {\n return typeof getProc(host) != 'undefined'\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
open mobile recharge page | mobileRecharge() {
this.set('route.path', '/mobile');
} | [
"function fnOpenDcrLockeduserScreen(userCode) {\n $.mobile.changePage(\"/HiDoctor_Activity/MobileNotification/DCRLockDetail?userCode=\" + userCode, {\n type: \"post\",\n reverse: false,\n changeHash: false\n });\n}",
"function showCorrectLogonPage() {\n if(initializeRewards.urlContainsFlowID()){\n changePageFn('#urlogon');\n } else if (isCustomerUsingToken(ccoTokenKey)) {\n changePageFn('#cco');\n }else if (isCustomerUsingToken(bbTokenKey)) {\n changePageFn('#bb');\n }\n }",
"function changeLes7Oef61Page() {\n $.mobile.navigate( \"#les7Oef61\", { transition: 'slide'} );\n }// End function changeLes7Oef61Page()",
"function showReg()\n{\n var lang = 'en';\n if ('lang' in args)\n lang = args.lang;\n var\tform\t= this.form;\n var\trecid\t= this.id.substring(7);\n // display details\n window.open('WmbDetail.php?IDMB=' + recid + '&lang=' + lang,\n 'baptism');\n return false;\n}\t\t// showReg",
"function fnOpenOrderHistoryDetailView(id) {\n $.mobile.changePage(\"/HiDoctor_Activity/OTC/OrderHistoryDetailView?orderID=\" + id.split('_')[0] + \"&from=\" + id.split('_')[1], {\n type: \"post\",\n reverse: false,\n changeHash: false\n });\n}",
"openCheckout() {\n // TODO: Remove the need for a parameter in this function\n this.props.handleCartClose(false)\n this.props.navigation.navigate('WebCheckoutScreen', {\n webUrl: this.props.checkout.webUrl,\n }); ('WebCheckoutScreen')\n }",
"function fnOpenOrderSingleApproval(id) {\n $.mobile.changePage(\"/HiDoctor_Activity/OTC/SalesOrderSingleApproval?orderID=\" + id.split('^')[0] + \"&userCode=\" + id.split('^')[1], {\n type: \"post\",\n reverse: false,\n changeHash: false\n });\n}",
"function OpenADPage(){\n newleft=screen.width - 300;\n ADPage=window.open(\"/_myweb/hiad/280x300.html\",\"myweb_pop\",\"height=310,width=310,top=0,left=\" + newleft + \",toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,status=no\");\n}",
"function view_itin(link, own) {\n\twindow.location.href = \"../itinerary_detail/itinerary_details.html?id=\" + link;\n}",
"function openPopupPromoCode() {\n window.location.hash = '#?promoCodePopup';\n $body.addClass('overflow');\n $overlayPromoCode.addClass('open');\n scrollTo($body, 0, 500, $overlayPromoCode);\n }",
"function changeLes5Oef2Page() {\n $.mobile.navigate( \"#les5Oef2\", { transition: 'slide'} );\n }// End function changeLes5Oef2Page()",
"function changeLes8OefPage() {\n $.mobile.navigate( \"#les8home\", { transition: 'slide'} );\n }// End function changeLes8OefPage()",
"function returnToRALanding(){\n var mcsUrl = localStorage['RA_MCS_URL'],\n wNd = getTopWindow() || window;\n if (mcsUrl){\n wNd.location.href = mcsUrl + '/common/emxNavigator.jsp?appName=SIMREII_AP' +\n '&suiteKey=SimulationCentral&StringResourceFileId=smaSimulationCentralStringResource' +\n '&SuiteDirectory=simulationcentral';\n } else {\n wNd.location.href = '../common/emxNavigator.jsp?appName=SIMREII_AP' +\n '&suiteKey=SimulationCentral&StringResourceFileId=smaSimulationCentralStringResource' +\n '&SuiteDirectory=simulationcentral';\n }\n}",
"function Aufloesung() {\n\t\tif ( ($(document).width() <= 827) || ($(document).height() <= 420) ) {\n\t\t var $Check = confirm(\"Aufgrund der geringen Auflösung empfehlen wir die Verwendung unserer Mobilen Seite.\");\n\t\t\tif ( $Check == true) {\n\t\t\t\twindow.location = \"/mobile\";\n\t\t\t} else {\n\t\t\t// Sonst ganz normal weiterladen\n\t\t\t}\n\t\t}\n\t}",
"function descargarInspeccionMpApk(){\n $('.fb').show();\n $('.fbback').show();\n $('body').css('overflow','hidden');\n location.href=\"http://www.montajesyprocesos.com/inspeccion/servidor/aplicacion/Inspeccion_MP-debug.apk\";\n cerrarVentanaCarga();\n}",
"function openRelease() {\n jetpack.tabs.open(releaseLink);\n jetpack.tabs[jetpack.tabs.length - 1].focus();\n}",
"function changeLes7Page() {\n $.mobile.navigate( \"#les7Page\", { transition: 'slide'} );\n }// End function changeLes7Page()",
"function detailsClick(ipaddr)\n{\n window.open(\"details.html?ipaddr=\"+ipaddr, '_blank').focus();\n}",
"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 }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
buttonPost Call a simple POST request when clicking on a button | function buttonPost(url, callingButton) {
$(document).ready(function() {
$(callingButton).click(function(){
$.post(url, function(returnString) {
if (returnString.status == true) {
alert('success');
} else {
alert('failure');
}
}, 'json');
});
});
} | [
"function buttonTopic(button, action) {\n let xhr = new XMLHttpRequest();\n let data = {\"session\": button.dataset.id}\n xhr.responseType = \"json\";\n xhr.open(\"PUT\", \"../../api/session/session.php\");\n\n xhr.send(JSON.stringify(data));\n setTimeout(function () {\n window.location = \"../../index.php?controller=topic&action=\" + action + \"\";\n }, 1000);\n}",
"function postTweetHandler(){\n\t$('#postTweetButton').on('click', function(e){\n\t\te.preventDefault();\n\t\tvar tweetContent = $('#tweetText').val();\n tweetAjaxPost(tweetContent)\n\t});\n}",
"function onBtnAskClick(e) {\n e.preventDefault();\n \n // find out which of the [Choice][Range][Free] checkboxes are checked\n var ckb = null;\n for (i = 0; i < ckbChoices.length; i++) {\n if (ckbChoices[i].checked) {\n ckb = ckbChoices[i];\n break;\n }\n }\n \n if (txtQ.value.length < 1 || ckb == null) {\n alert(\"Question definition is incomplete!\");\n return;\n }\n \n // construct the JSON object to be sent to the server\n var question = { \"QuestionType\" : ckb.name, \"QuestionText\" : txtQ.value };\n \n // prepare the web POST request\n var request = new XMLHttpRequest();\n request.open(\"POST\", `${urlHostAPI}?name=${username}&cmd=ask`, true);\n request.timeout = 2000;\n request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');\n request.onload = onStatusResponse;\n request.send(JSON.stringify(question));\n}",
"function submitLike(event) {\n id=($(this).attr('id')).slice(5)\n let path = like_post_url\n let json_data ={\"postID\":id}\n $.post(path,\n json_data,\n submitLike_callback);\n // TODO Objective 10: send post-n id via AJAX POST to like_view (reload page upon success)\n}",
"function sendButtonMessage(recipientId,title,buttons) {\n var messageData = {\n recipient: { \n id: recipientId\n },\n message: {\n attachment: {\n type: \"template\",\n payload: {\n template_type: \"button\",\n text: title,\n buttons:buttons\n }\n }\n }\n };\n\n callSendAPI(messageData);\n}",
"function pokeSubmit(pokee) {\n $.ajaxSetup({\n headers: {\n 'X-CSRF-TOKEN': $('meta[name=\"csrf-token\"]').attr('content')\n }\n });\n $.ajax({\n url: '/poke',\n type: 'POST',\n data: {pokee: pokee},\n error: function(data)\n {\n console.log(\"Something caught fire, probably server related!\");\n }\n });\n}",
"function CreateSubmitButton(CLID, isAsync)\n{\n DW(CreateSubmitButton_(CLID, isAsync));\n}",
"function buttonSubmitHandler(updatedDeck) {\n updateDeck(updatedDeck).then((editedDeck) =>\n history.push(`/decks/${editedDeck.id}`)\n );\n }",
"function vote(a_Button, a_SongHash, a_VoteType, a_VoteValue)\n{\n\t// Highlight and disable the button for a while:\n\ta_Button.style.opacity = '0.5';\n\ta_Button.enabled = false\n\tsetTimeout(function()\n\t{\n\t\ta_Button.style.opacity = '1';\n\t\ta_Button.enabled = false;\n\t}, 1000);\n\n\tvar xhttp = new XMLHttpRequest();\n\txhttp.onreadystatechange = function()\n\t{\n\t\tif ((this.readyState === 4) && (this.status === 200))\n\t\t{\n\t\t\t// TODO: Update the relevant song's rating\n\t\t\t// document.getElementById(\"demo\").innerHTML = this.responseText;\n\t\t}\n\t};\n\txhttp.open(\"POST\", \"api/vote\", true);\n\txhttp.setRequestHeader(\"Content-type\", \"application/x-www-form-urlencoded\");\n\txhttp.send(\"songHash=\" + a_SongHash + \"&voteType=\" + a_VoteType + \"&voteValue=\" + a_VoteValue);\n}",
"submitData(api){\n // console.log(this.message);\n if(this.message === \"\"){\n console.log(\"cannot submit the form!!\")\n return false;\n }\n\n fetch(api,{\n method:'POST',\n body: this.message,\n });\n\n return true;\n }",
"handlePost(e){\n\t\te.preventDefault();\n\t\tthis.setState({\n\t\t\tisChecked:true,\n\t\t\thidediv:true\n\t\t})\n\t\tthis.postUserData(e.target.value,true);\n\t}",
"function clickButton(button, callback) {\n if (!(button instanceof $)) {\n button = $(button);\n }\n if (!button.hasClass(\"inline-editable-button\")) {\n button = button.closest(\".inline-editable-button\");\n } /*child element was clicked inside the button*/\n var editable = button.data(\"editable-element\") ? $(button.data(\"editable-element\")) : button.closest(\".inline-editable\") || null,\n cntr = button.data(\"editable-container\") ? $(button.data(\"editable-container\")) : editable.closest(\".inline-editable-host\"),\n json = editable == null ? null : editable.data(\"json-result-item\") || (!!editable.data(\"json-var\") ? eval(editable.data(\"json-var\")) : button.data()),\n form = button.closest(\"form\"),\n formData = json,\n tmpln = button.data(\"template\"),\n insertOrder = button.data(\"insert-order\"),\n url = button.data(\"url\"),\n urlDataType = button.data(\"url-datatype\") || \"json\",\n urlMethod = button.data(\"url-method\"),\n clickCallbacks = [];\n for (var prop in json) {\n if (json[prop] instanceof $ || $.isFunction(json[prop]) || !!(json[prop] || {}).eventNamespace) {\n delete json[prop]; /*remove jquery items, functions, and jquery widgets*/\n }\n }\n clickCallbacks.push(function () {\n $(button.data(\"host-selector\")).each(function (i, host) {\n autoasync.refreshEditable({ editable: host, button: button });\n });\n });\n if (callback)\n clickCallbacks.push(callback);\n\n clickCallbacks.push(function () {\n /*If the container is now empty, then check for noitems template or button*/\n appendItems(cntr);\n });\n var encType = '';\n if (form instanceof $ && form.length > 0) {\n encType = form.attr('enctype');\n if (button instanceof $ && !button.hasClass(\"link-button-cancel\") && !button.hasClass(\"novalidate\")) {\n if (!autoasync.isValidForm(button)) {\n return;\n }\n }\n if (typeof url == 'undefined') {\n url = form.attr(\"action\");\n urlMethod = urlMethod || form.attr(\"method\");\n }\n json = form.toObject({ json: json });\n formData = encType != 'multipart/form-data'\n ? form.serialize()\n : new FormData(form[0]);\n }\n var togglePrms = { container: cntr, editable: editable, button: button, form: form, templateName: tmpln, data: json, url: url, insertOrder: insertOrder };\n togglePrms = autoasync.toggleAction(togglePrms);\n if (!!url) {\n if (togglePrms.templateName) {\n button.data(\"ajax-submit-wait-message-disable\", true);\n }\n urlMethod = (urlMethod || \"post\").toLowerCase();\n var postData = formData,\n postButtonId = button.attr('id');\n if (urlMethod == \"get\" && !postData) {\n postData = {};\n }\n if (postButtonId && postData) {\n if (postData.split) {\n postData = postData + \"&\" + postButtonId + \"=\" + postButtonId;\n } else if (postData instanceof FormData) {\n postData.append(postButtonId, postButtonId);\n } else {\n postData[postButtonId] = postButtonId;\n }\n }\n autoasync.post({ data: urlMethod == \"post\" && encType != 'multipart/form-data' ? json : postData, type: urlMethod, cache: false, url: url, dataType: urlDataType },\n function (result) {\n togglePrms.isUpdate = true;\n if (!result.split) {\n if ($.cookie && result.cookie && result.cookie && result.cookie.length > 0) {\n $.each(result.cookie, function (index, item) {\n $.cookie(item.name, item.value, { expires: item.expires || 7, path: item.path || '/' });\n });\n }\n if (result.redirect && result.redirect.split) {\n window.location.href = result.redirect;\n }\n if (result.reload) {\n window.location.href = window.location.href;\n }\n var dataItems = result.Items || result.items;\n if (!dataItems || dataItems.length == 0)\n dataItems = [].concat(result.Item || result.item || result);\n togglePrms.data = dataItems[0];\n if (result.templateName) {\n togglePrms.templateName = result.templateName;\n }\n autoasync.toggleAction(togglePrms);\n autoasync.resultMessage($.extend({}, result, { element: togglePrms.editable }));\n if (dataItems.length > 1) {\n dataItems = dataItems.slice(1);\n autoasync.appendItems(cntr, dataItems);\n }\n } else {\n togglePrms.html = result;\n autoasync.toggleAction(togglePrms);\n }\n clickCallbacks.forEach(function (item) {\n if ($.isFunction(item)) {\n item(togglePrms);\n }\n });\n }\n );\n } else {\n clickCallbacks.forEach(function (item) {\n if ($.isFunction(item)) {\n item(togglePrms);\n }\n });\n }\n }",
"function postNewEan13(button) {\n var inp = $(button.siblings(\"input.ean13addbox\")[0]);\n var ean13 = inp.val();\n if (! ean13validate(ean13)){\n alert(\"Le code EAN13 proposé n\\'est pas correcte. [\"\n + ean13clean(ean13) + \"] \" + ean13clean(ean13).length );\n return null;\n }\n var lis = $(button.parents(\"li.resitem\")[0]);\n var resid = button.resid();\n\n return $.ajax({\n url: document.folksonomie.postbase + 'resource.php',\n type: 'post',\n data: {\n folksores: resid,\n folksoean13: ean13clean(ean13)\n },\n success: function(data) {\n var cean = lis.find(\"span.currentean13\");\n if (cean.text().length > 0) {\n cean.text(cean.text() + \", \" + ean13dashDisplay(ean13));\n }\n else {\n cean.text(ean13dashDisplay(ean13));\n }\n lis.find(\"input.ean13addbox\").val(\"\");\n },\n error: function(xhr, msg) {\n if (xhr.status == 409) {\n alert(\"Le numéro EAN13 \" + ean13\n + \" est déjà associé à cette ressource.\");\n }\n else {\n alert(\"Error posting new ean13 \"\n + msg + \" status \" + xhr.status\n + \" \" + xhr.statusText);\n }\n }\n });\n}",
"function addClickListener(event) {\n // Prevents the button from causing the form to submit...\n event.preventDefault();\n // Debug message\n console.log('addClickListener');\n\n /* TODO: Create an ajax call to POST data to the target url\n * \"engine.php?a=add\".\n * The server expects a single POST key named \"text\".\n * TODO: If the call is successful, set the value of the text to \"\".\n * TODO: Use the function createItem by passing the returned JSON object\n * and append the HTML object returned to the ul with the id \n * \"todo_list\".\n * NOTE: \n * Remeber that the JSON response contains item and debug_info.\n */\n \n let text = $(\"#item_input\").val();\n let data = { text: text };\n $.post(\"engine.php?a=add\", data,function(response){\n new_j = JSON.parse(response);\n $(\"#item_input\").val(\"\");\n let new_item = createItem(new_j.item);\n $(\"ul#todo_list\").append(new_item);\n })\n\n}",
"function buttonClick() {\n var form = $('#myForm');\n \n var id = event.target.id;\n JSON.stringify($('form').serializeObject(id));\n\n return false;\n }",
"function sendNewPostEvent(postData) {\n request.post(TIMELINE_POST_EVENT_URL, {\n json: postData\n })\n .on('response', function (res) {\n if (res.statusCode != 200) {\n console.log(\"ERROR \" + res.statusCode + \": Could not send New Post event!\");\n res.on('data', function (data) {\n console.log(\"Data: \" + data);\n });\n }\n });\n}",
"handleSubmit(e) {\n e.preventDefault();\n \n this.handleClick();\n }",
"function invokeByPost(url, requestData, onLoad, acceptType) {\n\tvar xhr = createXHR();\n\t\n\txhr.onreadystatechange = function() {\n\t\tif (xhr.readyState == 4) {\n\t\t\tonLoad(xhr);\n\t\t\txhr = null; //Avoid IE memory leak\n\t\t}\n\t}\n\tvar body = \"\";\n\tfor (var name in requestData) {\n\t\tif (body.length > 0) {\n\t\t\tbody = body + \"&\";\n\t\t}\n\t\tbody = body + escape(name) + \"=\" + escape(requestData[name]);\n\t}\n\txhr.open(\"POST\", url, true);\n\txhr.setRequestHeader(\"Content-Type\",\n\t\t\"application/x-www-form-urlencoded; charset=UTF-8\");\n\txhr.setRequestHeader(\"Accept\", acceptType);\n\txhr.send(body);\n}",
"function postCoffee() {\r\n let name = document.getElementById(\"coffeetitle\");\r\n let combo = {};\r\n let text = document.getElementById(\"dynamictext\");\r\n\r\n // Build JSON.\r\n combo[\"name\"] = name.value.substring(0,21);\r\n combo[\"color\"] = coffeeColor;\r\n combo[\"sugar\"] = sugarContent;\r\n combo[\"cream\"] = creamerContent;\r\n\r\n // Conditional for adding a post.\r\n if (name.value !== \"\") {\r\n // Clear name.\r\n name.value = \"\";\r\n let url = \"https://coffeemakerservice.herokuapp.com/\";\r\n // Build the fetchOptions to be used.\r\n let fetchOptions = {\r\n method : 'POST',\r\n headers : {\r\n 'Accept': 'application/json',\r\n 'Content-Type' : 'application/json'\r\n },\r\n body : JSON.stringify(combo)\r\n };\r\n // Attempt to post the message.\r\n fetch(url, fetchOptions)\r\n .then(checkStatus)\r\n .then(function(responseText) {\r\n text.innerHTML = responseText;\r\n \t\t})\r\n \t\t.catch(function(error) {\r\n \t\t\ttext.innerHTML = error;\r\n \t\t});\r\n }\r\n }",
"function sendToServer() {\n // Url issue is sent to\n const url = 'http://localhost:1234/whap/add-issue?' + 'iss';\n // Data being sent\n var data = {\n name: document.getElementById(\"title\").value,\n des: document.getElementById(\"msg\").value,\n prio: document.getElementById(\"priority\").value,\n os: document.getElementById(\"OS\").value,\n com: document.getElementById(\"component\").value,\n ass: document.getElementById(\"assignee\").value,\n user: window.name\n };\n\n // Posts the data\n var resp = postData('http://localhost:1234/whap/add-issue', data)\n // Tells user they did it\n .then(alert(\"You did it\"));\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
edit selectGdfTender Ajax call | function editSelGdfTender(ajaxUrl, namespace) {
$("#loaderWrap").show();
var tenderRefNo = $("#tenderReferenceNumber").val();
var productCategoryVal = $("#productCategoryVal").val();
var title = $("#title").val();
var publicationDate = $("#publicationDate").val();
var deadlineForTechBidsSub = $("#deadlineForTechBidsSub").val();
var method = $("#method").text();
var tenderSubRefId = $("#tenderSubRefId").val();
var schedularJson = [];
$(".list-product-wrapper .list-product").each(
function() {
itemsArray = [];
$(this).find(
".tenderRootDiv .tenderItemTable .tbl_posts_body tr")
.each(
function() {
itemsArray.push({
tenderItemNumber : $(this).find(
"#tendItem").val(),
gdfGenericCode : $(this).find(
"#gdfGenCode").val(),
tenderItemRefId : $(this).find(
"#tenderItemRefId").val(),
})
});
schedularJson.push({
schduleNumber : $(this).find("#schedNum").text(),
scheduleName : $(this).find("#schedName").val(),
patientTarget : $(this).find("#patTarget").val(),
tenderItems : itemsArray
});
});
var jsonInput = {
tenderRefNo : tenderRefNo,
productCategoryVal : productCategoryVal,
title : title,
publicationDate : publicationDate,
deadlineForTechBidsSub : deadlineForTechBidsSub,
method : method,
tenderSubRefId : tenderSubRefId,
selGdfTenderArr : schedularJson
};
// alert(":::jsonInput:::" + jsonInput);
var url = ajaxUrl;
var data = {
"requestData" : JSON.stringify(jsonInput)
};
jQuery.post(url, data, function(data) {
var response = JSON.stringify(eval("(" + data + ")"));
// alert(":::response:::" + response);
var json = JSON.parse(response);
// alert(":::json:::" + json);
$('.adhocinfo').empty()
$('.adhocinfo').append(html);
});
// $('.nextBtnTab1').attr("disabled", false);
// $('#tabNext').attr("disabled", false);
// disableToolTip();
setTimeout(function() {
$("#loaderWrap").hide();
}, 2000);
} | [
"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 saveSelGdfTender(ajaxUrl, namespace) {\n\n\t$(\"#loaderWrap\").show();\n\n\tvar tenderRefNo = $(\"#tenderReferenceNumber\").val();\n\tvar productCategoryVal = $(\"#productCategoryVal\").val();\n\tvar title = $(\"#title\").val();\n\tvar publicationDate = $(\"#publicationDate\").val();\n\tvar deadlineForTechBidsSub = $(\"#deadlineForTechBidsSub\").val();\n\tvar method = $(\"#method\").text();\n\tvar tenderSubRefId = $(\"#tenderSubRefId\").val();\n\n\tvar schedularJson = [];\n\t$(\".list-product-wrapper .list-product\").each(\n\t\t\tfunction() {\n\t\t\t\titemsArray = [];\n\t\t\t\t$(this).find(\n\t\t\t\t\t\t\".tenderRootDiv .tenderItemTable .tbl_posts_body tr\")\n\t\t\t\t\t\t.each(\n\t\t\t\t\t\t\t\tfunction() {\n\t\t\t\t\t\t\t\t\titemsArray.push({\n\t\t\t\t\t\t\t\t\t\ttenderItemNumber : $(this).find(\n\t\t\t\t\t\t\t\t\t\t\t\t\"#tendItem\").val(),\n\t\t\t\t\t\t\t\t\t\tgdfGenericCode : $(this).find(\n\t\t\t\t\t\t\t\t\t\t\t\t\"#gdfGenCode\").val(),\n\t\t\t\t\t\t\t\t\t\ttenderItemRefId : $(this).find(\n\t\t\t\t\t\t\t\t\t\t\t\t\"#tenderItemRefId\").val(),\n\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t});\n\t\t\t\tschedularJson.push({\n\t\t\t\t\tschduleNumber : $(this).find(\"#schedNum\").text(),\n\t\t\t\t\tscheduleName : $(this).find(\"#schedName\").val(),\n\t\t\t\t\tpatientTarget : $(this).find(\"#patTarget\").val(),\n\t\t\t\t\ttenderItems : itemsArray\n\t\t\t\t});\n\t\t\t});\n\n\tvar jsonInput = {\n\t\ttenderRefNo : tenderRefNo,\n\t\tproductCategoryVal : productCategoryVal,\n\t\ttitle : title,\n\t\tpublicationDate : publicationDate,\n\t\tdeadlineForTechBidsSub : deadlineForTechBidsSub,\n\t\tmethod : method,\n\t\ttenderSubRefId : tenderSubRefId,\n\t\tselGdfTenderArr : schedularJson\n\t};\n\n\t// alert(\":::jsonInput:::\" + jsonInput);\n\tvar url = ajaxUrl;\n\n\tvar data = {\n\t\t\"requestData\" : JSON.stringify(jsonInput)\n\t};\n\n\tjQuery.post(url, data, function(data) {\n\n\t\tvar response = JSON.stringify(eval(\"(\" + data + \")\"));\n\t\t// alert(\":::response:::\" + response);\n\t\tvar json = JSON.parse(response);\n\t\t// alert(\":::json:::\" + json);\n\n\t\t$('.adhocinfo').empty()\n\t\t$('.adhocinfo').append(html);\n\n\t});\n\t// $('.nextBtnTab1').attr(\"disabled\", false);\n\t// $('#tabNext').attr(\"disabled\", false);\n\tdisableToolTip();\n\tsetTimeout(function() {\n\t\t$(\"#loaderWrap\").hide();\n\t}, 2000);\n}",
"function bindeaRecuperadosServidorNEOption(a) { \n $('#sel-id_servidor-ne').change(function (event) {\n id = $(this).val();\n html = $(this).children(\":selected\").html();\n tabla = 'servidor'\n event.preventDefault();\n bindeaRecuperadosServidor(a);\n\n });\n }",
"function onChange(control, oldValue, newValue, isLoading, isTemplate) {\n if (isLoading || newValue === '') {\n return;\n }\n \n var ga = new GlideAjax('acmeClientScriptUtil');\n ga.addParam('sysparm_name', 'getSupportGrp');\n ga.addParam('syspam_ci_sysid', newValue);\n \n ga.getXML(assignGrp);\n \n function assignGrp(response){\n var answer = JSON.parse(response.responseXML.documentElement.getAttribute(\"answer\"));\n if(answer){\n g_form.setValue('assignment_group', answer.value, answer.displayValue);\n } \n }\n }",
"function bindeaRecuperadosOptionAdmin() { \n $('select[id$=admin]').change(function (event) { \n tabla = $(this).attr('tabla');\n id = $(this).val();\n style = $(this).children('[value='+id+']').attr('style') \n html = $(this).children(\":selected\").html();\n bindeaRecuperadosInputAdmin();\n if (tabla == 'servidor') { \n event.preventDefault(); \n bindeaRecuperadosServidor(''); \n } \n }); \n }",
"function updateSelectedDepartment() {\n\n }",
"function admin_post_edit_load_faculty() {\n // $(\"select[name*='facultyName']\").hide();\n get_faculty(faculty_selector_vars.univCode, function (response) {\n\n var stored_faculty = faculty_selector_vars.facultyName;\n var obj = JSON.parse(response);\n var len = obj.length;\n var $facultyValues = '';\n\n $(\"select[name*='facultyName']\").fadeIn();\n for (i = 0; i < len; i++) {\n var myfaculty = obj[i];\n if (myfaculty.faculty_name == stored_faculty) {\n var selected = ' selected=\"selected\"';\n } else {\n var selected = false;\n }\n $facultyValues += '<option value=\"' + myfaculty.faculty_name + '\"' + selected + '>' + myfaculty.faculty_name + '</option>';\n }\n $(\"select[name*='facultyName']\").append($facultyValues);\n\n });\n }",
"function getTier1Link(selectedClient, selectedProvider, isAdd, selectedTier1) {\n $.ajax({\n url: '/get-Tier1Link',\n method: 'post',\n timeout: 20000,\n data: {\n _token: $('#token').val(),\n client_id: selectedClient,\n provider_id: selectedProvider\n },\n success: function (response){\n\n //Begin process response\n if(response.success == true){\n \n var tier1_link = response.data.tier1_link;\n \n $('#tier1Link').empty();\n $('#tier1LinkEdit').empty();\n \n for($i=0; $i< tier1_link.length; $i++){ \n\n rowTemplate = '<option>{tier1_link[$i]}</option>';\n rowTemplate = rowTemplate.replace('{tier1_link[$i]}', tier1_link[$i]);\n\n if(isAdd) \n $('#tier1Link').append(rowTemplate); \n else\n $('#tier1LinkEdit').append(rowTemplate);\n \n }\n\n if(isAdd) {\n\n rowTemplate = '<option selected disabled hidden>Select Tier1Link</option>';\n $('#tier1Link').append(rowTemplate);\n\n } else {\n\n if (selectedTier1 != '')\n $(\"#tier1LinkEdit\").val(selectedTier1);\n else {\n\n rowTemplate = '<option selected disabled hidden>Select Tier1Link</option>';\n $('#tier1LinkEdit').append(rowTemplate);\n\n }\n\n }\n\n $(\"#tier1LinkEdit\").prop(\"disabled\", false);\n\n }else if (response.success == false) {\n\n if (response.data.action == 'reloadPage') {\n \n window.showCSRFModal();\n return false;\n \n }\n }\n }\n })\n }",
"function selectEventFormAutoChange() {\n\n var object = $(\"#eventFormSelect\");\n var value = object[0].value;\n var ajaxURL = \"../myPHP/classHandler.php?c=EmaileratorEvent&a=Read&MultiSelect=true&field=id&id=\" + value;\n var parentForm = $(\"#eventForm\");\n\n if (value == \"new\") {\n resetEventForm();\n }\n else { \n updateFormFromSelectAjax(ajaxURL, \"#eventForm\");\n updateLogDivAjax(\"#eventLogDiv\", \"EventID\", value);\n updateLogDivAjax(\"#generalLogDiv\");\n parentForm.find(\"#GoButton\").html(\"Update\");\n parentForm.find(\"#DeleteButton\").css(\"visibility\", \"visible\");\n }\n\n}",
"function editProductsRegistration(ajaxUrl) {\n\n\t$(\"#loaderWrap\").show();\n\n\tvar tenderRefNo = $(\"#tenderReferenceNumber\").val();\n\n\tvar schedularJson = [];\n\t$(\".product-registration-wrapper .list-product\")\n\t\t\t.each(\n\t\t\t\t\tfunction() {\n\t\t\t\t\t\titemsArray = [];\n\t\t\t\t\t\t$(this)\n\t\t\t\t\t\t\t\t.find(\n\t\t\t\t\t\t\t\t\t\t\".tenderRootDiv .tenderItemTable .tbl_posts_body tr\")\n\t\t\t\t\t\t\t\t.each(\n\t\t\t\t\t\t\t\t\t\tfunction() {\n\n\t\t\t\t\t\t\t\t\t\t\titemsArray\n\t\t\t\t\t\t\t\t\t\t\t\t\t.push({\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tgdfGenericCode : $(this)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.find(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"#gdfGenCode\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.val(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tlistOfCountries : $(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tthis)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.find(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"#listOfCountries\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.val(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tfppRegStatus : $(this)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.find(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"#fppRegStatus\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.val(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tfppRegId : $(this)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.find(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"#fppRegId\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.val(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\ttenderReferenceNumber : $(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tthis)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.find(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"#tenderReferenceNumber\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.val(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tfppRegAcceptedStatus : $(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tthis)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.find(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"#fppRegAcceptedStatus\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.val(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\ttenderFPPRegRefNumber : $(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tthis)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.find(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"#tenderFPPRegRefNumber\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.val(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tgdfTenderItemMatRefID : $(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tthis)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.find(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"#gdfTenderItemMatRefID\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.val(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\ttenderItemNumber : $(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tthis).find(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"#tendItem\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.val(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t// countryNames :\n\t\t\t\t\t\t\t\t\t\t\t\t\t// $(this).find(\"#countryNames\").val(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t})\n\n\t\t\t\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\tschedularJson.push({\n\t\t\t\t\t\t\tschduleNumber : $(this).find(\"#schedNum\").text(),\n\t\t\t\t\t\t\ttenderItems : itemsArray\n\t\t\t\t\t\t});\n\n\t\t\t\t\t});\n\n\t// alert(\":::schedularJson:::\" + schedularJson);\n\tvar jsonInput = {\n\t\ttenderRefNo : tenderRefNo,\n\t\tselectedPrdRegArr : schedularJson\n\t};\n\n\t// alert(\":::jsonInput:::\" + jsonInput);\n\tvar url = ajaxUrl;\n\n\tvar data = {\n\t\t\"requestData\" : JSON.stringify(jsonInput)\n\t};\n\n\tjQuery.post(url, data, function(data) {\n\n\t\tvar response = JSON.stringify(eval(\"(\" + data + \")\"));\n\t\t// alert(\":::response:::\" + response);\n\t\tvar json = JSON.parse(response);\n\t\t// alert(\":::json:::\" + json);\n\n\t\t$('.adhocinfo').empty()\n\t\t$('.adhocinfo').append(html);\n\n\t});\n\n\t// $('.nextBtnTab1').attr(\"disabled\", false);\n\t// disableToolTip();\n\tsetTimeout(function() {\n\t\t$(\"#loaderWrap\").hide();\n\t}, 2000);\n}",
"function getProveedor(selectedId = 0){\n $.ajax({\n url: API_PRODUCTOS + 'getProveedor',\n type: 'post',\n dataType: 'json',\n success: function (response) {\n let jsonResponse = response.dataset;\n //Si no se le ha ingresado un valor a selectedId, se ingresa la opcion deshabilitada para seleccionar al proveedor;\n //si no, se deja vacío (para el Create)\n let dropDown = selectedId == 0 ? `<option value=\"\" disabled selected>Selecciona el proveedor</option>` : '';\n jsonResponse.forEach(proovider => {\n //verificamos si el id que esta pasando ahorita es el mismo que el recibido, para aplicarle el proveedor seleccionado\n let estado = ((proovider.id_proveedor == selectedId) ? ' selected' : '');\n dropDown += `\n <option value=\"${proovider.id_proveedor}\"${estado}>${proovider.nombre_prov}</option>\n `;\n });\n //ingresamos las opciones al select\n $('#nombre_prov').html(dropDown);\n //inicializamos el select con materializecss\n $('#nombre_prov').formSelect();\n },\n error: function (jqXHR) {\n // Se verifica si la API ha respondido para mostrar la respuesta, de lo contrario se presenta el estado de la petición.\n if (jqXHR.status == 200) {\n console.log(jqXHR.responseText);\n } else {\n console.log(jqXHR.status + ' ' + jqXHR.statusText);\n }\n }\n });\n}",
"function oppdaterSelect(tx, res, selId) {\r\n var rec, i;\r\n /*\r\n * Løp gjennom resultatene og legg til elementer til dropdown\r\n */\r\n for ( i = 0; i < res.rows.length; i++) {\r\n rec = res.rows.item(i);\r\n $(selId).append($(\"<option />\").val(rec.id).text(rec.navn));\r\n };\r\n /*\r\n * Sett fokus på første element (index 0 er første) og oppdater skjerm\r\n */\r\n $(selId).prop('selectedIndex', 0).selectmenu('refresh');\r\n}",
"function hotelfilldropdown() {\n var name = $('#ddlCustomers :selected').text();\n $.ajax({\n type: \"POST\",\n url: \"../trns/hotelfilldropdown?name=\" + name,\n data: {},\n contentType: \"application/json; charset=utf-8\",\n dataType: \"json\",\n success: function (response) {\n //$scope.hoteldetailsfill = response.data[\"hoteldetails\"];\n $('#txtcode').val(response.hoteldetails[0].HotelCode);\n $('#txthname').val(response.hoteldetails[0].HotelName);\n $('#txthaddress').val(response.hoteldetails[0].Address);\n $('#txthphone').val(response.hoteldetails[0].Phone);\n $('#txthemail').val(response.hoteldetails[0].PrimaryEmail);\n $('#txtotheremail').val(response.hoteldetails[0].SecondaryEmail);\n var pricecount = response.pricedetails.length;\n if (pricecount == '1') {\n $('#mealpricediv1').show();\n $('#mealpricediv2').hide();\n $('#mealpricediv3').hide();\n $(\"#singlemealprice\").text(response.pricedetails[0].SinglePrice);\n $(\"#doublemealprice\").text(response.pricedetails[0].DoublePrice);\n if (response.pricedetails[0].TCId == \"1\") {\n $(\"#mealtype\").text(\"APAI\");\n } else if (response.pricedetails[0].TCId == \"2\") {\n $(\"#mealtype\").text(\"MAP\");\n } else {\n $(\"#mealtype\").text(\"CPAI\");\n }\n $('#txthCurrency1').text(response.pricedetails[0].HotelCurrencyCode == null ? 'INR' : response.pricedetails[0].HotelCurrencyCode);\n } else if (pricecount == '2') {\n $('#mealpricediv1').show();\n $('#mealpricediv2').show();\n $('#mealpricediv3').hide();\n $(\"#singlemealprice\").text(response.pricedetails[0].SinglePrice);\n $(\"#doublemealprice\").text(response.pricedetails[0].DoublePrice);\n if (response.pricedetails[0].TCId == \"1\") {\n $(\"#mealtype\").text(\"APAI\");\n } else if (response.pricedetails[0].TCId == \"2\") {\n $(\"#mealtype\").text(\"MAP\");\n } else if (response.pricedetails[0].TCId == \"3\") {\n $(\"#mealtype\").text(\"CPAI\");\n }\n $('#txthCurrency1').text(response.pricedetails[0].HotelCurrencyCode == null ? 'INR' : response.pricedetails[0].HotelCurrencyCode);\n $(\"#singlemealprice2\").text(response.pricedetails[1].SinglePrice);\n $(\"#doublemealprice2\").text(response.pricedetails[1].DoublePrice);\n if (response.pricedetails[1].TCId == \"1\") {\n $(\"#mealtype2\").text(\"APAI\");\n } else if (response.pricedetails[1].TCId == \"2\") {\n $(\"#mealtype2\").text(\"MAP\");\n } else if (response.pricedetails[1].TCId == \"3\") {\n $(\"#mealtype2\").text(\"CPAI\");\n }\n $('#txthCurrency2').text(response.pricedetails[1].HotelCurrencyCode == null ? 'INR' : response.pricedetails[1].HotelCurrencyCode);\n } else if (pricecount == '3') {\n $('#mealpricediv1').show();\n $('#mealpricediv2').show();\n $('#mealpricediv3').show();\n $(\"#singlemealprice\").text(response.pricedetails[0].SinglePrice);\n $(\"#doublemealprice\").text(response.pricedetails[0].DoublePrice);\n if (response.pricedetails[0].TCId == \"1\") {\n $(\"#mealtype\").text(\"APAI\");\n } else if (response.pricedetails[0].TCId == \"2\") {\n $(\"#mealtype\").text(\"MAP\");\n } else if (response.pricedetails[0].TCId == \"3\") {\n $(\"#mealtype\").text(\"CPAI\");\n }\n $('#txthCurrency1').text(response.pricedetails[0].HotelCurrencyCode == null ? 'INR' : response.pricedetails[0].HotelCurrencyCode);\n $(\"#singlemealprice2\").text(response.pricedetails[1].SinglePrice);\n $(\"#doublemealprice2\").text(response.pricedetails[1].DoublePrice);\n if (response.pricedetails[1].TCId == \"1\") {\n $(\"#mealtype2\").text(\"APAI\");\n } else if (response.pricedetails[1].TCId == \"2\") {\n $(\"#mealtype2\").text(\"MAP\");\n } else if (response.pricedetails[1].TCId == \"3\") {\n $(\"#mealtype2\").text(\"CPAI\");\n }\n $('#txthCurrency2').text(response.pricedetails[1].HotelCurrencyCode == null ? 'INR' : response.pricedetails[1].HotelCurrencyCode);\n\n $(\"#singlemealprice3\").text(response.pricedetails[2].SinglePrice);\n $(\"#doublemealprice3\").text(response.pricedetails[2].DoublePrice);\n if (response.pricedetails[2].TCId == \"1\") {\n $(\"#mealtype3\").text(\"APAI\");\n } else if (response.pricedetails[2].TCId == \"2\") {\n $(\"#mealtype3\").text(\"MAP\");\n } else if (response.pricedetails[2].TCId == \"3\") {\n $(\"#mealtype3\").text(\"CPAI\");\n }\n $('#txthCurrency3').text(response.pricedetails[2].HotelCurrencyCode == null ? 'INR' : response.pricedetails[2].HotelCurrencyCode);\n }\n }\n });\n}",
"function bindSelectedToForm() {\n saveKPForm.find('#kp-id').val(selected.id);\n saveKPForm.find('#kp-number').val(selected.number);\n saveKPForm.find('#kp-name').val(selected.title);\n kpLevelList.val(selected.kLevel).trigger('change');\n saveKPForm.find('#kp-score').val(selected.score);\n saveKPForm.find('#kp-syllabus').text(syllabus.level + ' ' + syllabus.version);\n saveKPForm.find('#kp-chapter').text(chapter.title);\n\n }",
"function displayCorrectYVItem(aSelect, jCode) {\r\n var value = aSelect.value;\r\n var url = '/action/showCoverGallery?journalCode=' + jCode + '&ajax=true&year=' + value;\r\n var parentNode = $('parentYearVolumeSelect');\r\n var width = Element.getWidth('cenVolumes');\r\n Element.remove('cenVolumes');\r\n parentNode.insert('<select id=\"cenVolumes\" name=\"year\"><option value=\"\">Loading...</option></select>');\r\n $('cenVolumes').style.width = width + \"px\";\r\n new Ajax.Request(url, {\r\n method: 'get',\r\n onSuccess: function(transport) {\r\n var jsonData = transport.responseText.evalJSON();\r\n if(jsonData != '') {\r\n //set correct labels in year/volume select\r\n var labels = jsonData.labels;\r\n var orderedKeys = jsonData.orderedKeys;\r\n if(labels != '' && orderedKeys){\r\n Element.remove('cenVolumes');\r\n //start building year/volume select with new values\r\n var resultText = \"<select id='cenVolumes' name='year'>\";\r\n for(var i = 0; i < orderedKeys.length; i++) {\r\n var currKey = orderedKeys[i];\r\n var selected = (i == orderedKeys.length -1);\r\n resultText += \"<option value='\" + currKey + \"'\" + (selected ? \" selected\" : \"\") + \">\" + labels[currKey] + \"</option>\";\r\n }\r\n resultText += \"</select>\";\r\n parentNode.insert(resultText);\r\n }\r\n }\r\n }\r\n });\r\n}",
"function FillGenresCallBack(data) \n{\n \n FillDropDowns(\"Genre\", data);\n}",
"function update_form_data(res) {\n $(\"#wl_id\").val(res.id); \n $(\"#wl_name\").val(res.name);\n $(\"#wl_category\").val(res.category);\n }",
"function modifUnidad(unid,asig){\r\n\tdocument.getElementById('unid_tem').value=unid;\r\n\tdocument.getElementById('titulo').innerHTML=\"MODIFICAR TEMA\";\r\n\tdocument.getElementById('boton_temas').innerHTML=\"Modificar\";\r\n\tdocument.forms.agregarTema.action=\"comunicaciones/modifTema.php\";\r\n\tdocument.getElementById('unid_viejo').value=unid;\r\n\tdocument.getElementById('boton').value=\"Modificar\";\r\n\tdocument.getElementById(asig).selected=true;\r\n}",
"function f_GUI_Update_Select(frame, he_select){\n\t// Check that the 'he_select' is found and correct\n\tif (he_select != null)\n\t{\n\t\t// Update GUI elements concerned \n\t\the_select.html(''); // Clear the content of the select\n\t\t\n\t\t// Determine what to inspect in frame\n\t\tvar whatToInspect;\n\t\tswitch(frame.AppID){\n\t\t\tcase APP_ID.LIST:\n\t\t\t\twhatToInspect = frame.RADOME_Cmds;\n\t\t\t\tbreak;\n\t\t\tcase APP_ID.AUDIO:\n\t\t\t\twhatToInspect = frame.RADOME_AudioFiles;\n\t\t\t\tbreak;\t\t\t\t\n\t\t\tdefault :\n\t\t\t\twhatToInspect = frame.RADOME_Cmds;\n\t\t\t\tbreak;\n\t\t}\n\t\t\n\t\t// Iterate over the data and append a select option\n\t\t$.each(whatToInspect, function(key, val){\n\t\t\t// Append option element to the select\n\t\t\the_select.append('<option value=\"' + val.id + '\">' + val.name + '</option>');\n\t\t\tif (frame.AppID == APP_ID.AUDIO)\n\t\t\t{\n\t\t\t\t// Update structure array concerned\n\t\t\t\tgRADOME_Conf.AudioTitle.push(val.name);\n\t\t\t\tgRADOME_Conf.AudioPath.push(gScope.RADOMEAudioPath + val.name);\n\t\t\t\tgRADOME_Conf.AudioDescription.push(\"Description de \"+val.name);\n\t\t\t}\n\t\t})\t\n\n\t\t// Refresh element\n\t\the_select.selectpicker('refresh');\n\t}\n\telse\n\t{\n\t\tf_RADOME_log(\"error in 'f_GUI_Update_Select' function : he_select is undefined\");\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This private function will add an icon to the message Parameters alertObject:the alert object customMessage: (optional) message of the alert. If not passed will use default alertObject.message | function messageWithIcon(alertObject,customMessage){
var message = "<img alt='"+alertObject.type+": ' src='"+icons_url+alertObject.type+".png' />";
if(customMessage !== undefined)
message += customMessage; //use custom message
else
message += alertObject.message; //use default alert message
return message;
} | [
"function alertMessageAdd() {\n\t\t\talert.css('display', 'block');\n\t\t}",
"function messageWithHelpLink(alertObject,message){\n\t\treturn \"<a href='\"+ help_url + \"alerts.html\" + alertObject.info +\"' target='_ANDIhelp'>\"\n\t\t\t\t+message\n\t\t\t\t+\" <span class='ANDI508-screenReaderOnly'>, Open Alerts Help</span></a> \";\n\t}",
"function renderDeleteMessage(objectText) {\n closeMessages();\n var div = $('<div>')\n .appendTo('#messages')\n .addClass('alert alert-info alert-dismissable');\n $(\"<button>\").appendTo(div)\n .attr('type', 'button')\n .attr('data-dismiss', 'alert')\n .attr('aria-hidden', 'true')\n .addClass('close')\n .html(\"×\");\n div.append(\"Successfully deleted '\"+objectText+\"'\");\n}",
"function appendIcon(appObject) {\n // Prefer short name, but use long name if short name is not specified\n var name = appObject.shortName;\n if (!name) {\n name = appObject.name;\n }\n var app = new Icon(appObject.id, name, appObject.appLaunchUrl);\n\n if (!appObject.offlineEnabled) {\n $(app).addClass(\"not-offline-enabled\");\n }\n /*\n app.addEventListener(\"click\", function(){\n event.preventDefault();\n chrome.management.launchApp(appObject.id);\n window.close();\n /*\n chrome.tabs.create({\n \"url\": appObject.appLaunchUrl,\n // \"pinned\": appObject.pinned\n }, appLoaded);*/\n // }, false);\n if (appObject.appLaunchUrl.substring(0, 17) == \"chrome://settings\") {\n app.addEventListener(\"click\", function() {\n chrome.tabs.update({url: \"chrome://settings\"});\n }, false);\n } else if (appObject.type == appTypes.packagedApp ||\n appObject.type == appTypes.legacyPackagedApp) {\n app.addEventListener(\"click\", function(){\n event.preventDefault();\n chrome.management.launchApp(appObject.id);\n chrome.tabs.getCurrent(function(tab) {\n chrome.tabs.remove(tab.id);\n });\n }, false);\n } else {\n // Web clip or hosted app\n app.addEventListener(\"click\", function() {\n event.preventDefault();\n chrome.tabs.update({\n url: appObject.appLaunchUrl,\n });\n }, false);\n }\n icons.appendChild(app.parentNode);\n return true;\n}",
"function createIconDialog() {\n iconDialog = new ui.BaseElement({\n type: \"dialog\",\n class: \"mdl-dialog\",\n innerHTML: \"<h5 class=\\\"mdl-color-text--blue-A200\\\">Choose an icon</h5>\",\n }).appendTo(\"body\");\n\n const icons = ui.arrayToElements(\n ui.IconButton,\n codepoints.map(e => ({\n innerHTML: new ui.MaterialIcon({ innerHTML: `${e}` }).element.outerHTML,\n })),\n { textColor: \"blue-A200\" }\n );\n\n icons.forEach((e) => {\n e.appendTo(iconDialog.element).addEventListener(\"click\", (event) => {\n iconDialog.currentTarget.firstChild.innerHTML = `${event.currentTarget.firstChild.innerHTML}`;\n iconDialog.element.close();\n });\n });\n}",
"function createAlert_return(alert, textAlert) {\n var result = \"<div class=\\\"col-md-12\\\"><div class=\\\"alert alert-\" + alert + \"\\\">\"\n + \"<button aria-hidden=\\\"true\\\" data-dismiss=\\\"alert\\\" class=\\\"close\\\" type=\\\"buttonn\\\">×</button><p>\" + textAlert + \"</p></div></div>\";\n return result;\n}",
"function displayNotification(type, messages, selector, insertBefore) {\n\tvar html = '<div class=\"alert alert-'+ type + ' alert-dismissable\">' +\n \t\t\t\t\t'<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">' + \n \t\t\t\t\t\t'×' + \n \t\t\t\t\t'</button>';\n\tfor(var i=0; i<messages.length; i++) {\n\t\thtml += \"<div>\"+messages[i]+'</div>';\n\t}\n\thtml += '</div>';\n\tif(insertBefore) {\n\t\t$(selector).before(html);\n\t} else {\n\t\t$(selector).html(html);\n\t}\n}",
"function AlertButton(label, id, title, clickLogic, overlayIcon){\n\tthis.label = label; //button's innerText\n\tthis.id = id;\t\t//button's id\n\tthis.title = title; //button's initial title attribute\n\tthis.clickLogic = clickLogic; //buttons clicklogic\n\tthis.overlayIcon = overlayIcon; //if button should contain overlayIcon, pass in overlayIcon. else pass in empty string \"\"\n}",
"function populateAlert(obj){\n if (obj instanceof Error){\n alert.innerHTML += obj;\n }\n}",
"function createIconWrapper(i, locationObject) {\n let tempIcon = locationObject.siteIcon;\n let tempName = locationObject.siteName;\n let tempURL = locationObject.url;\n let wrapper = \"\";\n if (tempURL === null) {\n // DISPLAY NONE\n wrapper = `<a href=\"${tempURL}\" class=\"iz-i m-s d-n\">\n <img src=\"${tempIcon}\" alt=\"${tempName}\" title=\"${tempName}\" class=\"br bd-g e-g-hv h-f w-f s-hv d-n\">\n </a>`;\n }\n else {\n wrapper = `<a href=\"${tempURL}\" class=\"iz-i m-s\">\n <img src=\"${tempIcon}\" alt=\"${tempName}\" title=\"${tempName}\" class=\"br bd-g e-g-hv h-f w-f p-s s-hv\">\n </a>`;\n }\n return wrapper;\n }",
"function getMsgAlertContextMenuObject() {\n return ({\n '': {\n title: 'reload this application',\n icon: './images/icon/refresh_16x16.png',\n onclick: function() {\n location.reload();\n }\n }\n });\n }",
"function noti(notiTitle, notiBody, showAlert) {\n if(typeof(Notification) != \"undefined\" && Notification.permission == \"granted\") {\n new Notification(notiTitle, {icon: \"images/roomicon.png\", body: notiBody});\n } else {\n if(showAlert) {\n alert(notiBody);\n }\n }\n}",
"function generateAlertHTML(alert, type) {\n //Construct alert content\n var content;\n if (type === \"sub alert\") content = `<strong>${alert.Name}</strong> ${Resources.IsNowTrending}`\n else if (type === \"user alert\") content = `<strong>${alert.Name}</strong> ${Resources.IsNowAvailable}`\n\n //Construct alert message\n var read = \"\";\n if (alert.IsRead) {\n read = \"alertRead\";\n }\n\n var alertItem = $(\"<li />\",\n {\n \"class\": `alertMessage${alert.AlertId} ${read}`,\n onclick: `markAsRead(${alert.AlertId})`\n });\n\n var alertCloseButton = $(\"<div />\",\n {\n \"class\": \"alertClose\",\n title: Resources.RemoveAlert\n }).append($(\"<a />\",\n {\n \"class\": \"fa fa-close\",\n onclick: `removeAlert(${alert.AlertId})`\n\n }));\n let alertBody = \"\";\n if (type === \"user alert\") {\n alertBody = $(\"<a />\",\n {\n href: `/User/UserWeeklyReview`\n });\n\n } else {\n alertBody = $(\"<a />\",\n {\n href: `/Person/Details/${alert.ItemId}`\n });\n }\n var alertIcon = $(\"<div />\",\n {\n \"class\": \"alertIcon\"\n }).append($(\"<i />\",\n {\n \"class\": \"fa fa-user\"\n }));\n var alertContent = $(\"<span />\",\n {\n \"class\": \"font_16\",\n html: content\n });\n var alertTime = $(\"<span />\",\n {\n \"class\": \"alertTime\",\n html: `<i class=\"font_11 fa fa-clock-o\"></i> ${jQuery.timeago(alert.TimeStamp)}`\n });\n alertBody.append(alertIcon).append(alertContent).append(alertTime);\n alertItem.append(alertCloseButton).append(alertBody);\n return alertItem;\n}",
"function MsgNotify( cMsg, cType, cIcon, lSound ) {\n\n\tcType = ( $.type(cType) == 'string' ) ? cType : 'info';\n\tcIcon = ( $.type( cIcon )== 'string' ) ? cIcon : '';\n\tlSound = ( $.type( lSound )== 'boolean' ) ? lSound : false;\n\t\n//\t$.notify.defaults( { style: 'metro' );\n/*\n\tif ( lSound ) {\n\t\n\t\tswitch ( cType ) {\n\t\t\n\t\t\tcase 'success':\n\t\t\t\tTSound( _( '_sound_success' ) )\n\t\t\t\tbreak;\t\t\n\t\t\n\t\t\tcase 'warn':\n\t\t\t\tTSound( _( '_sound_warn' ) )\n\t\t\t\tbreak;\n\t\t\t\t\n\t\t\tcase 'error':\n\t\t\t\tTSound( _( '_sound_error' ) )\n\t\t\t\tbreak;\t\t\t\t\n\t\t\t\t\n\t\t\tcase 'info':\n\t\t\t\tTSound( _( '_sound_info' ) )\n\t\t\t\tbreak;\t\t\t\t\t\t\t\t\t\n\t\t}\t\t\n\t}\n\t*/\t\t\n\t\n\t//$.notify( { icon: \"images/tweb.png\", message: cMsg }, { type: cType, icon_type: 'image' } );\n\t$.notify( { icon: cIcon, message: cMsg }, { type: cType, icon_type: 'image' } );\n\n}",
"getAlerts() {\n return [\n {\n key: 'applicationUpdated',\n icon: 'cloud download',\n message: (\n <div className={styles['single-line-message']}>\n New application version available\n ({this.renderVersionChange()})\n {this.renderClickToUpgradeLink()}\n </div>\n ),\n isVisible: this.isApplicationUpdatedAlertVisible,\n onDismiss: this.createGenericOnDismiss('applicationUpdated'),\n heightPx: 48,\n severity: 'info',\n },\n ];\n }",
"function usfEventIcon(objDate) {\n\t\tvar eventIcon = document.createElement('div');\n\t\teventIcon.className = 'widget_calIcon';\n\t\t\n\t\tvar eventIconMonth = document.createElement('span');\n\t\teventIconMonth.className = 'widget_calIconMonth';\n\t\teventIconMonth.appendChild(document.createTextNode(objDate.getAbbrMonthName()));\n\t\t\n\t\tvar eventIconDay = document.createElement('span');\n\t\teventIconDay.className = 'widget_calIconDay';\n\t\teventIconDay.appendChild(document.createTextNode(pad(objDate.Day,2)));\n\t\t\n\t\teventIcon.appendChild(eventIconMonth);\n\t\teventIcon.appendChild(eventIconDay);\n\t\treturn eventIcon;\n\t}",
"function alertMessageRemoval() {\n\t\t\talert.css('display', 'none');\n\t\t}",
"function addIcon(position, icons, container, input, internalCreate) {\n // tslint:enable\n let result = typeof (icons) === 'string' ? icons.split(',')\n : icons;\n if (position.toLowerCase() === 'append') {\n for (let icon of result) {\n appendSpan(icon, container, internalCreate);\n }\n }\n else {\n for (let icon of result) {\n prependSpan(icon, container, input, internalCreate);\n }\n }\n }",
"alert( alertId, text ) {\n let alertText = null;\n\n if ( Array.isArray( text ) ) {\n alertText = \"\";\n for ( let part of text ) {\n alertText += part;\n }\n }\n else {\n alertText = text;\n }\n\n this.eventBus.message(\n {\n headers: {\n routing: {\n incoming: \"none\",\n outgoing: \"client\"\n }\n },\n message: {\n aps: {\n type: \"aps-alert\"\n },\n content: {\n targetId: alertId,\n markdown: alertText\n }\n }\n }\n );\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
METHODS TO HANDLE EVENTS mailboxCheck | function mailboxCheck() {
if (lock) {
pending++;
} else {
sendMessage("");
}
} | [
"waitMail(addr) {\n return imap_listener.waitMail(addr);\n }",
"function is_in_guest_list(event, guest){\n var guests = event.getGuestList();\n for (var j=0; j<guests.length; j++) {\n //Logger.log(\"Check guest \"+guests[j].getEmail());\n if(guests[j].getEmail()==guest){\n var answer = guests[j].getGuestStatus();\n //Logger.log(\"Answer of \"+guest+\": \"+answer)\n return answer;\n }\n }\n return false;\n}",
"function load_mailbox(mailbox) {\n globalMailbox = mailbox;\n\n const msg_list = document.createElement('div');\n\n // grab emails\n fetch(`/emails/${mailbox}`)\n .then(response => response.json())\n .then(emails => {\n\n msg_list.innerHTML = '';\n const num_of_emails = emails.length;\n msg_list.appendChild(make_el('p', `${num_of_emails} message${(num_of_emails === 1 ? '' : 's')}`));\n\n if (num_of_emails > 0) {\n for (const email in emails) {\n const email_entry = make_el('div', null, 'btn-outline-primary clickable');\n email_entry.addEventListener('click', () => get_email(emails[email].id));\n if (emails[email].read === true) {\n email_entry.classList.add('read');\n }\n if (mailbox === 'sent') {\n email_entry.appendChild(make_el('span', `To: ${emails[email].recipients}`, 'message-address'));\n } else {\n email_entry.appendChild(make_el('span', `From: ${emails[email].sender}`, 'message-address'));\n }\n email_entry.appendChild(make_el('span', ` ${emails[email].subject}`));\n email_entry.appendChild(make_el('span', ` ${emails[email].timestamp}`, 'last'));\n\n msg_list.appendChild(email_entry);\n\n }\n }\n\n })\n\n // Show the mailbox and hide other views\n switch_view('#emails-view');\n\n // Show the mailbox name\n document.querySelector('#emails-view').innerHTML = `<h3>${mailbox.charAt(0).toUpperCase() + mailbox.slice(1)}</h3>`;\n\n document.querySelector('#emails-view').appendChild(msg_list);\n}",
"function processInboxCheckPayments(){\n try{\n getScriptLock();\n init();\n writeLog({operation: 'processInboxCheckPayments'});\n initLists();\n _processInbox();\n _checkPayments();\n writeLog({end: true});\n }\n catch(e){\n log.errors.push(arguments.callee.name + ' failed: ' + err2str(e));\n writeLog({end: true});\n }\n finally{\n if (constants.lock) constants.lock.releaseLock();\n }\n}",
"function checkForInviteBox() {\r\n\t\t// Get container of invite dialog.\r\n\t\tvar inviteBoxCheck = document.getElementsByClassName('eventInviteLayout')[0] || document.getElementsByClassName('standardLayout')[0] ||\r\n\t\t\tdocument.getElementById('fb_multi_friend_selector_wrapper');\r\n\t\t\r\n\t\t// Check for match of inviteBoxCheck, and the TBODY that is later used as an insertion anchor.\r\n\t\tif (inviteBoxCheck && inviteBoxCheck.getElementsByTagName('tbody')[0]) {\r\n\t\t\t// Add the button.\r\n\t\t\taddButton(inviteBoxCheck);\r\n\t\t\t\r\n\t\t\t// Can not be used at the moment. I have not found a way to re-apply the event handler.\r\n\t\t\t/* Remove node insertion watcher (it's strange, but it needs to be delayed a ms)\r\n\t\t\twindow.setTimeout(function () {\r\n\t\t\t\twindow.removeEventListener('DOMNodeInserted', checkForInviteBox, false);\r\n\t\t\t }, 1);\r\n\t\t\t*/\r\n\t\t}\r\n\t}",
"function findWebGLEvents(modelHelper, mailboxEvents, animationEvents) {\n for (var event of modelHelper.model.getDescendantEvents()) {\n if (event.title === 'DrawingBuffer::prepareMailbox')\n mailboxEvents.push(event);\n else if (event.title === 'PageAnimator::serviceScriptedAnimations')\n animationEvents.push(event);\n }\n }",
"async listen() {\n const contract = await this.getContract();\n contract.on('Claimed', async (vendor, phone, amount) => {\n try {\n const otp = Math.floor(1000 + Math.random() * 9000);\n const data = await this.setHashToChain(contract, vendor, phone.toString(), otp.toString());\n\n const message = `A vendor is requesting ${amount} token from your account. If you agree, please provide this OTP to vendor: ${otp}`;\n // eslint-disable-next-line global-require\n const sms = require(`./plugins/sms/${config.get('plugins.sms.service')}`);\n\n // call SMS function from plugins to send SMS to beneficiary\n sms(phone.toString(), message);\n } catch (e) {\n console.log(e);\n }\n });\n console.log('--- Listening to Blockchain Events ----');\n }",
"function checkIfEvent(redditData, db, r) {\n if (redditData.title.toLowerCase().includes(eventMentioned)) {\n sendModMailAlert(redditData, db, r);\n replyToEventHost(redditData);\n r.getSubmission(redditData.name).remove({\n spam: true\n }).then(function (error) {\n console.log(error);\n });\n } else {\n db.run(\"INSERT INTO redditPost (name, processed) VALUES ('\" + redditData.name + \"', '1')\");\n }\n}",
"function facebookWebhookListener(req, res) {\n\tconsole.log(\"Got ICM\");\n\tif (!req.body || !req.body.entry[0] || !req.body.entry[0].messaging) return console.error(\"no entries on received body\");\n\tlet messaging_events = req.body.entry[0].messaging;\n\tfor (let messagingItem of messaging_events) {\n\t\tlet user_id = messagingItem.sender.id;\n\t\tdb_utils.getUserById(user_id, messagingItem, parseIncomingMSGSession);\n\t}\n\tres.sendStatus(200);\n}",
"onMailViewChanged() {\n // only do this if we're currently active. no need to queue it because we\n // always update the mail view whenever we are made active.\n if (this.active) {\n // you cannot cancel a view change!\n window.dispatchEvent(\n new Event(\"MailViewChanged\", { bubbles: false, cancelable: false })\n );\n }\n }",
"function confirmationSelectionHandler(){\n const header = SheetsLibrary.getHeaderAsObjFromSheet(ActiveSheet, 1);\n const allEvents = SheetsLibrary.getAllRowsAsObjInArr(ActiveSheet, 1);\n const events = SheetsLibrary.getSelectedRowsAsObjInArr(ActiveSheet, 1);\n const selectedEvent = events[0];\n console.log(selectedEvent);\n if( !isReady() ) return\n\n try {\n // Update Jour Fixe Calendar Event\n const jourFixeCal = CAL.getCalendarById(officeHourId);\n const eventInCal = jourFixeCal.getEventById(selectedEvent.id);\n const newTitleForEvent = \"Jour Fixe | \" + selectedEvent.user;\n const start = eventInCal.getStartTime();\n const end = eventInCal.getEndTime();\n \n let calDescription = getSFLinkFromEmail(selectedEvent.Email) ? `Hier ist der Link zu deinen Botschafter-Kampagnen: ` + getSFLinkFromEmail(selectedEvent.Email) : \"\"; \n \n // Create Calendar Event in personal Call\n const myCal = CAL.getCalendarById(myCalId);\n const newCalEvent = myCal.createEvent( newTitleForEvent, start, end);\n eventInCal.setTitle( newTitleForEvent );\n\n if( newCalEvent ){\n // Add the Meet Link to the Description\n // Need to either get the Meet Link, if it is there, or create a Meeting using the Advanced Calendar API\n const meetLink = getMeetLink(newCalEvent.getId()); //Calendar.Events.get(myCalId, newCalEvent.getId());\n if( meetLink )\n calDescription += `\\nHier ist der Link zum Gespräch: ${meetLink}`;\n newCalEvent.setDescription( calDescription );\n eventInCal.setDescription( calDescription );\n \n updateField( selectedEvent.rowNum, header.status, newCalEvent.getId() );\n disableOtherEventsFromThisSubmission(); \n newCalEvent.addGuest( selectedEvent.Email );\n sendConfirmationToBotschafter( {\n email: selectedEvent.Email,\n subject: `Bestätigung Jour-Fixe am ${selectedEvent.Datum}`,\n body: `Hi ${selectedEvent.user},\\nhiermit bestätige ich deinen Jour-Fixe-Termin am ${selectedEvent.Datum} um ${selectedEvent.Uhrzeit}.\\nLiebe Grüße,\\nShari`\n });\n }\n } catch(err) {\n console.error(\"Fehler: \"+err);\n alert(\"Could not create Event: \"+err.message);\n }\n\n // Disable other events from the same submission \n function disableOtherEventsFromThisSubmission( ){\n const eventsFromThisSubmission = allEvents.filter( event => event.submissionId === selectedEvent.submissionId && event.id != selectedEvent.id ) ;\n eventsFromThisSubmission.forEach( event => updateField( event.rowNum, header.status, \"disabled\") );\n }\n \n // Checks to see if event selected is empty and not disabled\n function isReady(){\n if( events.length > 1 ){\n alert(\"Bitte nur eine auswählen\");\n return\n }\n \n if( selectedEvent.status === \"disabled\" ){\n alert(\"Eintrag ist disabled und kann nicht erstellt werden\");\n return\n }\n \n if( selectedEvent.status != \"\" ){\n alert(\"Eintrag hat bereits einen Status und kann deshalb nicht neu erstellt werden.\");\n return\n }\n \n return true\n }\n}",
"function doCheckJobsProcess ()\n{\n if (!parseJobsReq.registeredJobs.length) {\n /* If there is no registered jobs, do not subscribe for jobs events */\n return;\n }\n\tjobsApi.jobs.on('job complete', function (id) {\n\t\tlogutils.logger.info(\"We are on jobs.on for event 'job complete', id:\" + id);\n\t\tjobsApi.kue.Job.get(id, function (err, job) {\n\t\t\tif ((err) || (null == job)) {\n\t\t\t\tlogutils.logger.error(\"Some error happened or job is null: \" +\n\t\t\t\t\terr + \" processID: \" + process.pid);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tlogutils.logger.debug(\"Job \" + job.id + \" completed by process: \" + process.pid);\n\t\t\tcheckAndRequeueJobs(job);\n\t\t});\n\t});\n}",
"function email_check() {\r\n email_warn(email_validate());\r\n final_validate();\r\n}",
"function onMessageReceived(e) {\n var data = JSON.parse(e.data);\n\n switch (data.event) {\n case 'ready':\n onReady();\n break;\n\n case 'playProgress':\n onPlayProgress(data.data);\n break;\n\n case 'pause':\n onPause();\n break;\n\n case 'finish':\n onFinish();\n break;\n }\n }",
"onRetrievingUnreadEmails() {\r\n this._update('Retrieving emails...');\r\n }",
"function load_mailbox(mailbox) {\n //Clear the id div\n document.querySelector('#email-content').innerHTML = \"\"\n\n // Show the mailbox and hide other views\n document.querySelector('#emails-view').style.display = 'block';\n document.querySelector('#compose-view').style.display = 'none';\n\n // Show the mailbox name\n document.querySelector('#emails-view').innerHTML = `<h3>${mailbox.charAt(0).toUpperCase() + mailbox.slice(1)}</h3>`;\n\n // Load Emails\n load_emails(mailbox);\n}",
"function handleMsg (eventHandlers, msg) {\n var e;\n for (e in msg) {\n if (msg.hasOwnProperty(e)) { \n\thandle(eventHandlers, e, msg[e]);\n }\n }\n }",
"function onMessage(evt) {\n let obj = JSON.parse(evt.data);\n if(obj.isMsg == true) {\n chatMsg(obj);\n } else {\n updateUsersList(obj);\n }\n}",
"readEvents(checkSemaphore) {\n let fromBlock = this.lastReadBlock;\n let toBlock = fromBlock + 10000;\n if (toBlock > this.highestBlock) {\n toBlock = this.highestBlock;\n }\n if (!checkSemaphore) {\n if (this.readingEvents === true) {\n return;\n }\n this.readingEvents = true;\n }\n logger.info(\n \"Reading block-range %d -> %d (%d remaining)\",\n fromBlock,\n toBlock,\n this.highestBlock - fromBlock\n );\n this.contract.getPastEvents(\n \"PeepethEvent\",\n {\n fromBlock: fromBlock,\n toBlock: toBlock\n },\n (error, events) => {\n events.map(this.parseEvent.bind(this));\n logger.info(\"done..\");\n this.lastReadBlock = toBlock;\n if (this.highestBlock > toBlock) {\n this.readEvents(true);\n } else {\n logger.info(\n \"fromBlock %d - lastReadBlock %d - highestBlock %d\",\n fromBlock,\n this.lastReadBlock,\n this.highestBlock\n );\n logger.info(\"event reader going to sleep\");\n this.dumpUsers();\n this.readingEvents = false;\n }\n }\n );\n }",
"function receiveCallback(data) {\n receiveWhois(session,data);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
MAG_InputVerifcode ========= MAG_get_sel_auth_index ================ | function MAG_get_sel_auth_index() { // PR2023-02-03
//console.log("=== MAG_get_sel_auth =====") ;
let sel_auth_index = null;
// --- get list of auth_index of requsr
const requsr_auth_list = [];
if (permit_dict.usergroup_list.includes("auth1")){
requsr_auth_list.push(1)
};
if (permit_dict.usergroup_list.includes("auth2")){
requsr_auth_list.push(2)
};
//console.log(" requsr_auth_list", requsr_auth_list) ;
// get selected auth_index (user can be chairperson / secretary and examiner at the same time)
if (requsr_auth_list.length) {
if (requsr_auth_list.includes(setting_dict.sel_auth_index)) {
sel_auth_index = setting_dict.sel_auth_index;
} else {
sel_auth_index = requsr_auth_list[0];
setting_dict.sel_auth_index = sel_auth_index;
};
};
mod_MAG_dict.requsr_auth_list = requsr_auth_list;
mod_MAG_dict.auth_index = sel_auth_index;
//console.log(" >> mod_MAG_dict.requsr_auth_list", mod_MAG_dict.requsr_auth_list) ;
//console.log(" >> mod_MAG_dict.auth_index", mod_MAG_dict.auth_index) ;
} | [
"function MASE_UploadAuthIndex (el_select) {\n //console.log(\"=== MASE_UploadAuthIndex =====\") ;\n\n// --- put new auth_index in mod_MASE_dict and setting_dict\n mod_MASE_dict.auth_index = (Number(el_select.value)) ? Number(el_select.value) : null;\n setting_dict.sel_auth_index = mod_MASE_dict.auth_index;\n setting_dict.sel_auth_function = b_get_function_of_auth_index(loc, mod_MASE_dict.auth_index);\n //console.log( \"setting_dict.sel_auth_function: \", setting_dict.sel_auth_function);\n\n// --- upload new setting\n const upload_dict = {selected_pk: {sel_auth_index: setting_dict.sel_auth_index}};\n b_UploadSettings (upload_dict, urls.url_usersetting_upload);\n\n }",
"function MAG_fill_select_authindex () { // PR2023-02-06\n //console.log(\"----- MAG_fill_select_authindex -----\") ;\n //console.log(\" mod_MAG_dict.examperiod\", mod_MAG_dict.examperiod);\n //console.log(\" mod_MAG_dict.requsr_auth_list\", mod_MAG_dict.requsr_auth_list);\n\n // --- fill selectbox auth_index\n if (el_MAG_auth_index){\n // auth_list = [{value: 1, caption: 'Chairperson'}, {value: 3, caption: 'Examiner'} )\n const auth_list = [];\n const cpt_list = [null, loc.Chairperson, loc.Secretary, loc.Examiner, loc.Corrector];\n for (let i = 0, auth_index; auth_index = mod_MAG_dict.requsr_auth_list[i]; i++) {\n auth_list.push({value: auth_index, caption: cpt_list[auth_index]});\n };\n t_FillOptionsFromList(el_MAG_auth_index, auth_list, \"value\", \"caption\",\n loc.Select_function, loc.No_functions_found, setting_dict.sel_auth_index);\n//console.log(\" >>>>>>>>>>>>>>>> auth_list\", auth_list)\nconst is_disabled = (!auth_list || auth_list.length <= 1);\n//console.log(\" >>>>>>>>>>>>>>>> is_disabled\", is_disabled)\n el_MAG_auth_index.readOnly = (!auth_list || auth_list.length <= 1);\n };\n }",
"function GetKeyIndex(imgui_key) {\r\n return bind.GetKeyIndex(imgui_key);\r\n }",
"async function getIndices(api, vals, validators) {\n let authIndices = [];\n for (const [index, validator] of validators.entries()){\n if (vals.includes(validator.toString())) {\n authIndices.push(index)\n console.log(index, validator.toString());\n }\n }\n return authIndices\n}",
"function findIndexInDidArrayMatchingSelection() {\t\n\t\tvar i=0;\n\t\twhile(i<detailIdJson.did_array.length) {\n\t\t\tif(detailIdJson.did_array[i].color==self.color() &&\n\t\t\t detailIdJson.did_array[i].size ==self.size() &&\n\t\t\t detailIdJson.did_array[i].sex ==self.sex() )\n\t\t\t\tbreak;\n\t\t\ti++;\n\t\t}\n\t\tif(i==detailIdJson.did_array.length)\n\t\t{\n\t\t\treturn -1;\n\t\t} else {\n\t\t\treturn i;\n\t\t}\t\n\t}",
"visitOid_index_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"findBoxArrayIndex(box){\n var arrayIndex;\n for (var i=0; i < this.state.boxes.length; i++) {\n if (this.state.boxes[i].boxIndex === box.boxIndex) {\n arrayIndex = i;\n break;\n }\n }\n\n return arrayIndex;\n }",
"getUserIndex(){\n var i;\n\n // For each user, check if UUID matches id in the usersPlaying array\n for (i = 0; i < this.props.usersPlaying.length; i++) {\n if(this.props.usersPlaying[i] == this.props.pubnubDemo.getUUID()) {\n return i;\n break;\n }\n }\n return -1;\n }",
"function getListIndex()\n{\n\tvar prmstr = window.location.search.substr(1);\n\tvar prmarr = prmstr.split (\"&\");\n\tvar params = {};\n\n\tfor ( var i = 0; i < prmarr.length; i++) {\n\t var tmparr = prmarr[i].split(\"=\");\n\t params[tmparr[0]] = tmparr[1];\n\t}\n\tlistIndex = params.listindex;\n}",
"get index() {\n\n // Check if the face is bound to a mesh and if not throw an error\n if (!this.mesh) throw new Error(`Cannot compute the index - the face is not bound to a Mesh`);\n\n // Return the index of the face in the faces\n return Number(this.mesh.faces.findIndex(face => face.equals(this)));\n }",
"function promptengine_findOptionInList(selectObj, optionValue)\r\n{\t\r\n if (selectObj == null || optionValue == null || optionValue == \"\")\r\n return -1;\r\n\t\r\n for (var i = 0; i < selectObj.options.length; i++)\r\n {\r\n if (selectObj.options[i].value == optionValue)\r\n return i;\r\n }\r\n\r\n return -1;\t\r\n}",
"function getAuthorizationCode() {\n const UUID = uuidv4();\n const REDIRECT_URL = 'https://'+chrome.runtime.id+'.chromiumapp.org';\n const OAUTH_URL = 'https://app.intercom.io/a/oauth/connect?client_id='+CLIENT_ID+'&state='+UUID+'&redirect_uri='+REDIRECT_URL;\n console.log('opening OAuth window');\n chrome.identity.launchWebAuthFlow({\n url: OAUTH_URL,\n interactive: true\n }, function(responseURL) {\n if (responseURL) {\n // Parsing response for authorization code and state\n let responseParams = responseURL.substring(responseURL.indexOf('?')+1);\n responseParams = responseParams.split('&');\n let params = {};\n for ( i = 0, l = responseParams.length; i < l; i++ ) {\n let temp = responseParams[i].split('=');\n params[temp[0]] = temp[1];\n }\n if (params.code && UUID == params.state) {\n console.log('received authorization code');\n // Trades authorization code for Access Token\n getAccessToken(params.code);\n }\n else {\n console.log('Error: no authorization code received');\n document.getElementById('oauthMessage').innerHTML=\n \"<p>Unexpected response.</p>\";\n }\n }\n });\n}",
"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 focus_curve_ind ()\r\n{\r\n\t// get index of curve in focus\r\n\tvar curve_in_focus = selections.focus();\r\n\r\n\t// return local index of curve\r\n\tvar curve_in_focus_ind = -1;\r\n\r\n // find curve index, if not null\r\n var curr_sel_ind = 0;\r\n for (var k = 0; k < max_num_sel; k++) {\r\n\r\n // check for curve index in current selection\r\n var ind_sel = selections.in_filtered_sel_x(curve_in_focus, k+1);\r\n\r\n // if found index (and within max number of plots), we're done\r\n if ((ind_sel != -1) &&\r\n (ind_sel < max_num_plots)) {\r\n curve_in_focus_ind = ind_sel + curr_sel_ind;\r\n break;\r\n }\r\n\r\n // otherwise, update index into selection\r\n curr_sel_ind = curr_sel_ind + Math.min(selections.len_filtered_sel(k+1), max_num_plots);\r\n\r\n }\r\n\r\n\treturn curve_in_focus_ind;\r\n}",
"function getOptionIndex(optionRoot, checkString)\n{\n\tif(optionRoot && checkString)\n\t{\n\t\tvar optionsCount = optionRoot.options.length;\n\t\tfor(var i=0; i<optionsCount; i++)\n\t\t\tif(checkString.indexOf(optionRoot.options[i].value) >= 0)\n\t\t\t\treturn i;\n\t}\n\n\treturn -1;\n}",
"function getIVs()\n{\n\treturn [\n\t\tparseInt(document.getElementById('hp-iv').value),\n\t\tparseInt(document.getElementById('atk-iv').value),\n\t\tparseInt(document.getElementById('def-iv').value),\n\t\tparseInt(document.getElementById('spa-iv').value),\n\t\tparseInt(document.getElementById('spd-iv').value),\n\t\tparseInt(document.getElementById('spe-iv').value)\n\t];\n}",
"getIndexID(elasticIndexName){\n\t\n\t\tlet uuid = null;\n\t\n\t\tfor(const [k, v] of Object.entries(this.indexPatterns)){\n\t\t const patt = new RegExp(k);\n\t\t if(patt.test(elasticIndexName)){\n\t\t uuid = v\n\t\t return uuid;\n\t\t }\n\t\t}\n\t\t\n\t\treturn uuid;\n\t}",
"function getPhraseIndex(arr){\n const phraseIndex = arr.indexOf(chosenPhrase);\n return phraseIndex;\n}",
"function getCodeFromKey(key) {\r\n //Constants for key\r\n if (key == STUDENT_INBOX_KEY) return 1;\r\n if (key == ADMIN_INBOX_KEY) return 2;\r\n if (key == STUDENT_SENT_ITEMS_KEY) return 3;\r\n if (key == ADMIN_SENT_ITEMS_KEY) return 4;\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deselect a cell widget. Notes It is a noop if the value does not change. It will emit the `selectionChanged` signal. | deselect(widget) {
if (!Private.selectedProperty.get(widget)) {
return;
}
Private.selectedProperty.set(widget, false);
this._selectionChanged.emit(void 0);
this.update();
} | [
"deselect() {\n if (this.selected != null) {\n this.selected.deselect();\n this.selected = null;\n }\n }",
"deselectValue(value) {\n if (this._invalid) {\n this.selectionModel.clear(false);\n }\n this.selectionModel.deselect(value);\n }",
"function unselect(self, value){\r\n var opts = self.options;\r\n var combo = self.combo;\r\n var values = combo.getValues();\r\n var index = $.inArray(value+'', values);\r\n if (index >= 0){\r\n values.splice(index, 1);\r\n setValues(self, values);\r\n opts.onUnselect.call(self, opts.finder.getRow(self, value));\r\n }\r\n }",
"function deselectDelegate(tblWidget, type, selected, deselect)\n{\n}",
"deselect(option) {\n this.deselectValue(option.value);\n }",
"deselect(option) {\n if (!this.disabled && !option.disabled) {\n option.deselect();\n }\n }",
"function render_deselect(context)\n{\n\tif(selection_coordinates != null)\n\t{\n\t\tstroke_tile(selection_coordinates.x, selection_coordinates.y, grid_color, context);\n\t}\n\trender_pivot(context);\n}",
"unselectItem(item)\n {\n delete this._selectedItems[item.id];\n item.setHighlight(false);\n }",
"onDeselectEvent(){ }",
"deselectAnnotation() {\n if (this.activeAnnotation) {\n this.activeAnnotation.setControlPointsVisibility(false);\n this.activeAnnotation = false;\n }\n }",
"function removeSelected(sel){\n if (isNode(sel))\n {\n graph.removeNode(sel)\n }\n else if (isEdge(sel))\n {\n graph.removeEdge(sel)\n } \n selected = undefined\n repaint()\n }",
"_onElementDeselect() {\n this._displayNoSelectedElementInfo.apply(this);\n }",
"unselectCurrentItem() {\n const activePaginationItem = this.paginationItems[this.activeIndexItem];\n\n activePaginationItem.tabIndex = '-1';\n activePaginationItem.ariaSelected = FALSE_STRING;\n activePaginationItem.className = INDICATOR_ACTION;\n\n this.carouselItems[this.activeIndexItem].callbacks.unselect();\n }",
"function unselectByClick() {\n var points = this.getSelectedPoints();\n if (points.length > 0) {\n Highcharts.each(points, function (point) {\n point.select(false, true);\n });\n }\n }",
"function testSelectionIsClearedWhenSelectedItemIsRemoved() {\n select.render(sandboxEl);\n var item1 = new goog.ui.MenuItem('item 1');\n select.addItem(item1);\n select.addItem(new goog.ui.MenuItem('item 2'));\n\n select.setSelectedItem(item1);\n select.removeItem(item1);\n assertNull(select.getSelectedItem());\n}",
"function unselectCurrentPlayer () {\r\n that.isSelected = false;\r\n this.unhighlightStates();\r\n this.removeClass('selected');\r\n }",
"disable() {\n this.clearSelection();\n this._removeMouseDownListeners();\n this._enabled = false;\n }",
"clearSelect() {\n const [selection] = this.cm.getDoc().listSelections();\n\n if (selection) {\n this.cm.setCursor(selection.to());\n }\n }",
"function unselectFeature() {\n if (highlight) {\n highlight.remove();\n }\n }",
"disableSelect() {\n this.select = false;\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.