hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
sequencelengths
5
5
{ "id": 1, "code_window": [ "\n", "Your `else if` statement should check if `monsterHealth` is less than or equal to `0`.\n", "\n", "```js\n", "assert.match(attack.toString(), /else\\s*if\\s*\\(\\s*monsterHealth\\s*<=\\s*0\\s*\\)/);\n", "```\n", "\n", "Your `else if` statement should call the `defeatMonster` function.\n", "\n", "```js\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "assert.match(attack.toString(), /else\\s+if\\s*\\(\\s*monsterHealth\\s*<=\\s*0\\s*\\)/);\n" ], "file_path": "curriculum/challenges/english/15-javascript-algorithms-and-data-structures-22/learn-basic-javascript-by-building-a-role-playing-game/62a8ee154c8946678775c4a4.md", "type": "replace", "edit_start_line_idx": 32 }
--- id: 6568c024933423d85d5ed93c title: Step 38 challengeType: 20 dashedName: step-38 --- # --description-- If `num` is not in the row, the expression evaluates to `True` and it means the number is valid for insertion. If `num` is in the row, the expression evaluates to `False` and insertion would violate the rules. Return the value from the expression you wrote in the previous step, so that the validity of a number can be checked. # --hints-- You should have `return num not in self.board[row]` within `valid_in_row`. ```js const tCode = code.replace(/\r/g, ''); const valid = __helpers.python.getDef(tCode, "valid_in_row"); const {function_body} = valid; assert.match(function_body, /return\s+num\s+not\s+in\s+self\.board\[row\]/); ``` # --seed-- ## --seed-contents-- ```py class Board: def __init__(self, board): self.board = board def __str__(self): upper_lines = f'\n╔═══{"╤═══"*2}{"╦═══"}{"╤═══"*2}{"╦═══"}{"╤═══"*2}╗\n' middle_lines = f'╟───{"┼───"*2}{"╫───"}{"┼───"*2}{"╫───"}{"┼───"*2}╢\n' lower_lines = f'╚═══{"╧═══"*2}{"╩═══"}{"╧═══"*2}{"╩═══"}{"╧═══"*2}╝\n' board_string = upper_lines for index, line in enumerate(self.board): row_list = [] for square_no, part in enumerate([line[:3], line[3:6], line[6:]], start=1): row_square = '|'.join(str(item) for item in part) row_list.extend(row_square) if square_no != 3: row_list.append('║') row = f'║ {" ".join(row_list)} ║\n' row_empty = row.replace('0', ' ') board_string += row_empty if index < 8: if index % 3 == 2: board_string += f'╠═══{"╪═══"*2}{"╬═══"}{"╪═══"*2}{"╬═══"}{"╪═══"*2}╣\n' else: board_string += middle_lines else: board_string += lower_lines return board_string def find_empty_cell(self): for row, contents in enumerate(self.board): try: col = contents.index(0) return row, col except ValueError: pass return None --fcc-editable-region-- def valid_in_row(self, row, num): num not in self.board[row] --fcc-editable-region-- ```
curriculum/challenges/chinese-traditional/07-scientific-computing-with-python/learn-classes-and-objects-by-building-a-sudoku-solver/6568c024933423d85d5ed93c.md
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/5973899673bed0cdcd8a960453fd63639fbcf315
[ 0.0001775798009475693, 0.0001716585538815707, 0.00016605904966127127, 0.0001727723574731499, 0.000004084889042133 ]
{ "id": 1, "code_window": [ "\n", "Your `else if` statement should check if `monsterHealth` is less than or equal to `0`.\n", "\n", "```js\n", "assert.match(attack.toString(), /else\\s*if\\s*\\(\\s*monsterHealth\\s*<=\\s*0\\s*\\)/);\n", "```\n", "\n", "Your `else if` statement should call the `defeatMonster` function.\n", "\n", "```js\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "assert.match(attack.toString(), /else\\s+if\\s*\\(\\s*monsterHealth\\s*<=\\s*0\\s*\\)/);\n" ], "file_path": "curriculum/challenges/english/15-javascript-algorithms-and-data-structures-22/learn-basic-javascript-by-building-a-role-playing-game/62a8ee154c8946678775c4a4.md", "type": "replace", "edit_start_line_idx": 32 }
--- id: 5900f3951000cf542c50fea8 title: 'Problema 41: Número primo pandigital' challengeType: 1 forumTopicId: 302078 dashedName: problem-41-pandigital-prime --- # --description-- Dizemos que um número de `n` algarismos é pandigital se ele usar todos os algarismos de 1 a `n` exatamente uma vez. Por exemplo, 2143 é um número pandigital de 4 algarismos e também é um número primo. Qual é o maior número primo pandigital de comprimento `n` que existe? # --hints-- `pandigitalPrime(4)` deve retornar um número. ```js assert(typeof pandigitalPrime(4) === 'number'); ``` `pandigitalPrime(4)` deve retornar 4231. ```js assert(pandigitalPrime(4) == 4231); ``` `pandigitalPrime(7)` deve retornar 7652413. ```js assert(pandigitalPrime(7) == 7652413); ``` # --seed-- ## --seed-contents-- ```js function pandigitalPrime(n) { return n; } pandigitalPrime(7); ``` # --solutions-- ```js function pandigitalPrime(n) { function isPrime(num) { for (let i = 2, s = Math.sqrt(num); i <= s; i++) { if (num % i === 0) { return false; } } return num !== 1; } function getPermutations(n) { if (n === 1) { permutations.push(digitsArr.join('')); } else { for (let i = 0; i < n - 1; i++) { getPermutations(n - 1); // swap(n % 2 === 0 ? i : 0, n - 1); if (n % 2 === 0) { swap(i, n - 1); } else { swap(0, n - 1); } } getPermutations(n - 1); } } function swap(x, y) { let temp = digitsArr[x]; digitsArr[x] = digitsArr[y]; digitsArr[y] = temp; } let max = 0; let permutations = []; let digitsArr; let pandigitalNum = ''; for (let max = n; max > 0; max--) { pandigitalNum += max; } for (let i = 0; i < pandigitalNum.length; i++) { if (max > 0) { break; } else { permutations = []; const currMax = pandigitalNum.slice(i); digitsArr = currMax.split(''); getPermutations(digitsArr.length); // sort permutations in descending order permutations.sort(function(a, b) { return b - a; }); for (let perm of permutations) { const thisPerm = parseInt(perm); if (isPrime(thisPerm)) { max = thisPerm; break; } } } } return max; } ```
curriculum/challenges/portuguese/18-project-euler/project-euler-problems-1-to-100/problem-41-pandigital-prime.md
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/5973899673bed0cdcd8a960453fd63639fbcf315
[ 0.00017748872051015496, 0.00017405877588316798, 0.00016674338257871568, 0.00017550845223013312, 0.000003412738124097814 ]
{ "id": 2, "code_window": [ "\n", "Your `else if` statement should call the `defeatMonster` function.\n", "\n", "```js\n", "assert.match(attack.toString(), /else\\s*if\\s*\\(\\s*monsterHealth\\s*<=\\s*0\\s*\\)\\s*(\\{\\s*)?defeatMonster(\\s*\\})?/);\n", "```\n", "\n", "# --seed--\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "assert.match(attack.toString(), /else\\s+if\\s*\\(\\s*monsterHealth\\s*<=\\s*0\\s*\\)\\s*(\\{\\s*)?defeatMonster(\\s*\\})?/);\n" ], "file_path": "curriculum/challenges/english/15-javascript-algorithms-and-data-structures-22/learn-basic-javascript-by-building-a-role-playing-game/62a8ee154c8946678775c4a4.md", "type": "replace", "edit_start_line_idx": 38 }
--- id: 64c705fd8969d677066792b8 title: Step 44 challengeType: 0 dashedName: step-44 --- # --description-- Add an `else if` statement where the condition checks if the left key was pressed and the player's `x` position is greater than 100. Inside the `else if` statement, assign the number -5 to the player's x velocity. # --hints-- You should add an `else if` statement to your `animate` function. ```js assert.match(animate.toString(), /else if/); ``` You should check if the left key was pressed and if the player's `x` position is greater than 100. ```js assert.match(animate.toString(), /keys\.leftKey\.pressed\s*&&\s*player\.position\.x\s*>\s*100/); ``` You should assign the number -5 to the player's `x` velocity inside the `else if`. ```js assert.match(animate.toString(), /player\.velocity\.x\s*=\s*-5\s*;?/); ``` # --seed-- ## --seed-contents-- ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Learn Intermediate OOP by Building a Platformer Game</title> <link rel="stylesheet" href="./styles.css" /> </head> <body> <div class="start-screen"> <h1 class="main-title">freeCodeCamp Code Warrior</h1> <p class="instructions"> Help the main player navigate to the yellow checkpoints. </p> <p class="instructions"> Use the keyboard arrows to move the player around. </p> <p class="instructions">You can also use the spacebar to jump.</p> <div class="btn-container"> <button class="btn" id="start-btn">Start Game</button> </div> </div> <div class="checkpoint-screen"> <h2>Congrats!</h2> <p>You reached the last checkpoint.</p> </div> <canvas id="canvas"></canvas> <script src="./script.js"></script> </body> </html> ``` ```css * { margin: 0; padding: 0; box-sizing: border-box; } :root { --main-bg-color: #0a0a23; --section-bg-color: #ffffff; --golden-yellow: #feac32; } body { background-color: var(--main-bg-color); } .start-screen { background-color: var(--section-bg-color); width: 100%; position: absolute; top: 50%; left: 50%; margin-right: -50%; transform: translate(-50%, -50%); border-radius: 30px; padding: 20px; padding-bottom: 5px; } .main-title { text-align: center; } .instructions { text-align: center; font-size: 1.2rem; margin: 15px; line-height: 2rem; } .btn { cursor: pointer; width: 100px; margin: 10px; color: #0a0a23; font-size: 18px; background-color: var(--golden-yellow); background-image: linear-gradient(#fecc4c, #ffac33); border-color: var(--golden-yellow); border-width: 3px; } .btn:hover { background-image: linear-gradient(#ffcc4c, #f89808); } .btn-container { display: flex; align-items: center; justify-content: center; } .checkpoint-screen { position: absolute; left: 0; right: 0; margin-left: auto; margin-right: auto; width: 100%; text-align: center; background-color: var(--section-bg-color); border-radius: 20px; padding: 10px; display: none; } #canvas { display: none; } @media (min-width: 768px) { .start-screen { width: 60%; max-width: 700px; } .checkpoint-screen { max-width: 300px; } } ``` ```js const startBtn = document.getElementById("start-btn"); const canvas = document.getElementById("canvas"); const startScreen = document.querySelector(".start-screen"); const checkpointScreen = document.querySelector(".checkpoint-screen"); const checkpointMessage = document.querySelector(".checkpoint-screen > p"); const ctx = canvas.getContext("2d"); canvas.width = innerWidth; canvas.height = innerHeight; const gravity = 0.5; let isCheckpointCollisionDetectionActive = true; class Player { constructor() { this.position = { x: 10, y: 400, }; this.velocity = { x: 0, y: 0, }; this.width = 40; this.height = 40; } draw() { ctx.fillStyle = "#99c9ff"; ctx.fillRect(this.position.x, this.position.y, this.width, this.height); } update() { this.draw(); this.position.x += this.velocity.x; this.position.y += this.velocity.y; if (this.position.y + this.height + this.velocity.y <= canvas.height) { if (this.position.y < 0) { this.position.y = 0; this.velocity.y = gravity; } this.velocity.y += gravity; } else { this.velocity.y = 0; } if (this.position.x < this.width) { this.position.x = this.width; } } } const player = new Player(); const animate = () => { requestAnimationFrame(animate); ctx.clearRect(0, 0, canvas.width, canvas.height); player.update(); --fcc-editable-region-- if (keys.rightKey.pressed && player.position.x < 400) { player.velocity.x = 5; } --fcc-editable-region-- } const keys = { rightKey: { pressed: false }, leftKey: { pressed: false } }; const startGame = () => { canvas.style.display = "block"; startScreen.style.display = "none"; player.draw(); } startBtn.addEventListener("click", startGame); ```
curriculum/challenges/english/15-javascript-algorithms-and-data-structures-22/learn-intermediate-oop-by-building-a-platformer-game/64c705fd8969d677066792b8.md
1
https://github.com/freeCodeCamp/freeCodeCamp/commit/5973899673bed0cdcd8a960453fd63639fbcf315
[ 0.0032738461159169674, 0.0003093975246883929, 0.00016408591181971133, 0.00017622338782530278, 0.0005958857364021242 ]
{ "id": 2, "code_window": [ "\n", "Your `else if` statement should call the `defeatMonster` function.\n", "\n", "```js\n", "assert.match(attack.toString(), /else\\s*if\\s*\\(\\s*monsterHealth\\s*<=\\s*0\\s*\\)\\s*(\\{\\s*)?defeatMonster(\\s*\\})?/);\n", "```\n", "\n", "# --seed--\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "assert.match(attack.toString(), /else\\s+if\\s*\\(\\s*monsterHealth\\s*<=\\s*0\\s*\\)\\s*(\\{\\s*)?defeatMonster(\\s*\\})?/);\n" ], "file_path": "curriculum/challenges/english/15-javascript-algorithms-and-data-structures-22/learn-basic-javascript-by-building-a-role-playing-game/62a8ee154c8946678775c4a4.md", "type": "replace", "edit_start_line_idx": 38 }
--- id: 65578c17d54dfab65cd54b95 title: Step 31 challengeType: 20 dashedName: step-31 --- # --description-- Since the algorithm begins its assessment from the starting node, after creating the `paths` dictionary, you need to add the starting node to its own list in the `paths` dictionary. Use the `append()` method to append `start` to the `paths[start]` list. # --hints-- You should use the `append()` method to append `start` to `paths[start]`. ```js ({ test: () => { const shortest = __helpers.python.getDef(code, "shortest_path"); const {function_body} = shortest; assert(function_body.match(/^\s{4}paths\s*\[\s*start\s*\]\.append\s*\(\s*start\s*\)/m)); } }) ``` # --seed-- ## --seed-contents-- ```py my_graph = { 'A': [('B', 3), ('D', 1)], 'B': [('A', 3), ('C', 4)], 'C': [('B', 4), ('D', 7)], 'D': [('A', 1), ('C', 7)] } --fcc-editable-region-- def shortest_path(graph, start): unvisited = list(graph) distances = {node: 0 if node == start else float('inf') for node in graph} paths = {node: [] for node in graph} print(f'Unvisited: {unvisited}\nDistances: {distances}') shortest_path(my_graph, 'A') --fcc-editable-region-- ```
curriculum/challenges/chinese/07-scientific-computing-with-python/learn-algorithm-design-by-building-a-shortest-path-algorithm/65578c17d54dfab65cd54b95.md
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/5973899673bed0cdcd8a960453fd63639fbcf315
[ 0.0013636454241350293, 0.00041002858779393137, 0.0001664328301558271, 0.00017291284166276455, 0.0004768162907566875 ]
{ "id": 2, "code_window": [ "\n", "Your `else if` statement should call the `defeatMonster` function.\n", "\n", "```js\n", "assert.match(attack.toString(), /else\\s*if\\s*\\(\\s*monsterHealth\\s*<=\\s*0\\s*\\)\\s*(\\{\\s*)?defeatMonster(\\s*\\})?/);\n", "```\n", "\n", "# --seed--\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "assert.match(attack.toString(), /else\\s+if\\s*\\(\\s*monsterHealth\\s*<=\\s*0\\s*\\)\\s*(\\{\\s*)?defeatMonster(\\s*\\})?/);\n" ], "file_path": "curriculum/challenges/english/15-javascript-algorithms-and-data-structures-22/learn-basic-javascript-by-building-a-role-playing-game/62a8ee154c8946678775c4a4.md", "type": "replace", "edit_start_line_idx": 38 }
--- id: 56533eb9ac21ba0edf2244df title: Lidar com várias opções idênticas em instruções switch challengeType: 1 videoUrl: 'https://scrimba.com/c/cdBKWCV' forumTopicId: 18242 dashedName: multiple-identical-options-in-switch-statements --- # --description-- Se a instrução `break` for omitida de uma instrução `case` de um `switch`, as instruções `case` seguintes serão executadas até que seja encontrado um `break`. Se você tem várias entradas com a mesma saída, você pode representá-las em uma instrução `switch` da seguinte forma: ```js let result = ""; switch (val) { case 1: case 2: case 3: result = "1, 2, or 3"; break; case 4: result = "4 alone"; } ``` Todos os casos para 1, 2 e 3 vão produzir o mesmo resultado. # --instructions-- Escreva uma instrução para definir `answer` para os seguintes intervalos: `1-3` - `Low` `4-6` - `Mid` `7-9` - `High` **Observação:** você precisará ter uma instrução `case` para cada número no intervalo. # --hints-- `sequentialSizes(1)` deve retornar a string `Low` ```js assert(sequentialSizes(1) === 'Low'); ``` `sequentialSizes(2)` deve retornar a string `Low` ```js assert(sequentialSizes(2) === 'Low'); ``` `sequentialSizes(3)` deve retornar a string `Low` ```js assert(sequentialSizes(3) === 'Low'); ``` `sequentialSizes(4)` deve retornar a string `Mid` ```js assert(sequentialSizes(4) === 'Mid'); ``` `sequentialSizes(5)` deve retornar a string `Mid` ```js assert(sequentialSizes(5) === 'Mid'); ``` `sequentialSizes(6)` deve retornar a string `Mid` ```js assert(sequentialSizes(6) === 'Mid'); ``` `sequentialSizes(7)` deve retornar a string `High` ```js assert(sequentialSizes(7) === 'High'); ``` `sequentialSizes(8)` deve retornar a string `High` ```js assert(sequentialSizes(8) === 'High'); ``` `sequentialSizes(9)` deve retornar a string `High` ```js assert(sequentialSizes(9) === 'High'); ``` Você não deve usar nenhuma instrução do tipo `if` ou `else` ```js assert(!/else/g.test(code) || !/if/g.test(code)); ``` Você deve ter nove instruções `case` ```js assert(code.match(/case/g).length === 9); ``` # --seed-- ## --seed-contents-- ```js function sequentialSizes(val) { let answer = ""; // Only change code below this line // Only change code above this line return answer; } sequentialSizes(1); ``` # --solutions-- ```js function sequentialSizes(val) { let answer = ""; switch (val) { case 1: case 2: case 3: answer = "Low"; break; case 4: case 5: case 6: answer = "Mid"; break; case 7: case 8: case 9: answer = "High"; } return answer; } ```
curriculum/challenges/portuguese/02-javascript-algorithms-and-data-structures/basic-javascript/multiple-identical-options-in-switch-statements.md
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/5973899673bed0cdcd8a960453fd63639fbcf315
[ 0.0006754208006896079, 0.00020458280050661415, 0.00016282146680168808, 0.00017209650832228363, 0.00012592022540047765 ]
{ "id": 2, "code_window": [ "\n", "Your `else if` statement should call the `defeatMonster` function.\n", "\n", "```js\n", "assert.match(attack.toString(), /else\\s*if\\s*\\(\\s*monsterHealth\\s*<=\\s*0\\s*\\)\\s*(\\{\\s*)?defeatMonster(\\s*\\})?/);\n", "```\n", "\n", "# --seed--\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "assert.match(attack.toString(), /else\\s+if\\s*\\(\\s*monsterHealth\\s*<=\\s*0\\s*\\)\\s*(\\{\\s*)?defeatMonster(\\s*\\})?/);\n" ], "file_path": "curriculum/challenges/english/15-javascript-algorithms-and-data-structures-22/learn-basic-javascript-by-building-a-role-playing-game/62a8ee154c8946678775c4a4.md", "type": "replace", "edit_start_line_idx": 38 }
--- id: bd7108d8c242eddfaeb5bd13 title: 世界地図にデータをマッピングする challengeType: 3 forumTopicId: 302365 dashedName: map-data-across-the-globe --- # --description-- **目標:** こちらと似た機能を持つアプリを構築してください: <https://codepen.io/freeCodeCamp/full/mVEJag> 以下のユーザーストーリーを満たし、すべてのテストが成功するようにしてください。 必要に応じて、どのようなライブラリあるいは API を使用してもかまいません。 あなた独自のアレンジを加えましょう。 **ユーザーストーリー:** 隕石が落下した世界地図上のすべての場所を見ることができます。 **ユーザーストーリー:** マップ上に示された箇所を見るだけで、隕石の相対的な大きさを伝えられます。 **ユーザーストーリー:** 隕石のデータポイントにマウスポインターを合わせることで、追加のデータを取得することができます。 **ヒント:** アプリを構築するために使用できるデータセットはこちらです: <https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/meteorite-strike-data.json> 完了したら、CodePen のプロジェクトへのリンクを入れて、「このチャレンジを完了しました」ボタンをクリックしてください。 You can get feedback on your project by sharing it on the <a href="https://forum.freecodecamp.org/c/project-feedback/409" target="_blank" rel="noopener noreferrer nofollow">freeCodeCamp forum</a>. # --solutions-- ```js // solution required ```
curriculum/challenges/japanese/10-coding-interview-prep/take-home-projects/map-data-across-the-globe.md
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/5973899673bed0cdcd8a960453fd63639fbcf315
[ 0.00018724759866017848, 0.000172543412190862, 0.00016507392865605652, 0.00016892605344764888, 0.000008813448403088842 ]
{ "id": 3, "code_window": [ "\n", "You should add an `else if` statement to your `animate` function.\n", "\n", "```js\n", "assert.match(animate.toString(), /else if/);\n", "```\n", "\n", "You should check if the left key was pressed and if the player's `x` position is greater than 100.\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "assert.match(animate.toString(), /else\\s+if/);\n" ], "file_path": "curriculum/challenges/english/15-javascript-algorithms-and-data-structures-22/learn-intermediate-oop-by-building-a-platformer-game/64c705fd8969d677066792b8.md", "type": "replace", "edit_start_line_idx": 18 }
--- id: 650757918a9e97418dc3d71a title: Step 111 challengeType: 0 dashedName: step-111 --- # --description-- The last thing you will need to do is add an `else if` statement. Your condition should check if the player's `x` position is greater than or equal to the checkpoint's `x` position and less than or equal to the checkpoint's `x` position plus `40`. Inside the body of the `else if` statement, you will need to call the `showCheckpointScreen` function and pass in the string `"You reached a checkpoint!"` as an argument. Congratulations! You have completed the platformer game project! # --hints-- You should add an `else if` clause to check is the player's `x` position is greater than or equal to the checkpoint's `x` position and less than or equal to the checkpoint's `x` position plus `40`. ```js assert.match(code, /if\s*\(\s*index\s*===\s*checkpoints\.length\s*-\s*1\s*\)\s*\{\s*isCheckpointCollisionDetectionActive\s*=\s*false;?\s*showCheckpointScreen\(("|'|`)You reached the final checkpoint!\1\);?\s*movePlayer\(\s*\1ArrowRight\1,\s*0,\s*false\);?\s*\}\s*else\s*if\s*\(\s*player\.position\.x\s*>=\s*checkpoint\.position\.x\s*&&\s*player\.position\.x\s*<=\s*checkpoint\.position\.x\s\+\s*40\s*\)\s*\{\s*/) ``` You should call the `showCheckpointScreen` function and pass in "You reached a checkpoint!" as an argument. ```js assert.match(code, /if\s*\(\s*index\s*===\s*checkpoints\.length\s*-\s*1\s*\)\s*\{\s*isCheckpointCollisionDetectionActive\s*=\s*false;?\s*showCheckpointScreen\(("|'|`)You reached the final checkpoint!\1\);?\s*movePlayer\(\s*\1ArrowRight\1,\s*0,\s*false\);?\s*\}\s*else\s*if\s*\(\s*player\.position\.x\s*>=\s*checkpoint\.position\.x\s*&&\s*player\.position\.x\s*<=\s*checkpoint\.position\.x\s\+\s*40\s*\)\s*\{\s*showCheckpointScreen\(\1You\s+reached\s+a\s*checkpoint!\1\);?\s*\};?/) ``` # --seed-- ## --seed-contents-- ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Learn Intermediate OOP by Building a Platformer Game</title> <link rel="stylesheet" href="./styles.css" /> </head> <body> <div class="start-screen"> <h1 class="main-title">freeCodeCamp Code Warrior</h1> <p class="instructions"> Help the main player navigate to the yellow checkpoints. </p> <p class="instructions"> Use the keyboard arrows to move the player around. </p> <p class="instructions">You can also use the spacebar to jump.</p> <div class="btn-container"> <button class="btn" id="start-btn">Start Game</button> </div> </div> <div class="checkpoint-screen"> <h2>Congrats!</h2> <p>You reached the last checkpoint.</p> </div> <canvas id="canvas"></canvas> <script src="./script.js"></script> </body> </html> ``` ```css * { margin: 0; padding: 0; box-sizing: border-box; } :root { --main-bg-color: #0a0a23; --section-bg-color: #ffffff; --golden-yellow: #feac32; } body { background-color: var(--main-bg-color); } .start-screen { background-color: var(--section-bg-color); width: 100%; position: absolute; top: 50%; left: 50%; margin-right: -50%; transform: translate(-50%, -50%); border-radius: 30px; padding: 20px; padding-bottom: 5px; } .main-title { text-align: center; } .instructions { text-align: center; font-size: 1.2rem; margin: 15px; line-height: 2rem; } .btn { cursor: pointer; width: 100px; margin: 10px; color: #0a0a23; font-size: 18px; background-color: var(--golden-yellow); background-image: linear-gradient(#fecc4c, #ffac33); border-color: var(--golden-yellow); border-width: 3px; } .btn:hover { background-image: linear-gradient(#ffcc4c, #f89808); } .btn-container { display: flex; align-items: center; justify-content: center; } .checkpoint-screen { position: absolute; left: 0; right: 0; margin-left: auto; margin-right: auto; width: 100%; text-align: center; background-color: var(--section-bg-color); border-radius: 20px; padding: 10px; display: none; } #canvas { display: none; } @media (min-width: 768px) { .start-screen { width: 60%; max-width: 700px; } .checkpoint-screen { max-width: 300px; } } ``` ```js const startBtn = document.getElementById("start-btn"); const canvas = document.getElementById("canvas"); const startScreen = document.querySelector(".start-screen"); const checkpointScreen = document.querySelector(".checkpoint-screen"); const checkpointMessage = document.querySelector(".checkpoint-screen > p"); const ctx = canvas.getContext("2d"); canvas.width = innerWidth; canvas.height = innerHeight; const gravity = 0.5; let isCheckpointCollisionDetectionActive = true; class Player { constructor() { this.position = { x: 10, y: 400, }; this.velocity = { x: 0, y: 0, }; this.width = 40; this.height = 40; } draw() { ctx.fillStyle = "#99c9ff"; ctx.fillRect(this.position.x, this.position.y, this.width, this.height); } update() { this.draw(); this.position.x += this.velocity.x; this.position.y += this.velocity.y; if (this.position.y + this.height + this.velocity.y <= canvas.height) { if (this.position.y < 0) { this.position.y = 0; this.velocity.y = gravity; } this.velocity.y += gravity; } else { this.velocity.y = 0; } if (this.position.x < this.width) { this.position.x = this.width; } } } class Platform { constructor(x, y) { this.position = { x, y, }; this.width = 200; this.height = 40; } draw() { ctx.fillStyle = "#acd157"; ctx.fillRect(this.position.x, this.position.y, this.width, this.height); } } class CheckPoint { constructor(x, y) { this.position = { x, y, }; this.width = 40; this.height = 70; }; draw() { ctx.fillStyle = "#f1be32"; ctx.fillRect(this.position.x, this.position.y, this.width, this.height); } claim() { this.width = 0; this.height = 0; this.position.y = Infinity; } }; const player = new Player(); const platformPositions = [ { x: 500, y: 450 }, { x: 700, y: 400 }, { x: 850, y: 350 }, { x: 900, y: 350 }, { x: 1050, y: 150 }, { x: 2500, y: 450 }, { x: 2900, y: 400 }, { x: 3150, y: 350 }, { x: 3900, y: 450 }, { x: 4200, y: 400 }, { x: 4400, y: 200 }, { x: 4700, y: 150 } ]; const platforms = platformPositions.map( (platform) => new Platform(platform.x, platform.y) ); const checkpointPositions = [ { x: 1170, y: 80 }, { x: 2900, y: 330 }, { x: 4800, y: 80 }, ]; const checkpoints = checkpointPositions.map( checkpoint => new CheckPoint(checkpoint.x, checkpoint.y) ); const animate = () => { requestAnimationFrame(animate); ctx.clearRect(0, 0, canvas.width, canvas.height); platforms.forEach((platform) => { platform.draw(); }); checkpoints.forEach(checkpoint => { checkpoint.draw(); }); player.update(); if (keys.rightKey.pressed && player.position.x < 400) { player.velocity.x = 5; } else if (keys.leftKey.pressed && player.position.x > 100) { player.velocity.x = -5; } else { player.velocity.x = 0; if (keys.rightKey.pressed && isCheckpointCollisionDetectionActive) { platforms.forEach((platform) => { platform.position.x -= 5; }); checkpoints.forEach((checkpoint) => { checkpoint.position.x -= 5; }); } else if (keys.leftKey.pressed && isCheckpointCollisionDetectionActive) { platforms.forEach((platform) => { platform.position.x += 5; }); checkpoints.forEach((checkpoint) => { checkpoint.position.x += 5; }); } } platforms.forEach((platform) => { const collisionDetectionRules = [ player.position.y + player.height <= platform.position.y, player.position.y + player.height + player.velocity.y >= platform.position.y, player.position.x >= platform.position.x - player.width / 2, player.position.x <= platform.position.x + platform.width - player.width / 3, ]; if (collisionDetectionRules.every((rule) => rule)) { player.velocity.y = 0; return; } const platformDetectionRules = [ player.position.x >= platform.position.x - player.width / 2, player.position.x <= platform.position.x + platform.width - player.width / 3, player.position.y + player.height >= platform.position.y, player.position.y <= platform.position.y + platform.height, ]; if (platformDetectionRules.every(rule => rule)) { player.position.y = platform.position.y + player.height; player.velocity.y = gravity; }; }); checkpoints.forEach((checkpoint, index) => { const checkpointDetectionRules = [ player.position.x >= checkpoint.position.x, player.position.y >= checkpoint.position.y, player.position.y + player.height <= checkpoint.position.y + checkpoint.height, isCheckpointCollisionDetectionActive ]; if (checkpointDetectionRules.every((rule) => rule)) { checkpoint.claim(); --fcc-editable-region-- if (index === checkpoints.length - 1) { isCheckpointCollisionDetectionActive = false; showCheckpointScreen("You reached the final checkpoint!"); movePlayer("ArrowRight", 0, false); } --fcc-editable-region-- }; }); } const keys = { rightKey: { pressed: false }, leftKey: { pressed: false } }; const movePlayer = (key, xVelocity, isPressed) => { if (!isCheckpointCollisionDetectionActive) { player.velocity.x = 0; player.velocity.y = 0; return; } switch (key) { case "ArrowLeft": keys.leftKey.pressed = isPressed; if (xVelocity === 0) { player.velocity.x = xVelocity; } player.velocity.x -= xVelocity; break; case "ArrowUp": case " ": case "Spacebar": player.velocity.y -= 8; break; case "ArrowRight": keys.rightKey.pressed = isPressed; if (xVelocity === 0) { player.velocity.x = xVelocity; } player.velocity.x += xVelocity; } } const startGame = () => { canvas.style.display = "block"; startScreen.style.display = "none"; animate(); } const showCheckpointScreen = (msg) => { checkpointScreen.style.display = "block"; checkpointMessage.textContent = msg; if (isCheckpointCollisionDetectionActive) { setTimeout(() => (checkpointScreen.style.display = "none"), 2000); } }; startBtn.addEventListener("click", startGame); window.addEventListener("keydown", ({ key }) => { movePlayer(key, 8, true); }); window.addEventListener("keyup", ({ key }) => { movePlayer(key, 0, false); }); ``` # --solutions-- ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Learn Intermediate OOP by Building a Platformer Game</title> <link rel="stylesheet" href="./styles.css" /> </head> <body> <div class="start-screen"> <h1 class="main-title">freeCodeCamp Code Warrior</h1> <p class="instructions"> Help the main player navigate to the yellow checkpoints. </p> <p class="instructions"> Use the keyboard arrows to move the player around. </p> <p class="instructions">You can also use the spacebar to jump.</p> <div class="btn-container"> <button class="btn" id="start-btn">Start Game</button> </div> </div> <div class="checkpoint-screen"> <h2>Congrats!</h2> <p>You reached the last checkpoint.</p> </div> <canvas id="canvas"></canvas> <script src="./script.js"></script> </body> </html> ``` ```css * { margin: 0; padding: 0; box-sizing: border-box; } :root { --main-bg-color: #0a0a23; --section-bg-color: #ffffff; --golden-yellow: #feac32; } body { background-color: var(--main-bg-color); } .start-screen { background-color: var(--section-bg-color); width: 100%; position: absolute; top: 50%; left: 50%; margin-right: -50%; transform: translate(-50%, -50%); border-radius: 30px; padding: 20px; padding-bottom: 5px; } .main-title { text-align: center; } .instructions { text-align: center; font-size: 1.2rem; margin: 15px; line-height: 2rem; } .btn { cursor: pointer; width: 100px; margin: 10px; color: #0a0a23; font-size: 18px; background-color: var(--golden-yellow); background-image: linear-gradient(#fecc4c, #ffac33); border-color: var(--golden-yellow); border-width: 3px; } .btn:hover { background-image: linear-gradient(#ffcc4c, #f89808); } .btn-container { display: flex; align-items: center; justify-content: center; } .checkpoint-screen { position: absolute; left: 0; right: 0; margin-left: auto; margin-right: auto; width: 100%; text-align: center; background-color: var(--section-bg-color); border-radius: 20px; padding: 10px; display: none; } #canvas { display: none; } @media (min-width: 768px) { .start-screen { width: 60%; max-width: 700px; } .checkpoint-screen { max-width: 300px; } } ``` ```js const startBtn = document.getElementById("start-btn"); const canvas = document.getElementById("canvas"); const startScreen = document.querySelector(".start-screen"); const checkpointScreen = document.querySelector(".checkpoint-screen"); const checkpointMessage = document.querySelector(".checkpoint-screen > p"); const ctx = canvas.getContext("2d"); canvas.width = innerWidth; canvas.height = innerHeight; const gravity = 0.5; let isCheckpointCollisionDetectionActive = true; class Player { constructor() { this.position = { x: 10, y: 400, }; this.velocity = { x: 0, y: 0, }; this.width = 40; this.height = 40; } draw() { ctx.fillStyle = "#99c9ff"; ctx.fillRect(this.position.x, this.position.y, this.width, this.height); } update() { this.draw(); this.position.x += this.velocity.x; this.position.y += this.velocity.y; if (this.position.y + this.height + this.velocity.y <= canvas.height) { if (this.position.y < 0) { this.position.y = 0; this.velocity.y = gravity; } this.velocity.y += gravity; } else { this.velocity.y = 0; } if (this.position.x < this.width) { this.position.x = this.width; } } } class Platform { constructor(x, y) { this.position = { x, y, }; this.width = 200; this.height = 40; } draw() { ctx.fillStyle = "#acd157"; ctx.fillRect(this.position.x, this.position.y, this.width, this.height); } } class CheckPoint { constructor(x, y) { this.position = { x, y, }; this.width = 40; this.height = 70; }; draw() { ctx.fillStyle = "#f1be32"; ctx.fillRect(this.position.x, this.position.y, this.width, this.height); } claim() { this.width = 0; this.height = 0; this.position.y = Infinity; } }; const player = new Player(); const platformPositions = [ { x: 500, y: 450 }, { x: 700, y: 400 }, { x: 850, y: 350 }, { x: 900, y: 350 }, { x: 1050, y: 150 }, { x: 2500, y: 450 }, { x: 2900, y: 400 }, { x: 3150, y: 350 }, { x: 3900, y: 450 }, { x: 4200, y: 400 }, { x: 4400, y: 200 }, { x: 4700, y: 150 } ]; const platforms = platformPositions.map( (platform) => new Platform(platform.x, platform.y) ); const checkpointPositions = [ { x: 1170, y: 80 }, { x: 2900, y: 330 }, { x: 4800, y: 80 }, ]; const checkpoints = checkpointPositions.map( checkpoint => new CheckPoint(checkpoint.x, checkpoint.y) ); const animate = () => { requestAnimationFrame(animate); ctx.clearRect(0, 0, canvas.width, canvas.height); platforms.forEach((platform) => { platform.draw(); }); checkpoints.forEach(checkpoint => { checkpoint.draw(); }); player.update(); if (keys.rightKey.pressed && player.position.x < 400) { player.velocity.x = 5; } else if (keys.leftKey.pressed && player.position.x > 100) { player.velocity.x = -5; } else { player.velocity.x = 0; if (keys.rightKey.pressed && isCheckpointCollisionDetectionActive) { platforms.forEach((platform) => { platform.position.x -= 5; }); checkpoints.forEach((checkpoint) => { checkpoint.position.x -= 5; }); } else if (keys.leftKey.pressed && isCheckpointCollisionDetectionActive) { platforms.forEach((platform) => { platform.position.x += 5; }); checkpoints.forEach((checkpoint) => { checkpoint.position.x += 5; }); } } platforms.forEach((platform) => { const collisionDetectionRules = [ player.position.y + player.height <= platform.position.y, player.position.y + player.height + player.velocity.y >= platform.position.y, player.position.x >= platform.position.x - player.width / 2, player.position.x <= platform.position.x + platform.width - player.width / 3, ]; if (collisionDetectionRules.every((rule) => rule)) { player.velocity.y = 0; return; } const platformDetectionRules = [ player.position.x >= platform.position.x - player.width / 2, player.position.x <= platform.position.x + platform.width - player.width / 3, player.position.y + player.height >= platform.position.y, player.position.y <= platform.position.y + platform.height, ]; if (platformDetectionRules.every(rule => rule)) { player.position.y = platform.position.y + player.height; player.velocity.y = gravity; }; }); checkpoints.forEach((checkpoint, index) => { const checkpointDetectionRules = [ player.position.x >= checkpoint.position.x, player.position.y >= checkpoint.position.y, player.position.y + player.height <= checkpoint.position.y + checkpoint.height, isCheckpointCollisionDetectionActive ]; if (checkpointDetectionRules.every((rule) => rule)) { checkpoint.claim(); if (index === checkpoints.length - 1) { isCheckpointCollisionDetectionActive = false; showCheckpointScreen("You reached the final checkpoint!"); movePlayer("ArrowRight", 0, false); } else if ( player.position.x >= checkpoint.position.x && player.position.x <= checkpoint.position.x + 40 ) { showCheckpointScreen("You reached a checkpoint!"); } }; }); } const keys = { rightKey: { pressed: false }, leftKey: { pressed: false } }; const movePlayer = (key, xVelocity, isPressed) => { if (!isCheckpointCollisionDetectionActive) { player.velocity.x = 0; player.velocity.y = 0; return; } switch (key) { case "ArrowLeft": keys.leftKey.pressed = isPressed; if (xVelocity === 0) { player.velocity.x = xVelocity; } player.velocity.x -= xVelocity; break; case "ArrowUp": case " ": case "Spacebar": player.velocity.y -= 8; break; case "ArrowRight": keys.rightKey.pressed = isPressed; if (xVelocity === 0) { player.velocity.x = xVelocity; } player.velocity.x += xVelocity; } } const startGame = () => { canvas.style.display = "block"; startScreen.style.display = "none"; animate(); } const showCheckpointScreen = (msg) => { checkpointScreen.style.display = "block"; checkpointMessage.textContent = msg; if (isCheckpointCollisionDetectionActive) { setTimeout(() => (checkpointScreen.style.display = "none"), 2000); } }; startBtn.addEventListener("click", startGame); window.addEventListener("keydown", ({ key }) => { movePlayer(key, 8, true); }); window.addEventListener("keyup", ({ key }) => { movePlayer(key, 0, false); }); ```
curriculum/challenges/english/15-javascript-algorithms-and-data-structures-22/learn-intermediate-oop-by-building-a-platformer-game/650757918a9e97418dc3d71a.md
1
https://github.com/freeCodeCamp/freeCodeCamp/commit/5973899673bed0cdcd8a960453fd63639fbcf315
[ 0.0037331192288547754, 0.00032945690327323973, 0.00016367963689845055, 0.00017137941904366016, 0.0005790165741927922 ]
{ "id": 3, "code_window": [ "\n", "You should add an `else if` statement to your `animate` function.\n", "\n", "```js\n", "assert.match(animate.toString(), /else if/);\n", "```\n", "\n", "You should check if the left key was pressed and if the player's `x` position is greater than 100.\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "assert.match(animate.toString(), /else\\s+if/);\n" ], "file_path": "curriculum/challenges/english/15-javascript-algorithms-and-data-structures-22/learn-intermediate-oop-by-building-a-platformer-game/64c705fd8969d677066792b8.md", "type": "replace", "edit_start_line_idx": 18 }
--- id: aa7697ea2477d1316795783b title: Schweine-Latein challengeType: 1 forumTopicId: 16039 dashedName: pig-latin --- # --description-- Schweine-Latein ist eine Art, englische Wörter zu verändern. Die Regeln lauten: \- Wenn ein Wort mit einem Konsonant beginnt, nimm den ersten Konsonanten oder Konsonanten Cluster, verschieben ihn an das Ende des Wortes und füge `ay` hinzu. \- Wenn ein Wort mit einem Vokal beginnt, füge einfach `way` am Ende hinzu. # --instructions-- Übersetze den angegebenen String in Schweine-Latein. Die Input Strings sind garantiert englische Wörter in ausschließlich Kleinbuchstaben. # --hints-- `translatePigLatin("california")` sollte den String `aliforniacay` zurückgeben. ```js assert.deepEqual(translatePigLatin('california'), 'aliforniacay'); ``` `translatePigLatin("paragraphs")` sollte den String `aragraphspay` zurückgeben. ```js assert.deepEqual(translatePigLatin('paragraphs'), 'aragraphspay'); ``` `translatePigLatin("glove")` sollte den String `oveglay` zurückgeben. ```js assert.deepEqual(translatePigLatin('glove'), 'oveglay'); ``` `translatePigLatin("algorithm")` sollte den String `algorithmway` zurückgeben. ```js assert.deepEqual(translatePigLatin('algorithm'), 'algorithmway'); ``` `translatePigLatin("eight")` sollte den String `eightway` zurückgeben. ```js assert.deepEqual(translatePigLatin('eight'), 'eightway'); ``` Sollte Wörter behandeln können, bei denen der erste Vokal in der Mitte des Wortes vorkommt. `translatePigLatin("schwartz")` sollte den String `artzschway` zurückgeben. ```js assert.deepEqual(translatePigLatin('schwartz'), 'artzschway'); ``` Sollte Wörter ohne Vokale behandeln. `translatePigLatin("rhythm")` sollte den String `rhythmay` zurückgeben. ```js assert.deepEqual(translatePigLatin('rhythm'), 'rhythmay'); ``` # --seed-- ## --seed-contents-- ```js function translatePigLatin(str) { return str; } translatePigLatin("consonant"); ``` # --solutions-- ```js function translatePigLatin(str) { if (isVowel(str.charAt(0))) return str + "way"; var front = []; str = str.split(''); while (str.length && !isVowel(str[0])) { front.push(str.shift()); } return [].concat(str, front).join('') + 'ay'; } function isVowel(c) { return ['a', 'e', 'i', 'o', 'u'].indexOf(c.toLowerCase()) !== -1; } ```
curriculum/challenges/german/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/pig-latin.md
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/5973899673bed0cdcd8a960453fd63639fbcf315
[ 0.0003592429275158793, 0.00020423084788490087, 0.00016537281044293195, 0.00016833041445352137, 0.00007400028698612005 ]
{ "id": 3, "code_window": [ "\n", "You should add an `else if` statement to your `animate` function.\n", "\n", "```js\n", "assert.match(animate.toString(), /else if/);\n", "```\n", "\n", "You should check if the left key was pressed and if the player's `x` position is greater than 100.\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "assert.match(animate.toString(), /else\\s+if/);\n" ], "file_path": "curriculum/challenges/english/15-javascript-algorithms-and-data-structures-22/learn-intermediate-oop-by-building-a-platformer-game/64c705fd8969d677066792b8.md", "type": "replace", "edit_start_line_idx": 18 }
--- id: 617bc3386dc7d07d6469bf20 title: Schritt 32 challengeType: 0 dashedName: step-32 --- # --description-- Beachte, dass du die Intensität von Rot erhöhen musst und die Intensität der grünen `rgb`-Werte senken musst, um Orange zu erstellen. Dies liegt daran, dass Orange die Kombination aus Rot und Gelb ist. Kombiniere Cyan mit Grün, um die Tertiärfarbe Frühlingsgrün herzustellen. Aktualisiere die `rgb`-Funktion in der `.two`-CSS-Regel so, dass Grün den maximalen Wert hat und Blau auf `127` eingestellt ist. # --hints-- Deine `.two`-CSS-Regel sollte eine `background-color`-Eigenschaft auf `rgb(0, 255, 127)` gesetzt haben. ```js assert(new __helpers.CSSHelp(document).getStyle('.two')?.backgroundColor === 'rgb(0, 255, 127)'); ``` # --seed-- ## --seed-contents-- ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Colored Markers</title> <link rel="stylesheet" href="styles.css"> </head> <body> <h1>CSS Color Markers</h1> <div class="container"> <div class="marker one"> </div> <div class="marker two"> </div> <div class="marker three"> </div> </div> </body> </html> ``` ```css h1 { text-align: center; } .container { background-color: rgb(255, 255, 255); padding: 10px 0; } .marker { width: 200px; height: 25px; margin: 10px auto; } .one { background-color: rgb(255, 127, 0); } --fcc-editable-region-- .two { background-color: rgb(0, 255, 255); } --fcc-editable-region-- .three { background-color: rgb(255, 0, 255); } ```
curriculum/challenges/german/14-responsive-web-design-22/learn-css-colors-by-building-a-set-of-colored-markers/617bc3386dc7d07d6469bf20.md
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/5973899673bed0cdcd8a960453fd63639fbcf315
[ 0.00017414551984984428, 0.00017008026770781726, 0.00016718372353352606, 0.00016989021969493479, 0.000002339592583666672 ]
{ "id": 3, "code_window": [ "\n", "You should add an `else if` statement to your `animate` function.\n", "\n", "```js\n", "assert.match(animate.toString(), /else if/);\n", "```\n", "\n", "You should check if the left key was pressed and if the player's `x` position is greater than 100.\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "assert.match(animate.toString(), /else\\s+if/);\n" ], "file_path": "curriculum/challenges/english/15-javascript-algorithms-and-data-structures-22/learn-intermediate-oop-by-building-a-platformer-game/64c705fd8969d677066792b8.md", "type": "replace", "edit_start_line_idx": 18 }
--- id: 64cb4e676c156f7332f40db7 title: Passo 102 challengeType: 0 dashedName: step-102 --- # --description-- Set the `checkpointMessage`'s `textContent` property to the `msg` parameter. # --hints-- You should set the `textContent` property of the `checkpointMessage` to the `msg` parameter. ```js assert.match(code, /\s*checkpointMessage\s*\.\s*textContent\s*=\s*msg\s*;?/); ``` # --seed-- ## --seed-contents-- ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Learn Intermediate OOP by Building a Platformer Game</title> <link rel="stylesheet" href="./styles.css" /> </head> <body> <div class="start-screen"> <h1 class="main-title">freeCodeCamp Code Warrior</h1> <p class="instructions"> Help the main player navigate to the yellow checkpoints. </p> <p class="instructions"> Use the keyboard arrows to move the player around. </p> <p class="instructions">You can also use the spacebar to jump.</p> <div class="btn-container"> <button class="btn" id="start-btn">Start Game</button> </div> </div> <div class="checkpoint-screen"> <h2>Congrats!</h2> <p>You reached the last checkpoint.</p> </div> <canvas id="canvas"></canvas> <script src="./script.js"></script> </body> </html> ``` ```css * { margin: 0; padding: 0; box-sizing: border-box; } :root { --main-bg-color: #0a0a23; --section-bg-color: #ffffff; --golden-yellow: #feac32; } body { background-color: var(--main-bg-color); } .start-screen { background-color: var(--section-bg-color); width: 100%; position: absolute; top: 50%; left: 50%; margin-right: -50%; transform: translate(-50%, -50%); border-radius: 30px; padding: 20px; padding-bottom: 5px; } .main-title { text-align: center; } .instructions { text-align: center; font-size: 1.2rem; margin: 15px; line-height: 2rem; } .btn { cursor: pointer; width: 100px; margin: 10px; color: #0a0a23; font-size: 18px; background-color: var(--golden-yellow); background-image: linear-gradient(#fecc4c, #ffac33); border-color: var(--golden-yellow); border-width: 3px; } .btn:hover { background-image: linear-gradient(#ffcc4c, #f89808); } .btn-container { display: flex; align-items: center; justify-content: center; } .checkpoint-screen { position: absolute; left: 0; right: 0; margin-left: auto; margin-right: auto; width: 100%; text-align: center; background-color: var(--section-bg-color); border-radius: 20px; padding: 10px; display: none; } #canvas { display: none; } @media (min-width: 768px) { .start-screen { width: 60%; max-width: 700px; } .checkpoint-screen { max-width: 300px; } } ``` ```js const startBtn = document.getElementById("start-btn"); const canvas = document.getElementById("canvas"); const startScreen = document.querySelector(".start-screen"); const checkpointScreen = document.querySelector(".checkpoint-screen"); const checkpointMessage = document.querySelector(".checkpoint-screen > p"); const ctx = canvas.getContext("2d"); canvas.width = innerWidth; canvas.height = innerHeight; const gravity = 0.5; let isCheckpointCollisionDetectionActive = true; class Player { constructor() { this.position = { x: 10, y: 400, }; this.velocity = { x: 0, y: 0, }; this.width = 40; this.height = 40; } draw() { ctx.fillStyle = "#99c9ff"; ctx.fillRect(this.position.x, this.position.y, this.width, this.height); } update() { this.draw(); this.position.x += this.velocity.x; this.position.y += this.velocity.y; if (this.position.y + this.height + this.velocity.y <= canvas.height) { if (this.position.y < 0) { this.position.y = 0; this.velocity.y = gravity; } this.velocity.y += gravity; } else { this.velocity.y = 0; } if (this.position.x < this.width) { this.position.x = this.width; } } } class Platform { constructor(x, y) { this.position = { x, y, }; this.width = 200; this.height = 40; } draw() { ctx.fillStyle = "#acd157"; ctx.fillRect(this.position.x, this.position.y, this.width, this.height); } } class CheckPoint { constructor(x, y) { this.position = { x, y, }; this.width = 40; this.height = 70; }; draw() { ctx.fillStyle = "#f1be32"; ctx.fillRect(this.position.x, this.position.y, this.width, this.height); } claim() { this.width = 0; this.height = 0; this.position.y = Infinity; } }; const player = new Player(); const platformPositions = [ { x: 500, y: 450 }, { x: 700, y: 400 }, { x: 850, y: 350 }, { x: 900, y: 350 }, { x: 1050, y: 150 }, { x: 2500, y: 450 }, { x: 2900, y: 400 }, { x: 3150, y: 350 }, { x: 3900, y: 450 }, { x: 4200, y: 400 }, { x: 4400, y: 200 }, { x: 4700, y: 150 } ]; const platforms = platformPositions.map( (platform) => new Platform(platform.x, platform.y) ); const checkpointPositions = [ { x: 1170, y: 80 }, { x: 2900, y: 330 }, { x: 4800, y: 80 }, ]; const checkpoints = checkpointPositions.map( checkpoint => new CheckPoint(checkpoint.x, checkpoint.y) ); const animate = () => { requestAnimationFrame(animate); ctx.clearRect(0, 0, canvas.width, canvas.height); platforms.forEach((platform) => { platform.draw(); }); checkpoints.forEach(checkpoint => { checkpoint.draw(); }); player.update(); if (keys.rightKey.pressed && player.position.x < 400) { player.velocity.x = 5; } else if (keys.leftKey.pressed && player.position.x > 100) { player.velocity.x = -5; } else { player.velocity.x = 0; if (keys.rightKey.pressed && isCheckpointCollisionDetectionActive) { platforms.forEach((platform) => { platform.position.x -= 5; }); checkpoints.forEach((checkpoint) => { checkpoint.position.x -= 5; }); } else if (keys.leftKey.pressed && isCheckpointCollisionDetectionActive) { platforms.forEach((platform) => { platform.position.x += 5; }); checkpoints.forEach((checkpoint) => { checkpoint.position.x += 5; }); } } platforms.forEach((platform) => { const collisionDetectionRules = [ player.position.y + player.height <= platform.position.y, player.position.y + player.height + player.velocity.y >= platform.position.y, player.position.x >= platform.position.x - player.width / 2, player.position.x <= platform.position.x + platform.width - player.width / 3, ]; if (collisionDetectionRules.every((rule) => rule)) { player.velocity.y = 0; return; } const platformDetectionRules = [ player.position.x >= platform.position.x - player.width / 2, player.position.x <= platform.position.x + platform.width - player.width / 3, player.position.y + player.height >= platform.position.y, player.position.y <= platform.position.y + platform.height, ]; if (platformDetectionRules.every(rule => rule)) { player.position.y = platform.position.y + player.height; player.velocity.y = gravity; }; }); } const keys = { rightKey: { pressed: false }, leftKey: { pressed: false } }; const movePlayer = (key, xVelocity, isPressed) => { if (!isCheckpointCollisionDetectionActive) { player.velocity.x = 0; player.velocity.y = 0; return; } switch (key) { case "ArrowLeft": keys.leftKey.pressed = isPressed; if (xVelocity === 0) { player.velocity.x = xVelocity; } player.velocity.x -= xVelocity; break; case "ArrowUp": case " ": case "Spacebar": player.velocity.y -= 8; break; case "ArrowRight": keys.rightKey.pressed = isPressed; if (xVelocity === 0) { player.velocity.x = xVelocity; } player.velocity.x += xVelocity; } } const startGame = () => { canvas.style.display = "block"; startScreen.style.display = "none"; animate(); } --fcc-editable-region-- const showCheckpointScreen = (msg) => { checkpointScreen.style.display = "block"; }; --fcc-editable-region-- startBtn.addEventListener("click", startGame); window.addEventListener("keydown", ({ key }) => { movePlayer(key, 8, true); }); window.addEventListener("keyup", ({ key }) => { movePlayer(key, 0, false); }); ```
curriculum/challenges/portuguese/15-javascript-algorithms-and-data-structures-22/learn-intermediate-oop-by-building-a-platformer-game/64cb4e676c156f7332f40db7.md
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/5973899673bed0cdcd8a960453fd63639fbcf315
[ 0.0024764188565313816, 0.000255803344771266, 0.00016456206503789872, 0.00017003201355692, 0.0003785699373111129 ]
{ "id": 4, "code_window": [ "You should add a `forEach` loop that iterates through the `platforms` array.\n", "\n", "```js\n", "assert.match(code, /else\\sif\\s*\\(.*\\)\\s*{\\s*platforms\\.forEach\\(\\s*\\(platform\\)\\s*=>\\s*{\\s*(.*?)\\s*}\\s*\\);?/);\n", "\n", "```\n", "\n", "You should use the addition assignment operator to add 5 to the platform's `x` position.\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "assert.match(code, /else\\s+if\\s*\\(.*\\)\\s*{\\s*platforms\\.forEach\\(\\s*\\(platform\\)\\s*=>\\s*{\\s*(.*?)\\s*}\\s*\\);?/);\n" ], "file_path": "curriculum/challenges/english/15-javascript-algorithms-and-data-structures-22/learn-intermediate-oop-by-building-a-platformer-game/64c9dc4bd63a92295347c449.md", "type": "replace", "edit_start_line_idx": 27 }
--- id: 62a8ee154c8946678775c4a4 title: Step 126 challengeType: 0 dashedName: step-126 --- # --description-- You can make an `else` statement conditional by using `else if`. Here's an example: ```js if (num > 10) { } else if (num < 5) { } ``` At the end of your `if` statement, add an `else if` statement to check if `monsterHealth` is less than or equal to `0`. In your `else if`, call the `defeatMonster` function. # --hints-- You should have an `else if` statement. ```js assert.match(attack.toString(), /else if/); ``` Your `else if` statement should check if `monsterHealth` is less than or equal to `0`. ```js assert.match(attack.toString(), /else\s*if\s*\(\s*monsterHealth\s*<=\s*0\s*\)/); ``` Your `else if` statement should call the `defeatMonster` function. ```js assert.match(attack.toString(), /else\s*if\s*\(\s*monsterHealth\s*<=\s*0\s*\)\s*(\{\s*)?defeatMonster(\s*\})?/); ``` # --seed-- ## --seed-contents-- ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="./styles.css"> <title>RPG - Dragon Repeller</title> </head> <body> <div id="game"> <div id="stats"> <span class="stat">XP: <strong><span id="xpText">0</span></strong></span> <span class="stat">Health: <strong><span id="healthText">100</span></strong></span> <span class="stat">Gold: <strong><span id="goldText">50</span></strong></span> </div> <div id="controls"> <button id="button1">Go to store</button> <button id="button2">Go to cave</button> <button id="button3">Fight dragon</button> </div> <div id="monsterStats"> <span class="stat">Monster Name: <strong><span id="monsterName"></span></strong></span> <span class="stat">Health: <strong><span id="monsterHealth"></span></strong></span> </div> <div id="text"> Welcome to Dragon Repeller. You must defeat the dragon that is preventing people from leaving the town. You are in the town square. Where do you want to go? Use the buttons above. </div> </div> <script src="./script.js"></script> </body> </html> ``` ```css body { background-color: #0a0a23; } #text { background-color: #0a0a23; color: #ffffff; padding: 10px; } #game { max-width: 500px; max-height: 400px; background-color: #ffffff; color: #ffffff; margin: 30px auto 0px; padding: 10px; } #controls, #stats { border: 1px solid #0a0a23; padding: 5px; color: #0a0a23; } #monsterStats { display: none; border: 1px solid #0a0a23; padding: 5px; color: #ffffff; background-color: #c70d0d; } .stat { padding-right: 10px; } button { cursor: pointer; color: #0a0a23; background-color: #feac32; background-image: linear-gradient(#fecc4c, #ffac33); border: 3px solid #feac32; } ``` ```js let xp = 0; let health = 100; let gold = 50; let currentWeapon = 0; let fighting; let monsterHealth; let inventory = ["stick"]; const button1 = document.querySelector('#button1'); const button2 = document.querySelector("#button2"); const button3 = document.querySelector("#button3"); const text = document.querySelector("#text"); const xpText = document.querySelector("#xpText"); const healthText = document.querySelector("#healthText"); const goldText = document.querySelector("#goldText"); const monsterStats = document.querySelector("#monsterStats"); const monsterName = document.querySelector("#monsterName"); const monsterHealthText = document.querySelector("#monsterHealth"); const weapons = [ { name: 'stick', power: 5 }, { name: 'dagger', power: 30 }, { name: 'claw hammer', power: 50 }, { name: 'sword', power: 100 } ]; const monsters = [ { name: "slime", level: 2, health: 15 }, { name: "fanged beast", level: 8, health: 60 }, { name: "dragon", level: 20, health: 300 } ] const locations = [ { name: "town square", "button text": ["Go to store", "Go to cave", "Fight dragon"], "button functions": [goStore, goCave, fightDragon], text: "You are in the town square. You see a sign that says \"Store\"." }, { name: "store", "button text": ["Buy 10 health (10 gold)", "Buy weapon (30 gold)", "Go to town square"], "button functions": [buyHealth, buyWeapon, goTown], text: "You enter the store." }, { name: "cave", "button text": ["Fight slime", "Fight fanged beast", "Go to town square"], "button functions": [fightSlime, fightBeast, goTown], text: "You enter the cave. You see some monsters." }, { name: "fight", "button text": ["Attack", "Dodge", "Run"], "button functions": [attack, dodge, goTown], text: "You are fighting a monster." } ]; // initialize buttons button1.onclick = goStore; button2.onclick = goCave; button3.onclick = fightDragon; function update(location) { button1.innerText = location["button text"][0]; button2.innerText = location["button text"][1]; button3.innerText = location["button text"][2]; button1.onclick = location["button functions"][0]; button2.onclick = location["button functions"][1]; button3.onclick = location["button functions"][2]; text.innerText = location.text; } function goTown() { update(locations[0]); } function goStore() { update(locations[1]); } function goCave() { update(locations[2]); } function buyHealth() { if (gold >= 10) { gold -= 10; health += 10; goldText.innerText = gold; healthText.innerText = health; } else { text.innerText = "You do not have enough gold to buy health."; } } function buyWeapon() { if (currentWeapon < weapons.length - 1) { if (gold >= 30) { gold -= 30; currentWeapon++; goldText.innerText = gold; let newWeapon = weapons[currentWeapon].name; text.innerText = "You now have a " + newWeapon + "."; inventory.push(newWeapon); text.innerText += " In your inventory you have: " + inventory; } else { text.innerText = "You do not have enough gold to buy a weapon."; } } else { text.innerText = "You already have the most powerful weapon!"; button2.innerText = "Sell weapon for 15 gold"; button2.onclick = sellWeapon; } } function sellWeapon() { if (inventory.length > 1) { gold += 15; goldText.innerText = gold; let currentWeapon = inventory.shift(); text.innerText = "You sold a " + currentWeapon + "."; text.innerText += " In your inventory you have: " + inventory; } else { text.innerText = "Don't sell your only weapon!"; } } function fightSlime() { fighting = 0; goFight(); } function fightBeast() { fighting = 1; goFight(); } function fightDragon() { fighting = 2; goFight(); } function goFight() { update(locations[3]); monsterHealth = monsters[fighting].health; monsterStats.style.display = "block"; monsterName.innerText = monsters[fighting].name; monsterHealthText.innerText = monsterHealth; } --fcc-editable-region-- function attack() { text.innerText = "The " + monsters[fighting].name + " attacks."; text.innerText += " You attack it with your " + weapons[currentWeapon].name + "."; health -= monsters[fighting].level; monsterHealth -= weapons[currentWeapon].power + Math.floor(Math.random() * xp) + 1; healthText.innerText = health; monsterHealthText.innerText = monsterHealth; if (health <= 0) { lose(); } } --fcc-editable-region-- function dodge() { } ```
curriculum/challenges/english/15-javascript-algorithms-and-data-structures-22/learn-basic-javascript-by-building-a-role-playing-game/62a8ee154c8946678775c4a4.md
1
https://github.com/freeCodeCamp/freeCodeCamp/commit/5973899673bed0cdcd8a960453fd63639fbcf315
[ 0.0003613052540458739, 0.00018372281920164824, 0.00016404649068135768, 0.00017537597159389406, 0.00003558211028575897 ]
{ "id": 4, "code_window": [ "You should add a `forEach` loop that iterates through the `platforms` array.\n", "\n", "```js\n", "assert.match(code, /else\\sif\\s*\\(.*\\)\\s*{\\s*platforms\\.forEach\\(\\s*\\(platform\\)\\s*=>\\s*{\\s*(.*?)\\s*}\\s*\\);?/);\n", "\n", "```\n", "\n", "You should use the addition assignment operator to add 5 to the platform's `x` position.\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "assert.match(code, /else\\s+if\\s*\\(.*\\)\\s*{\\s*platforms\\.forEach\\(\\s*\\(platform\\)\\s*=>\\s*{\\s*(.*?)\\s*}\\s*\\);?/);\n" ], "file_path": "curriculum/challenges/english/15-javascript-algorithms-and-data-structures-22/learn-intermediate-oop-by-building-a-platformer-game/64c9dc4bd63a92295347c449.md", "type": "replace", "edit_start_line_idx": 27 }
--- id: 5d792538e2a8d20cc580d481 title: Step 115 challengeType: 0 dashedName: step-115 --- # --description-- The `slice` method can also work on arrays. Add a method `firsttwo` to `spreadsheetFunctions` which takes `arr` as argument and uses `slice` to return the first two elements of `arr`. # --hints-- See description above for instructions. ```js assert( JSON.stringify(spreadsheetFunctions.firsttwo([2, 6, 1, 4, 3])) === '[2,6]' ); ``` # --seed-- ## --before-user-code-- ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Spreadsheet</title> <style> #container { display: grid; grid-template-columns: 50px repeat(10, 200px); grid-template-rows: repeat(11, 30px); } .label { background-color: lightgray; text-align: center; vertical-align: middle; line-height: 30px; } </style> </head> <body> <div id="container"> <div></div> </div> ``` ## --after-user-code-- ```html </body> </html> ``` ## --seed-contents-- ```html <script> const infixToFunction = { "+": (x, y) => x + y, "-": (x, y) => x - y, "*": (x, y) => x * y, "/": (x, y) => x / y }; const infixEval = (str, regex) => str.replace(regex, (_, arg1, fn, arg2) => infixToFunction[fn](parseFloat(arg1), parseFloat(arg2)) ); const highPrecedence = str => { const regex = /([0-9.]+)([*\/])([0-9.]+)/; const str2 = infixEval(str, regex); return str === str2 ? str : highPrecedence(str2); }; --fcc-editable-region-- const spreadsheetFunctions = { "": x => x, random: ([x, y]) => Math.floor(Math.random() * y + x), increment: nums => nums.map(x => x + 1) }; --fcc-editable-region-- const applyFn = str => { const noHigh = highPrecedence(str); const infix = /([0-9.]+)([+-])([0-9.]+)/; const str2 = infixEval(noHigh, infix); const regex = /([a-z]*)\(([0-9., ]*)\)(?!.*\()/i; const toNumberList = args => args.split(",").map(parseFloat); const applyFunction = (fn, args) => spreadsheetFunctions[fn.toLowerCase()](toNumberList(args)); return str2.replace( regex, (match, fn, args) => spreadsheetFunctions.hasOwnProperty(fn.toLowerCase()) ? applyFunction(fn, args) : match ); }; const range = (start, end) => start > end ? [] : [start].concat(range(start + 1, end)); const charRange = (start, end) => range(start.charCodeAt(0), end.charCodeAt(0)).map(x => String.fromCharCode(x) ); const evalFormula = (x, cells) => { const idToText = id => cells.find(cell => cell.id === id).value; const rangeRegex = /([A-J])([1-9][0-9]?):([A-J])([1-9][0-9]?)/gi; const rangeFromString = (n1, n2) => range(parseInt(n1), parseInt(n2)); const elemValue = n => c => idToText(c + n); const addChars = c1 => c2 => n => charRange(c1, c2).map(elemValue(n)); const varRangeExpanded = x.replace(rangeRegex, (_, c1, n1, c2, n2) => rangeFromString(n1, n2).map(addChars(c1)(c2)) ); const varRegex = /[A-J][1-9][0-9]?/gi; const varExpanded = varRangeExpanded.replace( varRegex, match => idToText(match.toUpperCase()) ); const functionExpanded = applyFn(varExpanded); return functionExpanded === x ? functionExpanded : evalFormula(functionExpanded, cells); }; window.onload = () => { const container = document.getElementById("container"); const createLabel = name => { const label = document.createElement("div"); label.className = "label"; label.textContent = name; container.appendChild(label); }; const letters = charRange("A", "J"); letters.forEach(createLabel); range(1, 99).forEach(x => { createLabel(x); letters.forEach(y => { const input = document.createElement("input"); input.type = "text"; input.id = y + x; input.onchange = update; container.appendChild(input); }); }); }; const update = event => { const element = event.target; const value = element.value.replace(/\s/g, ""); if (!value.includes(element.id) && value[0] === "=") { element.value = evalFormula( value.slice(1), Array.from(document.getElementById("container").children) ); } }; </script> ``` # --solutions-- ```html <script> const infixToFunction = { "+": (x, y) => x + y, "-": (x, y) => x - y, "*": (x, y) => x * y, "/": (x, y) => x / y }; const infixEval = (str, regex) => str.replace(regex, (_, arg1, fn, arg2) => infixToFunction[fn](parseFloat(arg1), parseFloat(arg2)) ); const highPrecedence = str => { const regex = /([0-9.]+)([*\/])([0-9.]+)/; const str2 = infixEval(str, regex); return str === str2 ? str : highPrecedence(str2); }; const spreadsheetFunctions = { "": x => x, random: ([x, y]) => Math.floor(Math.random() * y + x), increment: nums => nums.map(x => x + 1), firsttwo: arr => arr.slice(0, 2) }; const applyFn = str => { const noHigh = highPrecedence(str); const infix = /([0-9.]+)([+-])([0-9.]+)/; const str2 = infixEval(noHigh, infix); const regex = /([a-z]*)\(([0-9., ]*)\)(?!.*\()/i; const toNumberList = args => args.split(",").map(parseFloat); const applyFunction = (fn, args) => spreadsheetFunctions[fn.toLowerCase()](toNumberList(args)); return str2.replace( regex, (match, fn, args) => spreadsheetFunctions.hasOwnProperty(fn.toLowerCase()) ? applyFunction(fn, args) : match ); }; const range = (start, end) => start > end ? [] : [start].concat(range(start + 1, end)); const charRange = (start, end) => range(start.charCodeAt(0), end.charCodeAt(0)).map(x => String.fromCharCode(x) ); const evalFormula = (x, cells) => { const idToText = id => cells.find(cell => cell.id === id).value; const rangeRegex = /([A-J])([1-9][0-9]?):([A-J])([1-9][0-9]?)/gi; const rangeFromString = (n1, n2) => range(parseInt(n1), parseInt(n2)); const elemValue = n => c => idToText(c + n); const addChars = c1 => c2 => n => charRange(c1, c2).map(elemValue(n)); const varRangeExpanded = x.replace(rangeRegex, (_, c1, n1, c2, n2) => rangeFromString(n1, n2).map(addChars(c1)(c2)) ); const varRegex = /[A-J][1-9][0-9]?/gi; const varExpanded = varRangeExpanded.replace( varRegex, match => idToText(match.toUpperCase()) ); const functionExpanded = applyFn(varExpanded); return functionExpanded === x ? functionExpanded : evalFormula(functionExpanded, cells); }; window.onload = () => { const container = document.getElementById("container"); const createLabel = name => { const label = document.createElement("div"); label.className = "label"; label.textContent = name; container.appendChild(label); }; const letters = charRange("A", "J"); letters.forEach(createLabel); range(1, 99).forEach(x => { createLabel(x); letters.forEach(y => { const input = document.createElement("input"); input.type = "text"; input.id = y + x; input.onchange = update; container.appendChild(input); }); }); }; const update = event => { const element = event.target; const value = element.value.replace(/\s/g, ""); if (!value.includes(element.id) && value[0] === "=") { element.value = evalFormula( value.slice(1), Array.from(document.getElementById("container").children) ); } }; </script> ```
curriculum/challenges/japanese/15-javascript-algorithms-and-data-structures-22/learn-functional-programming-by-building-a-spreadsheet/step-115.md
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/5973899673bed0cdcd8a960453fd63639fbcf315
[ 0.0001760927843861282, 0.0001710286596789956, 0.00016599413356743753, 0.00017192511586472392, 0.0000030130545383144636 ]
{ "id": 4, "code_window": [ "You should add a `forEach` loop that iterates through the `platforms` array.\n", "\n", "```js\n", "assert.match(code, /else\\sif\\s*\\(.*\\)\\s*{\\s*platforms\\.forEach\\(\\s*\\(platform\\)\\s*=>\\s*{\\s*(.*?)\\s*}\\s*\\);?/);\n", "\n", "```\n", "\n", "You should use the addition assignment operator to add 5 to the platform's `x` position.\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "assert.match(code, /else\\s+if\\s*\\(.*\\)\\s*{\\s*platforms\\.forEach\\(\\s*\\(platform\\)\\s*=>\\s*{\\s*(.*?)\\s*}\\s*\\);?/);\n" ], "file_path": "curriculum/challenges/english/15-javascript-algorithms-and-data-structures-22/learn-intermediate-oop-by-building-a-platformer-game/64c9dc4bd63a92295347c449.md", "type": "replace", "edit_start_line_idx": 27 }
--- id: 655283c039eb38f51e0e6f7e title: Task 9 challengeType: 19 dashedName: task-9 --- <!-- AUDIO REFERENCE: Tom: Hi, that's right! I'm Tom McKenzie. It's a pleasure to meet you. --> # --description-- Tom is introducing himself using a full name. # --question-- ## --text-- Which option is Tom using to formally introduce himself? ## --answers-- `I'm Tom McKenzie.` --- `Call me Tom.` ### --feedback-- Tom is providing both his first name and surname in a formal way. Choose the option that reflects this. --- `It's a pleasure to meet you.` ### --feedback-- Tom is providing both his first name and surname in a formal way. Choose the option that reflects this. --- `It's me, Tom.` ### --feedback-- Tom is providing both his first name and surname in a formal way. Choose the option that reflects this. ## --video-solution-- 1 # --scene-- ```json { "setup": { "background": "company2-center.png", "characters": [ { "character": "Tom", "position": {"x":50,"y":15,"z":1.2}, "opacity": 0 } ], "audio": { "filename": "1.1-1.mp3", "startTime": 1, "startTimestamp": 4.5, "finishTimestamp": 7 } }, "commands": [ { "character": "Tom", "opacity": 1, "startTime": 0 }, { "character": "Tom", "startTime": 1, "finishTime": 3.3, "dialogue": { "text": "Hi, that's right. I'm Tom McKenzie.", "align": "center" } }, { "character": "Tom", "opacity": 0, "startTime": 3.8 } ] } ```
curriculum/challenges/arabic/21-a2-english-for-developers/learn-greetings-in-your-first-day-at-the-office/655283c039eb38f51e0e6f7e.md
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/5973899673bed0cdcd8a960453fd63639fbcf315
[ 0.00017502214177511632, 0.00017238657164853066, 0.00016775443509686738, 0.00017374928575009108, 0.0000024372072857659077 ]
{ "id": 4, "code_window": [ "You should add a `forEach` loop that iterates through the `platforms` array.\n", "\n", "```js\n", "assert.match(code, /else\\sif\\s*\\(.*\\)\\s*{\\s*platforms\\.forEach\\(\\s*\\(platform\\)\\s*=>\\s*{\\s*(.*?)\\s*}\\s*\\);?/);\n", "\n", "```\n", "\n", "You should use the addition assignment operator to add 5 to the platform's `x` position.\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "assert.match(code, /else\\s+if\\s*\\(.*\\)\\s*{\\s*platforms\\.forEach\\(\\s*\\(platform\\)\\s*=>\\s*{\\s*(.*?)\\s*}\\s*\\);?/);\n" ], "file_path": "curriculum/challenges/english/15-javascript-algorithms-and-data-structures-22/learn-intermediate-oop-by-building-a-platformer-game/64c9dc4bd63a92295347c449.md", "type": "replace", "edit_start_line_idx": 27 }
--- id: 5a23c84252665b21eecc8043 title: Sum to 100 challengeType: 1 forumTopicId: 302335 dashedName: sum-to-100 --- # --description-- Find solutions to the *sum to one hundred* puzzle. Add (insert) the mathematical operators **+** or **─** (plus or minus) before any of the digits in the decimal numeric string **123456789** such that the resulting mathematical expression adds up to a particular sum (in this iconic case, **100**). Example: <pre><b>123 + 4 - 5 + 67 - 89 = 100</b></pre> # --instructions-- Write a function that takes a number as parameter. The function should return an array containing all solutions for the given number. The solutions should be strings representing the expressions. For example: "1+23-456+78-9". Sort the array before returning it. # --hints-- `sumTo100` should be a function. ```js assert(typeof sumTo100 == 'function'); ``` `sumTo100(199)` should return an array. ```js assert(Array.isArray(sumTo100(199))); ``` `sumTo100(199)` should return `["-1+2-3+45+67+89", "123-4+5+6+78-9", "123-4+56+7+8+9"]`. ```js assert.deepEqual(sumTo100(199), [ '-1+2-3+45+67+89', '123-4+5+6+78-9', '123-4+56+7+8+9' ]); ``` `sumTo100(209)` should return `["1+234+56+7-89"]`. ```js assert.deepEqual(sumTo100(209), ['1+234+56+7-89']); ``` `sumTo100(243)` should return `["-1-234+567-89", "-12+345+6-7-89", "123+45+6+78-9"]`. ```js assert.deepEqual(sumTo100(243), [ '-1-234+567-89', '-12+345+6-7-89', '123+45+6+78-9' ]); ``` `sumTo100(197)` should return `["1-2-3+45+67+89", "12+34-5+67+89", "123+4-5+6+78-9"]`. ```js assert.deepEqual(sumTo100(197), [ '1-2-3+45+67+89', '12+34-5+67+89', '123+4-5+6+78-9' ]); ``` # --seed-- ## --seed-contents-- ```js function sumTo100(n) { } ``` # --solutions-- ```js function sumTo100(n) { var permutationsWithRepetition = function(n, as) { return as.length > 0 ? foldl1(curry(cartesianProduct)(as), replicate(n, as)) : []; }; var cartesianProduct = function(xs, ys) { return [].concat.apply( [], xs.map(function(x) { return [].concat.apply( [], ys.map(function(y) { return [[x].concat(y)]; }) ); }) ); }; var curry = function(f) { return function(a) { return function(b) { return f(a, b); }; }; }; var flip = function(f) { return function(a, b) { return f.apply(null, [b, a]); }; }; var foldl1 = function(f, xs) { return xs.length > 0 ? xs.slice(1).reduce(f, xs[0]) : []; }; var replicate = function(n, a) { var v = [a], o = []; if (n < 1) return o; while (n > 1) { if (n & 1) o = o.concat(v); n >>= 1; v = v.concat(v); } return o.concat(v); }; var asSum = function(xs) { var dct = xs.reduceRight( function(a, sign, i) { var d = i + 1; // zero-based index to [1-9] positions if (sign !== 0) { // Sum increased, digits cleared return { digits: [], n: a.n + sign * parseInt([d].concat(a.digits).join(''), 10) }; } else return { // Digits extended, sum unchanged digits: [d].concat(a.digits), n: a.n }; }, { digits: [], n: 0 } ); return ( dct.n + (dct.digits.length > 0 ? parseInt(dct.digits.join(''), 10) : 0) ); }; var asString = function(xs) { var ns = xs.reduce(function(a, sign, i) { var d = (i + 1).toString(); return sign === 0 ? a + d : a + (sign > 0 ? '+' : '-') + d; }, ''); return ns[0] === '+' ? tail(ns) : ns; }; var universe = permutationsWithRepetition(9, [0, 1, -1]) .filter(function(x) { return x[0] !== 1 && asSum(x) === n; }) .map(asString); return universe.sort(); } ```
curriculum/challenges/espanol/22-rosetta-code/rosetta-code-challenges/sum-to-100.md
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/5973899673bed0cdcd8a960453fd63639fbcf315
[ 0.00017464756092522293, 0.00017094501527026296, 0.00016549773863516748, 0.00017130852211266756, 0.0000029407183319563046 ]
{ "id": 5, "code_window": [ "You should add an `else if` clause to check is the player's `x` position is greater than or equal to the checkpoint's `x` position and less than or equal to the checkpoint's `x` position plus `40`.\n", "\n", "```js\n", "assert.match(code, /if\\s*\\(\\s*index\\s*===\\s*checkpoints\\.length\\s*-\\s*1\\s*\\)\\s*\\{\\s*isCheckpointCollisionDetectionActive\\s*=\\s*false;?\\s*showCheckpointScreen\\((\"|'|`)You reached the final checkpoint!\\1\\);?\\s*movePlayer\\(\\s*\\1ArrowRight\\1,\\s*0,\\s*false\\);?\\s*\\}\\s*else\\s*if\\s*\\(\\s*player\\.position\\.x\\s*>=\\s*checkpoint\\.position\\.x\\s*&&\\s*player\\.position\\.x\\s*<=\\s*checkpoint\\.position\\.x\\s\\+\\s*40\\s*\\)\\s*\\{\\s*/)\n", "```\n", "\n", "You should call the `showCheckpointScreen` function and pass in \"You reached a checkpoint!\" as an argument.\n", "\n", "```js\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "assert.match(code, /if\\s*\\(\\s*index\\s*===\\s*checkpoints\\.length\\s*-\\s*1\\s*\\)\\s*\\{\\s*isCheckpointCollisionDetectionActive\\s*=\\s*false;?\\s*showCheckpointScreen\\((\"|'|`)You reached the final checkpoint!\\1\\);?\\s*movePlayer\\(\\s*\\1ArrowRight\\1,\\s*0,\\s*false\\);?\\s*\\}\\s*else\\s+if\\s*\\(\\s*player\\.position\\.x\\s*>=\\s*checkpoint\\.position\\.x\\s*&&\\s*player\\.position\\.x\\s*<=\\s*checkpoint\\.position\\.x\\s\\+\\s*40\\s*\\)\\s*\\{\\s*/)\n" ], "file_path": "curriculum/challenges/english/15-javascript-algorithms-and-data-structures-22/learn-intermediate-oop-by-building-a-platformer-game/650757918a9e97418dc3d71a.md", "type": "replace", "edit_start_line_idx": 22 }
--- id: 650757918a9e97418dc3d71a title: Step 111 challengeType: 0 dashedName: step-111 --- # --description-- The last thing you will need to do is add an `else if` statement. Your condition should check if the player's `x` position is greater than or equal to the checkpoint's `x` position and less than or equal to the checkpoint's `x` position plus `40`. Inside the body of the `else if` statement, you will need to call the `showCheckpointScreen` function and pass in the string `"You reached a checkpoint!"` as an argument. Congratulations! You have completed the platformer game project! # --hints-- You should add an `else if` clause to check is the player's `x` position is greater than or equal to the checkpoint's `x` position and less than or equal to the checkpoint's `x` position plus `40`. ```js assert.match(code, /if\s*\(\s*index\s*===\s*checkpoints\.length\s*-\s*1\s*\)\s*\{\s*isCheckpointCollisionDetectionActive\s*=\s*false;?\s*showCheckpointScreen\(("|'|`)You reached the final checkpoint!\1\);?\s*movePlayer\(\s*\1ArrowRight\1,\s*0,\s*false\);?\s*\}\s*else\s*if\s*\(\s*player\.position\.x\s*>=\s*checkpoint\.position\.x\s*&&\s*player\.position\.x\s*<=\s*checkpoint\.position\.x\s\+\s*40\s*\)\s*\{\s*/) ``` You should call the `showCheckpointScreen` function and pass in "You reached a checkpoint!" as an argument. ```js assert.match(code, /if\s*\(\s*index\s*===\s*checkpoints\.length\s*-\s*1\s*\)\s*\{\s*isCheckpointCollisionDetectionActive\s*=\s*false;?\s*showCheckpointScreen\(("|'|`)You reached the final checkpoint!\1\);?\s*movePlayer\(\s*\1ArrowRight\1,\s*0,\s*false\);?\s*\}\s*else\s*if\s*\(\s*player\.position\.x\s*>=\s*checkpoint\.position\.x\s*&&\s*player\.position\.x\s*<=\s*checkpoint\.position\.x\s\+\s*40\s*\)\s*\{\s*showCheckpointScreen\(\1You\s+reached\s+a\s*checkpoint!\1\);?\s*\};?/) ``` # --seed-- ## --seed-contents-- ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Learn Intermediate OOP by Building a Platformer Game</title> <link rel="stylesheet" href="./styles.css" /> </head> <body> <div class="start-screen"> <h1 class="main-title">freeCodeCamp Code Warrior</h1> <p class="instructions"> Help the main player navigate to the yellow checkpoints. </p> <p class="instructions"> Use the keyboard arrows to move the player around. </p> <p class="instructions">You can also use the spacebar to jump.</p> <div class="btn-container"> <button class="btn" id="start-btn">Start Game</button> </div> </div> <div class="checkpoint-screen"> <h2>Congrats!</h2> <p>You reached the last checkpoint.</p> </div> <canvas id="canvas"></canvas> <script src="./script.js"></script> </body> </html> ``` ```css * { margin: 0; padding: 0; box-sizing: border-box; } :root { --main-bg-color: #0a0a23; --section-bg-color: #ffffff; --golden-yellow: #feac32; } body { background-color: var(--main-bg-color); } .start-screen { background-color: var(--section-bg-color); width: 100%; position: absolute; top: 50%; left: 50%; margin-right: -50%; transform: translate(-50%, -50%); border-radius: 30px; padding: 20px; padding-bottom: 5px; } .main-title { text-align: center; } .instructions { text-align: center; font-size: 1.2rem; margin: 15px; line-height: 2rem; } .btn { cursor: pointer; width: 100px; margin: 10px; color: #0a0a23; font-size: 18px; background-color: var(--golden-yellow); background-image: linear-gradient(#fecc4c, #ffac33); border-color: var(--golden-yellow); border-width: 3px; } .btn:hover { background-image: linear-gradient(#ffcc4c, #f89808); } .btn-container { display: flex; align-items: center; justify-content: center; } .checkpoint-screen { position: absolute; left: 0; right: 0; margin-left: auto; margin-right: auto; width: 100%; text-align: center; background-color: var(--section-bg-color); border-radius: 20px; padding: 10px; display: none; } #canvas { display: none; } @media (min-width: 768px) { .start-screen { width: 60%; max-width: 700px; } .checkpoint-screen { max-width: 300px; } } ``` ```js const startBtn = document.getElementById("start-btn"); const canvas = document.getElementById("canvas"); const startScreen = document.querySelector(".start-screen"); const checkpointScreen = document.querySelector(".checkpoint-screen"); const checkpointMessage = document.querySelector(".checkpoint-screen > p"); const ctx = canvas.getContext("2d"); canvas.width = innerWidth; canvas.height = innerHeight; const gravity = 0.5; let isCheckpointCollisionDetectionActive = true; class Player { constructor() { this.position = { x: 10, y: 400, }; this.velocity = { x: 0, y: 0, }; this.width = 40; this.height = 40; } draw() { ctx.fillStyle = "#99c9ff"; ctx.fillRect(this.position.x, this.position.y, this.width, this.height); } update() { this.draw(); this.position.x += this.velocity.x; this.position.y += this.velocity.y; if (this.position.y + this.height + this.velocity.y <= canvas.height) { if (this.position.y < 0) { this.position.y = 0; this.velocity.y = gravity; } this.velocity.y += gravity; } else { this.velocity.y = 0; } if (this.position.x < this.width) { this.position.x = this.width; } } } class Platform { constructor(x, y) { this.position = { x, y, }; this.width = 200; this.height = 40; } draw() { ctx.fillStyle = "#acd157"; ctx.fillRect(this.position.x, this.position.y, this.width, this.height); } } class CheckPoint { constructor(x, y) { this.position = { x, y, }; this.width = 40; this.height = 70; }; draw() { ctx.fillStyle = "#f1be32"; ctx.fillRect(this.position.x, this.position.y, this.width, this.height); } claim() { this.width = 0; this.height = 0; this.position.y = Infinity; } }; const player = new Player(); const platformPositions = [ { x: 500, y: 450 }, { x: 700, y: 400 }, { x: 850, y: 350 }, { x: 900, y: 350 }, { x: 1050, y: 150 }, { x: 2500, y: 450 }, { x: 2900, y: 400 }, { x: 3150, y: 350 }, { x: 3900, y: 450 }, { x: 4200, y: 400 }, { x: 4400, y: 200 }, { x: 4700, y: 150 } ]; const platforms = platformPositions.map( (platform) => new Platform(platform.x, platform.y) ); const checkpointPositions = [ { x: 1170, y: 80 }, { x: 2900, y: 330 }, { x: 4800, y: 80 }, ]; const checkpoints = checkpointPositions.map( checkpoint => new CheckPoint(checkpoint.x, checkpoint.y) ); const animate = () => { requestAnimationFrame(animate); ctx.clearRect(0, 0, canvas.width, canvas.height); platforms.forEach((platform) => { platform.draw(); }); checkpoints.forEach(checkpoint => { checkpoint.draw(); }); player.update(); if (keys.rightKey.pressed && player.position.x < 400) { player.velocity.x = 5; } else if (keys.leftKey.pressed && player.position.x > 100) { player.velocity.x = -5; } else { player.velocity.x = 0; if (keys.rightKey.pressed && isCheckpointCollisionDetectionActive) { platforms.forEach((platform) => { platform.position.x -= 5; }); checkpoints.forEach((checkpoint) => { checkpoint.position.x -= 5; }); } else if (keys.leftKey.pressed && isCheckpointCollisionDetectionActive) { platforms.forEach((platform) => { platform.position.x += 5; }); checkpoints.forEach((checkpoint) => { checkpoint.position.x += 5; }); } } platforms.forEach((platform) => { const collisionDetectionRules = [ player.position.y + player.height <= platform.position.y, player.position.y + player.height + player.velocity.y >= platform.position.y, player.position.x >= platform.position.x - player.width / 2, player.position.x <= platform.position.x + platform.width - player.width / 3, ]; if (collisionDetectionRules.every((rule) => rule)) { player.velocity.y = 0; return; } const platformDetectionRules = [ player.position.x >= platform.position.x - player.width / 2, player.position.x <= platform.position.x + platform.width - player.width / 3, player.position.y + player.height >= platform.position.y, player.position.y <= platform.position.y + platform.height, ]; if (platformDetectionRules.every(rule => rule)) { player.position.y = platform.position.y + player.height; player.velocity.y = gravity; }; }); checkpoints.forEach((checkpoint, index) => { const checkpointDetectionRules = [ player.position.x >= checkpoint.position.x, player.position.y >= checkpoint.position.y, player.position.y + player.height <= checkpoint.position.y + checkpoint.height, isCheckpointCollisionDetectionActive ]; if (checkpointDetectionRules.every((rule) => rule)) { checkpoint.claim(); --fcc-editable-region-- if (index === checkpoints.length - 1) { isCheckpointCollisionDetectionActive = false; showCheckpointScreen("You reached the final checkpoint!"); movePlayer("ArrowRight", 0, false); } --fcc-editable-region-- }; }); } const keys = { rightKey: { pressed: false }, leftKey: { pressed: false } }; const movePlayer = (key, xVelocity, isPressed) => { if (!isCheckpointCollisionDetectionActive) { player.velocity.x = 0; player.velocity.y = 0; return; } switch (key) { case "ArrowLeft": keys.leftKey.pressed = isPressed; if (xVelocity === 0) { player.velocity.x = xVelocity; } player.velocity.x -= xVelocity; break; case "ArrowUp": case " ": case "Spacebar": player.velocity.y -= 8; break; case "ArrowRight": keys.rightKey.pressed = isPressed; if (xVelocity === 0) { player.velocity.x = xVelocity; } player.velocity.x += xVelocity; } } const startGame = () => { canvas.style.display = "block"; startScreen.style.display = "none"; animate(); } const showCheckpointScreen = (msg) => { checkpointScreen.style.display = "block"; checkpointMessage.textContent = msg; if (isCheckpointCollisionDetectionActive) { setTimeout(() => (checkpointScreen.style.display = "none"), 2000); } }; startBtn.addEventListener("click", startGame); window.addEventListener("keydown", ({ key }) => { movePlayer(key, 8, true); }); window.addEventListener("keyup", ({ key }) => { movePlayer(key, 0, false); }); ``` # --solutions-- ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Learn Intermediate OOP by Building a Platformer Game</title> <link rel="stylesheet" href="./styles.css" /> </head> <body> <div class="start-screen"> <h1 class="main-title">freeCodeCamp Code Warrior</h1> <p class="instructions"> Help the main player navigate to the yellow checkpoints. </p> <p class="instructions"> Use the keyboard arrows to move the player around. </p> <p class="instructions">You can also use the spacebar to jump.</p> <div class="btn-container"> <button class="btn" id="start-btn">Start Game</button> </div> </div> <div class="checkpoint-screen"> <h2>Congrats!</h2> <p>You reached the last checkpoint.</p> </div> <canvas id="canvas"></canvas> <script src="./script.js"></script> </body> </html> ``` ```css * { margin: 0; padding: 0; box-sizing: border-box; } :root { --main-bg-color: #0a0a23; --section-bg-color: #ffffff; --golden-yellow: #feac32; } body { background-color: var(--main-bg-color); } .start-screen { background-color: var(--section-bg-color); width: 100%; position: absolute; top: 50%; left: 50%; margin-right: -50%; transform: translate(-50%, -50%); border-radius: 30px; padding: 20px; padding-bottom: 5px; } .main-title { text-align: center; } .instructions { text-align: center; font-size: 1.2rem; margin: 15px; line-height: 2rem; } .btn { cursor: pointer; width: 100px; margin: 10px; color: #0a0a23; font-size: 18px; background-color: var(--golden-yellow); background-image: linear-gradient(#fecc4c, #ffac33); border-color: var(--golden-yellow); border-width: 3px; } .btn:hover { background-image: linear-gradient(#ffcc4c, #f89808); } .btn-container { display: flex; align-items: center; justify-content: center; } .checkpoint-screen { position: absolute; left: 0; right: 0; margin-left: auto; margin-right: auto; width: 100%; text-align: center; background-color: var(--section-bg-color); border-radius: 20px; padding: 10px; display: none; } #canvas { display: none; } @media (min-width: 768px) { .start-screen { width: 60%; max-width: 700px; } .checkpoint-screen { max-width: 300px; } } ``` ```js const startBtn = document.getElementById("start-btn"); const canvas = document.getElementById("canvas"); const startScreen = document.querySelector(".start-screen"); const checkpointScreen = document.querySelector(".checkpoint-screen"); const checkpointMessage = document.querySelector(".checkpoint-screen > p"); const ctx = canvas.getContext("2d"); canvas.width = innerWidth; canvas.height = innerHeight; const gravity = 0.5; let isCheckpointCollisionDetectionActive = true; class Player { constructor() { this.position = { x: 10, y: 400, }; this.velocity = { x: 0, y: 0, }; this.width = 40; this.height = 40; } draw() { ctx.fillStyle = "#99c9ff"; ctx.fillRect(this.position.x, this.position.y, this.width, this.height); } update() { this.draw(); this.position.x += this.velocity.x; this.position.y += this.velocity.y; if (this.position.y + this.height + this.velocity.y <= canvas.height) { if (this.position.y < 0) { this.position.y = 0; this.velocity.y = gravity; } this.velocity.y += gravity; } else { this.velocity.y = 0; } if (this.position.x < this.width) { this.position.x = this.width; } } } class Platform { constructor(x, y) { this.position = { x, y, }; this.width = 200; this.height = 40; } draw() { ctx.fillStyle = "#acd157"; ctx.fillRect(this.position.x, this.position.y, this.width, this.height); } } class CheckPoint { constructor(x, y) { this.position = { x, y, }; this.width = 40; this.height = 70; }; draw() { ctx.fillStyle = "#f1be32"; ctx.fillRect(this.position.x, this.position.y, this.width, this.height); } claim() { this.width = 0; this.height = 0; this.position.y = Infinity; } }; const player = new Player(); const platformPositions = [ { x: 500, y: 450 }, { x: 700, y: 400 }, { x: 850, y: 350 }, { x: 900, y: 350 }, { x: 1050, y: 150 }, { x: 2500, y: 450 }, { x: 2900, y: 400 }, { x: 3150, y: 350 }, { x: 3900, y: 450 }, { x: 4200, y: 400 }, { x: 4400, y: 200 }, { x: 4700, y: 150 } ]; const platforms = platformPositions.map( (platform) => new Platform(platform.x, platform.y) ); const checkpointPositions = [ { x: 1170, y: 80 }, { x: 2900, y: 330 }, { x: 4800, y: 80 }, ]; const checkpoints = checkpointPositions.map( checkpoint => new CheckPoint(checkpoint.x, checkpoint.y) ); const animate = () => { requestAnimationFrame(animate); ctx.clearRect(0, 0, canvas.width, canvas.height); platforms.forEach((platform) => { platform.draw(); }); checkpoints.forEach(checkpoint => { checkpoint.draw(); }); player.update(); if (keys.rightKey.pressed && player.position.x < 400) { player.velocity.x = 5; } else if (keys.leftKey.pressed && player.position.x > 100) { player.velocity.x = -5; } else { player.velocity.x = 0; if (keys.rightKey.pressed && isCheckpointCollisionDetectionActive) { platforms.forEach((platform) => { platform.position.x -= 5; }); checkpoints.forEach((checkpoint) => { checkpoint.position.x -= 5; }); } else if (keys.leftKey.pressed && isCheckpointCollisionDetectionActive) { platforms.forEach((platform) => { platform.position.x += 5; }); checkpoints.forEach((checkpoint) => { checkpoint.position.x += 5; }); } } platforms.forEach((platform) => { const collisionDetectionRules = [ player.position.y + player.height <= platform.position.y, player.position.y + player.height + player.velocity.y >= platform.position.y, player.position.x >= platform.position.x - player.width / 2, player.position.x <= platform.position.x + platform.width - player.width / 3, ]; if (collisionDetectionRules.every((rule) => rule)) { player.velocity.y = 0; return; } const platformDetectionRules = [ player.position.x >= platform.position.x - player.width / 2, player.position.x <= platform.position.x + platform.width - player.width / 3, player.position.y + player.height >= platform.position.y, player.position.y <= platform.position.y + platform.height, ]; if (platformDetectionRules.every(rule => rule)) { player.position.y = platform.position.y + player.height; player.velocity.y = gravity; }; }); checkpoints.forEach((checkpoint, index) => { const checkpointDetectionRules = [ player.position.x >= checkpoint.position.x, player.position.y >= checkpoint.position.y, player.position.y + player.height <= checkpoint.position.y + checkpoint.height, isCheckpointCollisionDetectionActive ]; if (checkpointDetectionRules.every((rule) => rule)) { checkpoint.claim(); if (index === checkpoints.length - 1) { isCheckpointCollisionDetectionActive = false; showCheckpointScreen("You reached the final checkpoint!"); movePlayer("ArrowRight", 0, false); } else if ( player.position.x >= checkpoint.position.x && player.position.x <= checkpoint.position.x + 40 ) { showCheckpointScreen("You reached a checkpoint!"); } }; }); } const keys = { rightKey: { pressed: false }, leftKey: { pressed: false } }; const movePlayer = (key, xVelocity, isPressed) => { if (!isCheckpointCollisionDetectionActive) { player.velocity.x = 0; player.velocity.y = 0; return; } switch (key) { case "ArrowLeft": keys.leftKey.pressed = isPressed; if (xVelocity === 0) { player.velocity.x = xVelocity; } player.velocity.x -= xVelocity; break; case "ArrowUp": case " ": case "Spacebar": player.velocity.y -= 8; break; case "ArrowRight": keys.rightKey.pressed = isPressed; if (xVelocity === 0) { player.velocity.x = xVelocity; } player.velocity.x += xVelocity; } } const startGame = () => { canvas.style.display = "block"; startScreen.style.display = "none"; animate(); } const showCheckpointScreen = (msg) => { checkpointScreen.style.display = "block"; checkpointMessage.textContent = msg; if (isCheckpointCollisionDetectionActive) { setTimeout(() => (checkpointScreen.style.display = "none"), 2000); } }; startBtn.addEventListener("click", startGame); window.addEventListener("keydown", ({ key }) => { movePlayer(key, 8, true); }); window.addEventListener("keyup", ({ key }) => { movePlayer(key, 0, false); }); ```
curriculum/challenges/english/15-javascript-algorithms-and-data-structures-22/learn-intermediate-oop-by-building-a-platformer-game/650757918a9e97418dc3d71a.md
1
https://github.com/freeCodeCamp/freeCodeCamp/commit/5973899673bed0cdcd8a960453fd63639fbcf315
[ 0.9949678778648376, 0.05187408998608589, 0.00016366589989047498, 0.00020435935584828258, 0.19574102759361267 ]
{ "id": 5, "code_window": [ "You should add an `else if` clause to check is the player's `x` position is greater than or equal to the checkpoint's `x` position and less than or equal to the checkpoint's `x` position plus `40`.\n", "\n", "```js\n", "assert.match(code, /if\\s*\\(\\s*index\\s*===\\s*checkpoints\\.length\\s*-\\s*1\\s*\\)\\s*\\{\\s*isCheckpointCollisionDetectionActive\\s*=\\s*false;?\\s*showCheckpointScreen\\((\"|'|`)You reached the final checkpoint!\\1\\);?\\s*movePlayer\\(\\s*\\1ArrowRight\\1,\\s*0,\\s*false\\);?\\s*\\}\\s*else\\s*if\\s*\\(\\s*player\\.position\\.x\\s*>=\\s*checkpoint\\.position\\.x\\s*&&\\s*player\\.position\\.x\\s*<=\\s*checkpoint\\.position\\.x\\s\\+\\s*40\\s*\\)\\s*\\{\\s*/)\n", "```\n", "\n", "You should call the `showCheckpointScreen` function and pass in \"You reached a checkpoint!\" as an argument.\n", "\n", "```js\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "assert.match(code, /if\\s*\\(\\s*index\\s*===\\s*checkpoints\\.length\\s*-\\s*1\\s*\\)\\s*\\{\\s*isCheckpointCollisionDetectionActive\\s*=\\s*false;?\\s*showCheckpointScreen\\((\"|'|`)You reached the final checkpoint!\\1\\);?\\s*movePlayer\\(\\s*\\1ArrowRight\\1,\\s*0,\\s*false\\);?\\s*\\}\\s*else\\s+if\\s*\\(\\s*player\\.position\\.x\\s*>=\\s*checkpoint\\.position\\.x\\s*&&\\s*player\\.position\\.x\\s*<=\\s*checkpoint\\.position\\.x\\s\\+\\s*40\\s*\\)\\s*\\{\\s*/)\n" ], "file_path": "curriculum/challenges/english/15-javascript-algorithms-and-data-structures-22/learn-intermediate-oop-by-building-a-platformer-game/650757918a9e97418dc3d71a.md", "type": "replace", "edit_start_line_idx": 22 }
--- id: 65688efcc78c9495e73acfc9 title: Step 3 challengeType: 20 dashedName: step-3 --- # --description-- Add two parameters to the `__init__` method, order matters: - `self`: This is a reference to the instance of the class. It is a convention to name this parameter self. - `board`: The board parameter is expected to be passed when creating an instance of the `Board` class. # --hints-- You should add the parameter `self` and `board` to the method. ```js assert.match(code, /def\s+__init__\s*\(\s*self\s*,\s*board\s*\):/); ``` # --seed-- ## --seed-contents-- ```py --fcc-editable-region-- class Board: def __init__(): --fcc-editable-region-- ```
curriculum/challenges/italian/07-scientific-computing-with-python/learn-classes-and-objects-by-building-a-sudoku-solver/65688efcc78c9495e73acfc9.md
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/5973899673bed0cdcd8a960453fd63639fbcf315
[ 0.0001708696800051257, 0.00016762423911131918, 0.00016512589354533702, 0.000167250691447407, 0.000002539836259529693 ]
{ "id": 5, "code_window": [ "You should add an `else if` clause to check is the player's `x` position is greater than or equal to the checkpoint's `x` position and less than or equal to the checkpoint's `x` position plus `40`.\n", "\n", "```js\n", "assert.match(code, /if\\s*\\(\\s*index\\s*===\\s*checkpoints\\.length\\s*-\\s*1\\s*\\)\\s*\\{\\s*isCheckpointCollisionDetectionActive\\s*=\\s*false;?\\s*showCheckpointScreen\\((\"|'|`)You reached the final checkpoint!\\1\\);?\\s*movePlayer\\(\\s*\\1ArrowRight\\1,\\s*0,\\s*false\\);?\\s*\\}\\s*else\\s*if\\s*\\(\\s*player\\.position\\.x\\s*>=\\s*checkpoint\\.position\\.x\\s*&&\\s*player\\.position\\.x\\s*<=\\s*checkpoint\\.position\\.x\\s\\+\\s*40\\s*\\)\\s*\\{\\s*/)\n", "```\n", "\n", "You should call the `showCheckpointScreen` function and pass in \"You reached a checkpoint!\" as an argument.\n", "\n", "```js\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "assert.match(code, /if\\s*\\(\\s*index\\s*===\\s*checkpoints\\.length\\s*-\\s*1\\s*\\)\\s*\\{\\s*isCheckpointCollisionDetectionActive\\s*=\\s*false;?\\s*showCheckpointScreen\\((\"|'|`)You reached the final checkpoint!\\1\\);?\\s*movePlayer\\(\\s*\\1ArrowRight\\1,\\s*0,\\s*false\\);?\\s*\\}\\s*else\\s+if\\s*\\(\\s*player\\.position\\.x\\s*>=\\s*checkpoint\\.position\\.x\\s*&&\\s*player\\.position\\.x\\s*<=\\s*checkpoint\\.position\\.x\\s\\+\\s*40\\s*\\)\\s*\\{\\s*/)\n" ], "file_path": "curriculum/challenges/english/15-javascript-algorithms-and-data-structures-22/learn-intermediate-oop-by-building-a-platformer-game/650757918a9e97418dc3d71a.md", "type": "replace", "edit_start_line_idx": 22 }
--- id: 5ddb965c65d27e1512d44dc7 title: Step 48 challengeType: 0 dashedName: step-48 --- # --description-- Now it's time to add some styling which can be added directly as attributes or classes. In our CSS file, we have a styling rule for any elements with the class name `green-text`. On line **20**, right after creating the `result` element, set the `className` property of `result` to be equal to `'green-text'`. Now if you submit the form again and inspect the `result` element, you will see it as `<h3 class="green-text">` and notice that the text is now green. # --hints-- See description above for instructions. ```js assert( code.replace(/\s/g, '').match(/result\.className\=[\'\"\`]green-text[\'\"\`]/) ); ``` # --seed-- ## --before-user-code-- ```html <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <meta name="description" content="" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" href="styles.css" /> </head> <body> <div class="container"> <form id="calorie-form"> <h2 class="center">Calorie Counter</h2> <div class="grid"> <legend>Sex</legend> <div> <input type="radio" name="sex" id="female" value="F" checked /> <label for="female"> Female (2,000 calories) </label> <div> <input type="radio" name="sex" id="male" value="M" /> <label for="male"> Male (2,500 calories) </label> </div> </div> </div> <div class="grid" id="entries"> Breakfast <input type="number" min="0" class="cal-control" id="breakfast" /><br /> Lunch <input type="number" min="0" class="cal-control" id="lunch" /><br /> Dinner <input type="number" min="0" class="cal-control" id="dinner" /> </div> <button type="button" class="btn-add" id="add"> Add Entry </button> <button type="submit" class="btn-solid" id="calculate"> Calculate </button> <button type="button" class="btn-outline" id="clear"> Clear </button> </form> <div id="output"></div> </div> </body> </html> ``` ## --after-user-code-- ```html </body> </html> ``` ## --seed-contents-- ```html <script> document.getElementById('calorie-form').onsubmit = calculate; function calculate(e) { e.preventDefault(); const total = Array.from(document.getElementsByClassName('cal-control')) .map(meal => Number(meal.value)) .reduce((accumulator, currentValue) => accumulator + currentValue, 0); const maxCalories = document.getElementById('female').checked ? 2000 : 2500; const difference = total - maxCalories; const surplusOrDeficit = difference > 0 ? 'Surplus' : 'Deficit'; const output = document.getElementById('output'); --fcc-editable-region-- const result = document.createElement('h3'); //put your code here const resultText = document.createTextNode( `${Math.abs(difference)} Calorie ${surplusOrDeficit}` ); --fcc-editable-region-- result.appendChild(resultText); output.appendChild(result); const line = document.createElement('hr'); output.appendChild(line); const recommended = document.createElement('h4'); const recommendedText = document.createTextNode( `${maxCalories} Recommended Calories` ); recommended.appendChild(recommendedText); output.appendChild(recommended); const consumed = document.createElement('h4'); consumed.innerHTML = `${total} Consumed Calories`; output.appendChild(consumed); } </script> ``` # --solutions-- ```html <script> document.getElementById('calorie-form').onsubmit = calculate; function calculate(e) { e.preventDefault(); const total = Array.from(document.getElementsByClassName('cal-control')) .map(meal => Number(meal.value)) .reduce((accumulator, currentValue) => accumulator + currentValue, 0); const maxCalories = document.getElementById('female').checked ? 2000 : 2500; const difference = total - maxCalories; const surplusOrDeficit = difference > 0 ? 'Surplus' : 'Deficit'; const output = document.getElementById('output'); const result = document.createElement('h3'); result.className = 'green-text'; const resultText = document.createTextNode( `${Math.abs(difference)} Calorie ${surplusOrDeficit}` ); result.appendChild(resultText); output.appendChild(result); const line = document.createElement('hr'); output.appendChild(line); const recommended = document.createElement('h4'); const recommendedText = document.createTextNode( `${maxCalories} Recommended Calories` ); recommended.appendChild(recommendedText); output.appendChild(recommended); const consumed = document.createElement('h4'); consumed.innerHTML = `${total} Consumed Calories`; output.appendChild(consumed); } </script> ```
curriculum/challenges/espanol/15-javascript-algorithms-and-data-structures-22/learn-form-validation-by-building-a-calorie-counter/step-048.md
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/5973899673bed0cdcd8a960453fd63639fbcf315
[ 0.00017411779845133424, 0.00016769829380791634, 0.00016419359599240124, 0.00016762725135777146, 0.000001969281356650754 ]
{ "id": 5, "code_window": [ "You should add an `else if` clause to check is the player's `x` position is greater than or equal to the checkpoint's `x` position and less than or equal to the checkpoint's `x` position plus `40`.\n", "\n", "```js\n", "assert.match(code, /if\\s*\\(\\s*index\\s*===\\s*checkpoints\\.length\\s*-\\s*1\\s*\\)\\s*\\{\\s*isCheckpointCollisionDetectionActive\\s*=\\s*false;?\\s*showCheckpointScreen\\((\"|'|`)You reached the final checkpoint!\\1\\);?\\s*movePlayer\\(\\s*\\1ArrowRight\\1,\\s*0,\\s*false\\);?\\s*\\}\\s*else\\s*if\\s*\\(\\s*player\\.position\\.x\\s*>=\\s*checkpoint\\.position\\.x\\s*&&\\s*player\\.position\\.x\\s*<=\\s*checkpoint\\.position\\.x\\s\\+\\s*40\\s*\\)\\s*\\{\\s*/)\n", "```\n", "\n", "You should call the `showCheckpointScreen` function and pass in \"You reached a checkpoint!\" as an argument.\n", "\n", "```js\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "assert.match(code, /if\\s*\\(\\s*index\\s*===\\s*checkpoints\\.length\\s*-\\s*1\\s*\\)\\s*\\{\\s*isCheckpointCollisionDetectionActive\\s*=\\s*false;?\\s*showCheckpointScreen\\((\"|'|`)You reached the final checkpoint!\\1\\);?\\s*movePlayer\\(\\s*\\1ArrowRight\\1,\\s*0,\\s*false\\);?\\s*\\}\\s*else\\s+if\\s*\\(\\s*player\\.position\\.x\\s*>=\\s*checkpoint\\.position\\.x\\s*&&\\s*player\\.position\\.x\\s*<=\\s*checkpoint\\.position\\.x\\s\\+\\s*40\\s*\\)\\s*\\{\\s*/)\n" ], "file_path": "curriculum/challenges/english/15-javascript-algorithms-and-data-structures-22/learn-intermediate-oop-by-building-a-platformer-game/650757918a9e97418dc3d71a.md", "type": "replace", "edit_start_line_idx": 22 }
--- id: 647d821de0d97b3283c72b36 title: Step 18 challengeType: 0 dashedName: step-18 --- # --description-- Rimuovi anche la regola CSS `.box` e le sue dichiarazioni perché non ne hai più bisogno. # --hints-- Dovresti rimuovere la regola CSS `.box` e tutti i suoi valori. ```js assert.notMatch(code, /\.box\s*\{\s*width:\s*400px;\s*height:\s*600px;\s*background-color:\s*#000;\s*position:\s*absolute;\s*left:\s*650px;\s*top:\s*800px;?\s*\}\s*/) ``` # --seed-- ## --seed-contents-- ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>fCC Cat Painting</title> <link rel="stylesheet" href="./styles.css"> </head> <body> <main> <div class="cat-head"></div> </main> </body> </html> ``` ```css * { box-sizing: border-box; } body { background-color: #c9d2fc; } .cat-head { position: absolute; right: 0; left: 0; top: 0; bottom: 0; margin: auto; background: linear-gradient(#5e5e5e 85%, #45454f 100%); width: 205px; height: 180px; border: 1px solid #000; border-radius: 46%; } --fcc-editable-region-- .box { width: 400px; height: 600px; background-color: #000; position: absolute; left: 650px; top: 800px; } --fcc-editable-region-- ```
curriculum/challenges/italian/14-responsive-web-design-22/learn-intermediate-css-by-building-a-cat-painting/647d821de0d97b3283c72b36.md
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/5973899673bed0cdcd8a960453fd63639fbcf315
[ 0.00016819217125885189, 0.00016596843488514423, 0.00016381374734919518, 0.00016606133431196213, 0.0000011502929737616796 ]
{ "id": 6, "code_window": [ "```\n", "\n", "You should call the `showCheckpointScreen` function and pass in \"You reached a checkpoint!\" as an argument.\n", "\n", "```js\n", "assert.match(code, /if\\s*\\(\\s*index\\s*===\\s*checkpoints\\.length\\s*-\\s*1\\s*\\)\\s*\\{\\s*isCheckpointCollisionDetectionActive\\s*=\\s*false;?\\s*showCheckpointScreen\\((\"|'|`)You reached the final checkpoint!\\1\\);?\\s*movePlayer\\(\\s*\\1ArrowRight\\1,\\s*0,\\s*false\\);?\\s*\\}\\s*else\\s*if\\s*\\(\\s*player\\.position\\.x\\s*>=\\s*checkpoint\\.position\\.x\\s*&&\\s*player\\.position\\.x\\s*<=\\s*checkpoint\\.position\\.x\\s\\+\\s*40\\s*\\)\\s*\\{\\s*showCheckpointScreen\\(\\1You\\s+reached\\s+a\\s*checkpoint!\\1\\);?\\s*\\};?/)\n", "```\n", "\n", "# --seed--\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "assert.match(code, /if\\s*\\(\\s*index\\s*===\\s*checkpoints\\.length\\s*-\\s*1\\s*\\)\\s*\\{\\s*isCheckpointCollisionDetectionActive\\s*=\\s*false;?\\s*showCheckpointScreen\\((\"|'|`)You reached the final checkpoint!\\1\\);?\\s*movePlayer\\(\\s*\\1ArrowRight\\1,\\s*0,\\s*false\\);?\\s*\\}\\s*else\\s+if\\s*\\(\\s*player\\.position\\.x\\s*>=\\s*checkpoint\\.position\\.x\\s*&&\\s*player\\.position\\.x\\s*<=\\s*checkpoint\\.position\\.x\\s\\+\\s*40\\s*\\)\\s*\\{\\s*showCheckpointScreen\\(\\1You\\s+reached\\s+a\\s*checkpoint!\\1\\);?\\s*\\};?/)\n" ], "file_path": "curriculum/challenges/english/15-javascript-algorithms-and-data-structures-22/learn-intermediate-oop-by-building-a-platformer-game/650757918a9e97418dc3d71a.md", "type": "replace", "edit_start_line_idx": 28 }
--- id: 64c9dc4bd63a92295347c449 title: Step 76 challengeType: 0 dashedName: step-76 --- # --description-- Next, add an `else if` statement to check if the left key was pressed and if `isCheckpointCollisionDetectionActive` is true. Inside that condition, add a `forEach` loop to iterate through the `platforms` array. Inside the loop, use the addition assignment operator to add 5 to the platform's `x` position. # --hints-- You should have a condition that checks if the left key was pressed and if `isCheckpointCollisionDetectionActive` is true. ```js assert.match(code, /if\s*\(\s*keys\.rightKey\.pressed\s*&&\s*isCheckpointCollisionDetectionActive\s*\)\s*{\s*platforms\.forEach\(\s*\(platform\)\s*=>\s*{\s*platform\.position\.x\s*-=\s*5\s*;\s*}\s*\);\s*}\s*else\s+if\s*\(\s*keys\.leftKey\.pressed\s*&&\s*isCheckpointCollisionDetectionActive\s*\)\s*{.*}\s*\);?/s); ``` You should add a `forEach` loop that iterates through the `platforms` array. ```js assert.match(code, /else\sif\s*\(.*\)\s*{\s*platforms\.forEach\(\s*\(platform\)\s*=>\s*{\s*(.*?)\s*}\s*\);?/); ``` You should use the addition assignment operator to add 5 to the platform's `x` position. ```js assert.match(code, /platforms\.forEach\(\s*\(platform\)\s*=>\s*{\s*platform\.position\.x\s*\+=\s*5\s*;?\s*}\s*\);?/); ``` # --seed-- ## --seed-contents-- ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Learn Intermediate OOP by Building a Platformer Game</title> <link rel="stylesheet" href="./styles.css" /> </head> <body> <div class="start-screen"> <h1 class="main-title">freeCodeCamp Code Warrior</h1> <p class="instructions"> Help the main player navigate to the yellow checkpoints. </p> <p class="instructions"> Use the keyboard arrows to move the player around. </p> <p class="instructions">You can also use the spacebar to jump.</p> <div class="btn-container"> <button class="btn" id="start-btn">Start Game</button> </div> </div> <div class="checkpoint-screen"> <h2>Congrats!</h2> <p>You reached the last checkpoint.</p> </div> <canvas id="canvas"></canvas> <script src="./script.js"></script> </body> </html> ``` ```css * { margin: 0; padding: 0; box-sizing: border-box; } :root { --main-bg-color: #0a0a23; --section-bg-color: #ffffff; --golden-yellow: #feac32; } body { background-color: var(--main-bg-color); } .start-screen { background-color: var(--section-bg-color); width: 100%; position: absolute; top: 50%; left: 50%; margin-right: -50%; transform: translate(-50%, -50%); border-radius: 30px; padding: 20px; padding-bottom: 5px; } .main-title { text-align: center; } .instructions { text-align: center; font-size: 1.2rem; margin: 15px; line-height: 2rem; } .btn { cursor: pointer; width: 100px; margin: 10px; color: #0a0a23; font-size: 18px; background-color: var(--golden-yellow); background-image: linear-gradient(#fecc4c, #ffac33); border-color: var(--golden-yellow); border-width: 3px; } .btn:hover { background-image: linear-gradient(#ffcc4c, #f89808); } .btn-container { display: flex; align-items: center; justify-content: center; } .checkpoint-screen { position: absolute; left: 0; right: 0; margin-left: auto; margin-right: auto; width: 100%; text-align: center; background-color: var(--section-bg-color); border-radius: 20px; padding: 10px; display: none; } #canvas { display: none; } @media (min-width: 768px) { .start-screen { width: 60%; max-width: 700px; } .checkpoint-screen { max-width: 300px; } } ``` ```js const startBtn = document.getElementById("start-btn"); const canvas = document.getElementById("canvas"); const startScreen = document.querySelector(".start-screen"); const checkpointScreen = document.querySelector(".checkpoint-screen"); const checkpointMessage = document.querySelector(".checkpoint-screen > p"); const ctx = canvas.getContext("2d"); canvas.width = innerWidth; canvas.height = innerHeight; const gravity = 0.5; let isCheckpointCollisionDetectionActive = true; class Player { constructor() { this.position = { x: 10, y: 400, }; this.velocity = { x: 0, y: 0, }; this.width = 40; this.height = 40; } draw() { ctx.fillStyle = "#99c9ff"; ctx.fillRect(this.position.x, this.position.y, this.width, this.height); } update() { this.draw(); this.position.x += this.velocity.x; this.position.y += this.velocity.y; if (this.position.y + this.height + this.velocity.y <= canvas.height) { if (this.position.y < 0) { this.position.y = 0; this.velocity.y = gravity; } this.velocity.y += gravity; } else { this.velocity.y = 0; } if (this.position.x < this.width) { this.position.x = this.width; } } } class Platform { constructor(x, y) { this.position = { x, y, }; this.width = 200; this.height = 40; } draw() { ctx.fillStyle = "#acd157"; ctx.fillRect(this.position.x, this.position.y, this.width, this.height); } } const player = new Player(); const platformPositions = [ { x: 500, y: 450 }, { x: 700, y: 400 }, { x: 850, y: 350 }, { x: 900, y: 350 }, { x: 1050, y: 150 }, { x: 2500, y: 450 }, { x: 2900, y: 400 }, { x: 3150, y: 350 }, { x: 3900, y: 450 }, { x: 4200, y: 400 }, { x: 4400, y: 200 }, { x: 4700, y: 150 } ]; const platforms = platformPositions.map( (platform) => new Platform(platform.x, platform.y) ); const animate = () => { requestAnimationFrame(animate); ctx.clearRect(0, 0, canvas.width, canvas.height); platforms.forEach((platform) => { platform.draw(); }); player.update(); if (keys.rightKey.pressed && player.position.x < 400) { player.velocity.x = 5; } else if (keys.leftKey.pressed && player.position.x > 100) { player.velocity.x = -5; } else { player.velocity.x = 0; --fcc-editable-region-- if (keys.rightKey.pressed && isCheckpointCollisionDetectionActive) { platforms.forEach((platform) => { platform.position.x -= 5; }); } --fcc-editable-region-- } } const keys = { rightKey: { pressed: false }, leftKey: { pressed: false } }; const movePlayer = (key, xVelocity, isPressed) => { if (!isCheckpointCollisionDetectionActive) { player.velocity.x = 0; player.velocity.y = 0; return; } switch (key) { case "ArrowLeft": keys.leftKey.pressed = isPressed; if (xVelocity === 0) { player.velocity.x = xVelocity; } player.velocity.x -= xVelocity; break; case "ArrowUp": case " ": case "Spacebar": player.velocity.y -= 8; break; case "ArrowRight": keys.rightKey.pressed = isPressed; if (xVelocity === 0) { player.velocity.x = xVelocity; } player.velocity.x += xVelocity; } } const startGame = () => { canvas.style.display = "block"; startScreen.style.display = "none"; animate(); } startBtn.addEventListener("click", startGame); window.addEventListener("keydown", ({ key }) => { movePlayer(key, 8, true); }); window.addEventListener("keyup", ({ key }) => { movePlayer(key, 0, false); }); ```
curriculum/challenges/english/15-javascript-algorithms-and-data-structures-22/learn-intermediate-oop-by-building-a-platformer-game/64c9dc4bd63a92295347c449.md
1
https://github.com/freeCodeCamp/freeCodeCamp/commit/5973899673bed0cdcd8a960453fd63639fbcf315
[ 0.012849199585616589, 0.0009738212102092803, 0.00016443582717329264, 0.0001701364672044292, 0.002231780905276537 ]
{ "id": 6, "code_window": [ "```\n", "\n", "You should call the `showCheckpointScreen` function and pass in \"You reached a checkpoint!\" as an argument.\n", "\n", "```js\n", "assert.match(code, /if\\s*\\(\\s*index\\s*===\\s*checkpoints\\.length\\s*-\\s*1\\s*\\)\\s*\\{\\s*isCheckpointCollisionDetectionActive\\s*=\\s*false;?\\s*showCheckpointScreen\\((\"|'|`)You reached the final checkpoint!\\1\\);?\\s*movePlayer\\(\\s*\\1ArrowRight\\1,\\s*0,\\s*false\\);?\\s*\\}\\s*else\\s*if\\s*\\(\\s*player\\.position\\.x\\s*>=\\s*checkpoint\\.position\\.x\\s*&&\\s*player\\.position\\.x\\s*<=\\s*checkpoint\\.position\\.x\\s\\+\\s*40\\s*\\)\\s*\\{\\s*showCheckpointScreen\\(\\1You\\s+reached\\s+a\\s*checkpoint!\\1\\);?\\s*\\};?/)\n", "```\n", "\n", "# --seed--\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "assert.match(code, /if\\s*\\(\\s*index\\s*===\\s*checkpoints\\.length\\s*-\\s*1\\s*\\)\\s*\\{\\s*isCheckpointCollisionDetectionActive\\s*=\\s*false;?\\s*showCheckpointScreen\\((\"|'|`)You reached the final checkpoint!\\1\\);?\\s*movePlayer\\(\\s*\\1ArrowRight\\1,\\s*0,\\s*false\\);?\\s*\\}\\s*else\\s+if\\s*\\(\\s*player\\.position\\.x\\s*>=\\s*checkpoint\\.position\\.x\\s*&&\\s*player\\.position\\.x\\s*<=\\s*checkpoint\\.position\\.x\\s\\+\\s*40\\s*\\)\\s*\\{\\s*showCheckpointScreen\\(\\1You\\s+reached\\s+a\\s*checkpoint!\\1\\);?\\s*\\};?/)\n" ], "file_path": "curriculum/challenges/english/15-javascript-algorithms-and-data-structures-22/learn-intermediate-oop-by-building-a-platformer-game/650757918a9e97418dc3d71a.md", "type": "replace", "edit_start_line_idx": 28 }
--- id: 657e5171f6746eadc5c6411f title: Task 80 challengeType: 19 dashedName: task-80 audioPath: curriculum/js-music-player/We-Are-Going-to-Make-it.mp3 --- <!-- (audio) James: Hey, Linda. Today, I want to talk to you about compliance and the obligations we have in our daily tasks. --> # --description-- Listen to the audio to answer the question below. # --question-- ## --text-- What is James planning to discuss with Linda? ## --answers-- Planning a holiday. ### --feedback-- James's discussion is about work, not holidays. --- Personal weekend plans. ### --feedback-- It focuses on job responsibilities, not personal plans. --- Going out for lunch. ### --feedback-- The conversation is about work duties, not lunch. --- Compliance and obligations. ## --video-solution-- 4
curriculum/challenges/japanese/21-a2-english-for-developers/learn-how-to-talk-about-a-typical-workday-and-tasks/657e5171f6746eadc5c6411f.md
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/5973899673bed0cdcd8a960453fd63639fbcf315
[ 0.00017255872080568224, 0.00017088413005694747, 0.00016960615175776184, 0.00017081599798984826, 0.0000011205144119230681 ]
{ "id": 6, "code_window": [ "```\n", "\n", "You should call the `showCheckpointScreen` function and pass in \"You reached a checkpoint!\" as an argument.\n", "\n", "```js\n", "assert.match(code, /if\\s*\\(\\s*index\\s*===\\s*checkpoints\\.length\\s*-\\s*1\\s*\\)\\s*\\{\\s*isCheckpointCollisionDetectionActive\\s*=\\s*false;?\\s*showCheckpointScreen\\((\"|'|`)You reached the final checkpoint!\\1\\);?\\s*movePlayer\\(\\s*\\1ArrowRight\\1,\\s*0,\\s*false\\);?\\s*\\}\\s*else\\s*if\\s*\\(\\s*player\\.position\\.x\\s*>=\\s*checkpoint\\.position\\.x\\s*&&\\s*player\\.position\\.x\\s*<=\\s*checkpoint\\.position\\.x\\s\\+\\s*40\\s*\\)\\s*\\{\\s*showCheckpointScreen\\(\\1You\\s+reached\\s+a\\s*checkpoint!\\1\\);?\\s*\\};?/)\n", "```\n", "\n", "# --seed--\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "assert.match(code, /if\\s*\\(\\s*index\\s*===\\s*checkpoints\\.length\\s*-\\s*1\\s*\\)\\s*\\{\\s*isCheckpointCollisionDetectionActive\\s*=\\s*false;?\\s*showCheckpointScreen\\((\"|'|`)You reached the final checkpoint!\\1\\);?\\s*movePlayer\\(\\s*\\1ArrowRight\\1,\\s*0,\\s*false\\);?\\s*\\}\\s*else\\s+if\\s*\\(\\s*player\\.position\\.x\\s*>=\\s*checkpoint\\.position\\.x\\s*&&\\s*player\\.position\\.x\\s*<=\\s*checkpoint\\.position\\.x\\s\\+\\s*40\\s*\\)\\s*\\{\\s*showCheckpointScreen\\(\\1You\\s+reached\\s+a\\s*checkpoint!\\1\\);?\\s*\\};?/)\n" ], "file_path": "curriculum/challenges/english/15-javascript-algorithms-and-data-structures-22/learn-intermediate-oop-by-building-a-platformer-game/650757918a9e97418dc3d71a.md", "type": "replace", "edit_start_line_idx": 28 }
--- id: 646f0f7c5933560af8e7e380 title: Hatua ya 67 challengeType: 0 dashedName: step-67 --- # --description-- Ndani ya kipengele cha `.cat-whiskers-left`, unda vipengele vitatu vya `div` ukitumia madarasa ya `cat-whisker-left-top`, `cat-whisker-left-middle` na `cat-whisker-left-bottom`. # --hints-- Hupaswi kubadilisha kipengele cha `div` kilichopo na darasa la `cat-whiskers-left`. ```js assert(document.querySelectorAll('div.cat-whiskers-left').length === 1) ``` Unapaswa kuunda vipengele vitatu vya `div` ndani ya kipengele chako cha `.cat-whiskers-left`. ```js assert(document.querySelectorAll('.cat-whiskers-left div').length === 3) ``` Kipengele cha kwanza cha `div` ndani ya kipengee cha `.cat-whiskers-left` kinapaswa kuwa na darasa la `cat-whisker-left-top`. ```js assert(document.querySelectorAll('.cat-whiskers-left div')[0].classList.contains('cat-whisker-left-top')) ``` Kipengele cha pili cha `div` ndani ya kipengee cha `.cat-whiskers-left` kinapaswa kuwa na darasa la `cat-whisker-left-middle`. ```js assert(document.querySelectorAll('.cat-whiskers-left div')[1].classList.contains('cat-whisker-left-middle')) ``` Kipengele cha tatu cha `div` ndani ya kipengee cha `.cat-whiskers-left` kinapaswa kuwa na darasa la `cat-whisker-left-bottom`. ```js assert(document.querySelectorAll('.cat-whiskers-left div')[2].classList.contains('cat-whisker-left-bottom')) ``` # --seed-- ## --seed-contents-- ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>fCC Cat Painting</title> <link rel="stylesheet" href="./styles.css"> </head> <body> <main> <div class="cat-head"> <div class="cat-ears"> <div class="cat-left-ear"> <div class="cat-left-inner-ear"></div> </div> <div class="cat-right-ear"> <div class="cat-right-inner-ear"></div> </div> </div> <div class="cat-eyes"> <div class="cat-left-eye"> <div class="cat-left-inner-eye"></div> </div> <div class="cat-right-eye"> <div class="cat-right-inner-eye"></div> </div> </div> <div class="cat-nose"></div> <div class="cat-mouth"> <div class="cat-mouth-line-left"></div> <div class="cat-mouth-line-right"></div> </div> <div class="cat-whiskers"> --fcc-editable-region-- <div class="cat-whiskers-left"> </div> --fcc-editable-region-- <div class="cat-whiskers-right"></div> </div> </div> </main> </body> </html> ``` ```css * { box-sizing: border-box; } body { background-color: #c9d2fc; } .cat-head { position: absolute; right: 0; left: 0; top: 0; bottom: 0; margin: auto; background: linear-gradient(#5e5e5e 85%, #45454f 100%); width: 205px; height: 180px; border: 1px solid #000; border-radius: 46%; } .cat-left-ear { position: absolute; top: -26px; left: -31px; z-index: 1; border-top-left-radius: 90px; border-top-right-radius: 10px; transform: rotate(-45deg); border-left: 35px solid transparent; border-right: 35px solid transparent; border-bottom: 70px solid #5e5e5e; } .cat-right-ear { position: absolute; top: -26px; left: 163px; z-index: 1; transform: rotate(45deg); border-top-left-radius: 90px; border-top-right-radius: 10px; border-left: 35px solid transparent; border-right: 35px solid transparent; border-bottom: 70px solid #5e5e5e; } .cat-left-inner-ear { position: absolute; top: 22px; left: -20px; border-top-left-radius: 90px; border-top-right-radius: 10px; border-bottom-right-radius: 40%; border-bottom-left-radius: 40%; border-left: 20px solid transparent; border-right: 20px solid transparent; border-bottom: 40px solid #3b3b4f; } .cat-right-inner-ear { position: absolute; top: 22px; left: -20px; border-top-left-radius: 90px; border-top-right-radius: 10px; border-bottom-right-radius: 40%; border-bottom-left-radius: 40%; border-left: 20px solid transparent; border-right: 20px solid transparent; border-bottom: 40px solid #3b3b4f; } .cat-left-eye { position: absolute; top: 54px; left: 39px; border-radius: 60%; transform: rotate(25deg); width: 30px; height: 40px; background-color: #000; } .cat-right-eye { position: absolute; top: 54px; left: 134px; border-radius: 60%; transform: rotate(-25deg); width: 30px; height: 40px; background-color: #000; } .cat-left-inner-eye { position: absolute; top: 8px; left: 2px; width: 10px; height: 20px; transform: rotate(10deg); background-color: #fff; border-radius: 60%; } .cat-right-inner-eye { position: absolute; top: 8px; left: 18px; transform: rotate(-5deg); width: 10px; height: 20px; background-color: #fff; border-radius: 60%; } .cat-nose { position: absolute; top: 108px; left: 85px; border-top-left-radius: 50%; border-bottom-right-radius: 50%; border-bottom-left-radius: 50%; transform: rotate(180deg); border-left: 15px solid transparent; border-right: 15px solid transparent; border-bottom: 20px solid #442c2c; } .cat-mouth div { width: 30px; height: 50px; border: 2px solid #000; border-radius: 190%/190px 150px 0 0; border-color: black transparent transparent transparent; } .cat-mouth-line-left { position: absolute; top: 88px; left: 74px; transform: rotate(170deg); } .cat-mouth-line-right { position: absolute; top: 88px; left: 91px; transform: rotate(165deg); } ```
curriculum/challenges/swahili/14-responsive-web-design-22/learn-intermediate-css-by-building-a-cat-painting/646f0f7c5933560af8e7e380.md
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/5973899673bed0cdcd8a960453fd63639fbcf315
[ 0.00018087332136929035, 0.00016911685816012323, 0.00016478645557072014, 0.00016921490896493196, 0.0000032803045542095788 ]
{ "id": 6, "code_window": [ "```\n", "\n", "You should call the `showCheckpointScreen` function and pass in \"You reached a checkpoint!\" as an argument.\n", "\n", "```js\n", "assert.match(code, /if\\s*\\(\\s*index\\s*===\\s*checkpoints\\.length\\s*-\\s*1\\s*\\)\\s*\\{\\s*isCheckpointCollisionDetectionActive\\s*=\\s*false;?\\s*showCheckpointScreen\\((\"|'|`)You reached the final checkpoint!\\1\\);?\\s*movePlayer\\(\\s*\\1ArrowRight\\1,\\s*0,\\s*false\\);?\\s*\\}\\s*else\\s*if\\s*\\(\\s*player\\.position\\.x\\s*>=\\s*checkpoint\\.position\\.x\\s*&&\\s*player\\.position\\.x\\s*<=\\s*checkpoint\\.position\\.x\\s\\+\\s*40\\s*\\)\\s*\\{\\s*showCheckpointScreen\\(\\1You\\s+reached\\s+a\\s*checkpoint!\\1\\);?\\s*\\};?/)\n", "```\n", "\n", "# --seed--\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "assert.match(code, /if\\s*\\(\\s*index\\s*===\\s*checkpoints\\.length\\s*-\\s*1\\s*\\)\\s*\\{\\s*isCheckpointCollisionDetectionActive\\s*=\\s*false;?\\s*showCheckpointScreen\\((\"|'|`)You reached the final checkpoint!\\1\\);?\\s*movePlayer\\(\\s*\\1ArrowRight\\1,\\s*0,\\s*false\\);?\\s*\\}\\s*else\\s+if\\s*\\(\\s*player\\.position\\.x\\s*>=\\s*checkpoint\\.position\\.x\\s*&&\\s*player\\.position\\.x\\s*<=\\s*checkpoint\\.position\\.x\\s\\+\\s*40\\s*\\)\\s*\\{\\s*showCheckpointScreen\\(\\1You\\s+reached\\s+a\\s*checkpoint!\\1\\);?\\s*\\};?/)\n" ], "file_path": "curriculum/challenges/english/15-javascript-algorithms-and-data-structures-22/learn-intermediate-oop-by-building-a-platformer-game/650757918a9e97418dc3d71a.md", "type": "replace", "edit_start_line_idx": 28 }
--- id: 5d792539b2e0bd8f9e8213e4 title: Step 133 challengeType: 0 dashedName: step-133 --- # --description-- Use the ternary operator to return `average([sorted[middle], sorted[middle + 1]])` if `length` is even, and `sorted[middle + 0.5]` otherwise. Note that the `middle` variable is close to the middle but is not actually the middle. # --hints-- See description above for instructions. ```js assert(median([1, 20, 3]) === 3 && median([27, 7, 20, 10]) === 15); ``` # --seed-- ## --before-user-code-- ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Spreadsheet</title> <style> #container { display: grid; grid-template-columns: 50px repeat(10, 200px); grid-template-rows: repeat(11, 30px); } .label { background-color: lightgray; text-align: center; vertical-align: middle; line-height: 30px; } </style> </head> <body> <div id="container"> <div></div> </div> ``` ## --after-user-code-- ```html </body> </html> ``` ## --seed-contents-- ```html <script> const infixToFunction = { "+": (x, y) => x + y, "-": (x, y) => x - y, "*": (x, y) => x * y, "/": (x, y) => x / y }; const infixEval = (str, regex) => str.replace(regex, (_, arg1, fn, arg2) => infixToFunction[fn](parseFloat(arg1), parseFloat(arg2)) ); const highPrecedence = str => { const regex = /([0-9.]+)([*\/])([0-9.]+)/; const str2 = infixEval(str, regex); return str === str2 ? str : highPrecedence(str2); }; const isEven = num => num % 2 === 0; const sum = nums => nums.reduce((a, x) => a + x); const average = nums => sum(nums) / nums.length; --fcc-editable-region-- const median = nums => { const sorted = nums.slice().sort((x, y) => x - y); const length = sorted.length; const middle = sorted.length / 2 - 1; return isEven(length); }; --fcc-editable-region-- const spreadsheetFunctions = { "": x => x, random: ([x, y]) => Math.floor(Math.random() * y + x), increment: nums => nums.map(x => x + 1), firsttwo: arr => arr.slice(0, 2), lasttwo: arr => arr.slice(-2), even: nums => nums.filter(isEven), sum, average, has2: arr => arr.includes(2), nodups: arr => arr.reduce((a, x) => a.includes(x) ? a : a.concat(x), []), range: arr => range(...arr) }; const applyFn = str => { const noHigh = highPrecedence(str); const infix = /([0-9.]+)([+-])([0-9.]+)/; const str2 = infixEval(noHigh, infix); const regex = /([a-z]*)\(([0-9., ]*)\)(?!.*\()/i; const toNumberList = args => args.split(",").map(parseFloat); const applyFunction = (fn, args) => spreadsheetFunctions[fn.toLowerCase()](toNumberList(args)); return str2.replace( regex, (match, fn, args) => spreadsheetFunctions.hasOwnProperty(fn.toLowerCase()) ? applyFunction(fn, args) : match ); }; const range = (start, end) => start > end ? [] : [start].concat(range(start + 1, end)); const charRange = (start, end) => range(start.charCodeAt(0), end.charCodeAt(0)).map(x => String.fromCharCode(x) ); const evalFormula = (x, cells) => { const idToText = id => cells.find(cell => cell.id === id).value; const rangeRegex = /([A-J])([1-9][0-9]?):([A-J])([1-9][0-9]?)/gi; const rangeFromString = (n1, n2) => range(parseInt(n1), parseInt(n2)); const elemValue = n => c => idToText(c + n); const addChars = c1 => c2 => n => charRange(c1, c2).map(elemValue(n)); const varRangeExpanded = x.replace(rangeRegex, (_, c1, n1, c2, n2) => rangeFromString(n1, n2).map(addChars(c1)(c2)) ); const varRegex = /[A-J][1-9][0-9]?/gi; const varExpanded = varRangeExpanded.replace( varRegex, match => idToText(match.toUpperCase()) ); const functionExpanded = applyFn(varExpanded); return functionExpanded === x ? functionExpanded : evalFormula(functionExpanded, cells); }; window.onload = () => { const container = document.getElementById("container"); const createLabel = name => { const label = document.createElement("div"); label.className = "label"; label.textContent = name; container.appendChild(label); }; const letters = charRange("A", "J"); letters.forEach(createLabel); range(1, 99).forEach(x => { createLabel(x); letters.forEach(y => { const input = document.createElement("input"); input.type = "text"; input.id = y + x; input.onchange = update; container.appendChild(input); }); }); }; const update = event => { const element = event.target; const value = element.value.replace(/\s/g, ""); if (!value.includes(element.id) && value[0] === "=") { element.value = evalFormula( value.slice(1), Array.from(document.getElementById("container").children) ); } }; </script> ``` # --solutions-- ```html <script> const infixToFunction = { "+": (x, y) => x + y, "-": (x, y) => x - y, "*": (x, y) => x * y, "/": (x, y) => x / y }; const infixEval = (str, regex) => str.replace(regex, (_, arg1, fn, arg2) => infixToFunction[fn](parseFloat(arg1), parseFloat(arg2)) ); const highPrecedence = str => { const regex = /([0-9.]+)([*\/])([0-9.]+)/; const str2 = infixEval(str, regex); return str === str2 ? str : highPrecedence(str2); }; const isEven = num => num % 2 === 0; const sum = nums => nums.reduce((a, x) => a + x); const average = nums => sum(nums) / nums.length; const median = nums => { const sorted = nums.slice().sort((x, y) => x - y); const length = sorted.length; const middle = sorted.length / 2 - 1; return isEven(length) ? average([sorted[middle], sorted[middle + 1]]) : sorted[middle + 0.5]; }; const spreadsheetFunctions = { "": x => x, random: ([x, y]) => Math.floor(Math.random() * y + x), increment: nums => nums.map(x => x + 1), firsttwo: arr => arr.slice(0, 2), lasttwo: arr => arr.slice(-2), even: nums => nums.filter(isEven), sum, average, has2: arr => arr.includes(2), nodups: arr => arr.reduce((a, x) => a.includes(x) ? a : a.concat(x), []), range: arr => range(...arr) }; const applyFn = str => { const noHigh = highPrecedence(str); const infix = /([0-9.]+)([+-])([0-9.]+)/; const str2 = infixEval(noHigh, infix); const regex = /([a-z]*)\(([0-9., ]*)\)(?!.*\()/i; const toNumberList = args => args.split(",").map(parseFloat); const applyFunction = (fn, args) => spreadsheetFunctions[fn.toLowerCase()](toNumberList(args)); return str2.replace( regex, (match, fn, args) => spreadsheetFunctions.hasOwnProperty(fn.toLowerCase()) ? applyFunction(fn, args) : match ); }; const range = (start, end) => start > end ? [] : [start].concat(range(start + 1, end)); const charRange = (start, end) => range(start.charCodeAt(0), end.charCodeAt(0)).map(x => String.fromCharCode(x) ); const evalFormula = (x, cells) => { const idToText = id => cells.find(cell => cell.id === id).value; const rangeRegex = /([A-J])([1-9][0-9]?):([A-J])([1-9][0-9]?)/gi; const rangeFromString = (n1, n2) => range(parseInt(n1), parseInt(n2)); const elemValue = n => c => idToText(c + n); const addChars = c1 => c2 => n => charRange(c1, c2).map(elemValue(n)); const varRangeExpanded = x.replace(rangeRegex, (_, c1, n1, c2, n2) => rangeFromString(n1, n2).map(addChars(c1)(c2)) ); const varRegex = /[A-J][1-9][0-9]?/gi; const varExpanded = varRangeExpanded.replace( varRegex, match => idToText(match.toUpperCase()) ); const functionExpanded = applyFn(varExpanded); return functionExpanded === x ? functionExpanded : evalFormula(functionExpanded, cells); }; window.onload = () => { const container = document.getElementById("container"); const createLabel = name => { const label = document.createElement("div"); label.className = "label"; label.textContent = name; container.appendChild(label); }; const letters = charRange("A", "J"); letters.forEach(createLabel); range(1, 99).forEach(x => { createLabel(x); letters.forEach(y => { const input = document.createElement("input"); input.type = "text"; input.id = y + x; input.onchange = update; container.appendChild(input); }); }); }; const update = event => { const element = event.target; const value = element.value.replace(/\s/g, ""); if (!value.includes(element.id) && value[0] === "=") { element.value = evalFormula( value.slice(1), Array.from(document.getElementById("container").children) ); } }; </script> ```
curriculum/challenges/italian/15-javascript-algorithms-and-data-structures-22/learn-functional-programming-by-building-a-spreadsheet/step-133.md
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/5973899673bed0cdcd8a960453fd63639fbcf315
[ 0.00017337674216832966, 0.00016892235726118088, 0.00016378141299355775, 0.0001696698018349707, 0.0000028523802484414773 ]
{ "id": 0, "code_window": [ " alignmentPeriod: 'cloud-monitoring-auto',\n", " aliasBy: '',\n", " selectorName: 'select_slo_health',\n", " serviceId: '',\n", " sloId: '',\n" ], "labels": [ "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " serviceName: '',\n" ], "file_path": "public/app/plugins/datasource/cloud-monitoring/components/SLOQueryEditor.tsx", "type": "add", "edit_start_line_idx": 23 }
import React from 'react'; import { Segment, SegmentAsync } from '@grafana/ui'; import { SelectableValue } from '@grafana/data'; import { selectors } from '../constants'; import { Project, AlignmentPeriods, AliasBy, QueryInlineField } from '.'; import { SLOQuery } from '../types'; import CloudMonitoringDatasource from '../datasource'; export interface Props { usedAlignmentPeriod?: number; variableOptionGroup: SelectableValue<string>; onChange: (query: SLOQuery) => void; onRunQuery: () => void; query: SLOQuery; datasource: CloudMonitoringDatasource; } export const defaultQuery: (dataSource: CloudMonitoringDatasource) => SLOQuery = (dataSource) => ({ projectName: dataSource.getDefaultProject(), alignmentPeriod: 'cloud-monitoring-auto', aliasBy: '', selectorName: 'select_slo_health', serviceId: '', sloId: '', }); export function SLOQueryEditor({ query, datasource, onChange, variableOptionGroup, usedAlignmentPeriod, }: React.PropsWithChildren<Props>) { return ( <> <Project templateVariableOptions={variableOptionGroup.options} projectName={query.projectName} datasource={datasource} onChange={(projectName) => onChange({ ...query, projectName })} /> <QueryInlineField label="Service"> <SegmentAsync allowCustomValue value={query?.serviceId} placeholder="Select service" loadOptions={() => datasource.getSLOServices(query.projectName).then((services) => [ { label: 'Template Variables', options: variableOptionGroup.options, }, ...services, ]) } onChange={({ value: serviceId = '' }) => onChange({ ...query, serviceId, sloId: '' })} /> </QueryInlineField> <QueryInlineField label="SLO"> <SegmentAsync allowCustomValue value={query?.sloId} placeholder="Select SLO" loadOptions={() => datasource.getServiceLevelObjectives(query.projectName, query.serviceId).then((sloIds) => [ { label: 'Template Variables', options: variableOptionGroup.options, }, ...sloIds, ]) } onChange={async ({ value: sloId = '' }) => { const slos = await datasource.getServiceLevelObjectives(query.projectName, query.serviceId); const slo = slos.find(({ value }) => value === datasource.templateSrv.replace(sloId)); onChange({ ...query, sloId, goal: slo?.goal }); }} /> </QueryInlineField> <QueryInlineField label="Selector"> <Segment allowCustomValue value={[...selectors, ...variableOptionGroup.options].find((s) => s.value === query?.selectorName ?? '')} options={[ { label: 'Template Variables', options: variableOptionGroup.options, }, ...selectors, ]} onChange={({ value: selectorName }) => onChange({ ...query, selectorName })} /> </QueryInlineField> <AlignmentPeriods templateSrv={datasource.templateSrv} templateVariableOptions={variableOptionGroup.options} alignmentPeriod={query.alignmentPeriod || ''} perSeriesAligner={query.selectorName === 'select_slo_health' ? 'ALIGN_MEAN' : 'ALIGN_NEXT_OLDER'} usedAlignmentPeriod={usedAlignmentPeriod} onChange={(alignmentPeriod) => onChange({ ...query, alignmentPeriod })} /> <AliasBy value={query.aliasBy} onChange={(aliasBy) => onChange({ ...query, aliasBy })} /> </> ); }
public/app/plugins/datasource/cloud-monitoring/components/SLOQueryEditor.tsx
1
https://github.com/grafana/grafana/commit/ae64dcf0638e1b860dd3e56cdd97abb7c90833c0
[ 0.08614535629749298, 0.011598917655646801, 0.0001647622702876106, 0.0002609366783872247, 0.02471734583377838 ]
{ "id": 0, "code_window": [ " alignmentPeriod: 'cloud-monitoring-auto',\n", " aliasBy: '',\n", " selectorName: 'select_slo_health',\n", " serviceId: '',\n", " sloId: '',\n" ], "labels": [ "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " serviceName: '',\n" ], "file_path": "public/app/plugins/datasource/cloud-monitoring/components/SLOQueryEditor.tsx", "type": "add", "edit_start_line_idx": 23 }
import React, { PureComponent } from 'react'; import { AnnotationEventMappings, DataQuery, LoadingState, DataSourceApi, AnnotationQuery } from '@grafana/data'; import { Spinner, Icon, IconName, Button } from '@grafana/ui'; import { getDashboardSrv } from 'app/features/dashboard/services/DashboardSrv'; import { getTimeSrv } from 'app/features/dashboard/services/TimeSrv'; import { cx, css } from 'emotion'; import { standardAnnotationSupport } from '../standardAnnotationSupport'; import { executeAnnotationQuery } from '../annotations_srv'; import { PanelModel } from 'app/features/dashboard/state'; import { AnnotationQueryResponse } from '../types'; import { AnnotationFieldMapper } from './AnnotationResultMapper'; import coreModule from 'app/core/core_module'; interface Props { datasource: DataSourceApi; annotation: AnnotationQuery<DataQuery>; change: (annotation: AnnotationQuery<DataQuery>) => void; } interface State { running?: boolean; response?: AnnotationQueryResponse; } export default class StandardAnnotationQueryEditor extends PureComponent<Props, State> { state = {} as State; componentDidMount() { this.verifyDataSource(); } componentDidUpdate(oldProps: Props) { if (this.props.annotation !== oldProps.annotation) { this.verifyDataSource(); } } verifyDataSource() { const { datasource, annotation } = this.props; // Handle any migration issues const processor = { ...standardAnnotationSupport, ...datasource.annotations, }; const fixed = processor.prepareAnnotation!(annotation); if (fixed !== annotation) { this.props.change(fixed); } else { this.onRunQuery(); } } onRunQuery = async () => { const { datasource, annotation } = this.props; this.setState({ running: true, }); const response = await executeAnnotationQuery( { range: getTimeSrv().timeRange(), panel: {} as PanelModel, dashboard: getDashboardSrv().getCurrent(), }, datasource, annotation ).toPromise(); this.setState({ running: false, response, }); }; onQueryChange = (target: DataQuery) => { this.props.change({ ...this.props.annotation, target, }); }; onMappingChange = (mappings: AnnotationEventMappings) => { this.props.change({ ...this.props.annotation, mappings, }); }; renderStatus() { const { response, running } = this.state; let rowStyle = 'alert-info'; let text = '...'; let icon: IconName | undefined = undefined; if (running || response?.panelData?.state === LoadingState.Loading || !response) { text = 'loading...'; } else { const { events, panelData } = response; if (panelData?.error) { rowStyle = 'alert-error'; icon = 'exclamation-triangle'; text = panelData.error.message ?? 'error'; } else if (!events?.length) { rowStyle = 'alert-warning'; icon = 'exclamation-triangle'; text = 'No events found'; } else { const frame = panelData?.series[0]; text = `${events.length} events (from ${frame?.fields.length} fields)`; } } return ( <div className={cx( rowStyle, css` margin: 4px 0px; padding: 4px; display: flex; justify-content: space-between; align-items: center; ` )} > <div> {icon && ( <> <Icon name={icon} /> &nbsp; </> )} {text} </div> <div> {running ? ( <Spinner /> ) : ( <Button variant="secondary" size="xs" onClick={this.onRunQuery}> TEST </Button> )} </div> </div> ); } render() { const { datasource, annotation } = this.props; const { response } = this.state; // Find the annotaiton runner let QueryEditor = datasource.annotations?.QueryEditor || datasource.components?.QueryEditor; if (!QueryEditor) { return <div>Annotations are not supported. This datasource needs to export a QueryEditor</div>; } const query = annotation.target ?? { refId: 'Anno' }; return ( <> <QueryEditor key={datasource?.name} query={query} datasource={datasource} onChange={this.onQueryChange} onRunQuery={this.onRunQuery} data={response?.panelData} range={getTimeSrv().timeRange()} /> {this.renderStatus()} <AnnotationFieldMapper response={response} mappings={annotation.mappings} change={this.onMappingChange} /> <br /> </> ); } } // Careful to use a unique directive name! many plugins already use "annotationEditor" and have conflicts coreModule.directive('standardAnnotationEditor', [ 'reactDirective', (reactDirective: any) => { return reactDirective(StandardAnnotationQueryEditor, ['annotation', 'datasource', 'change']); }, ]);
public/app/features/annotations/components/StandardAnnotationQueryEditor.tsx
0
https://github.com/grafana/grafana/commit/ae64dcf0638e1b860dd3e56cdd97abb7c90833c0
[ 0.00017621894949115813, 0.00017193774692714214, 0.00016482779756188393, 0.00017226807540282607, 0.0000025838264718913706 ]
{ "id": 0, "code_window": [ " alignmentPeriod: 'cloud-monitoring-auto',\n", " aliasBy: '',\n", " selectorName: 'select_slo_health',\n", " serviceId: '',\n", " sloId: '',\n" ], "labels": [ "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " serviceName: '',\n" ], "file_path": "public/app/plugins/datasource/cloud-monitoring/components/SLOQueryEditor.tsx", "type": "add", "edit_start_line_idx": 23 }
package opentsdb type OpenTsdbQuery struct { Start int64 `json:"start"` End int64 `json:"end"` Queries []map[string]interface{} `json:"queries"` } type OpenTsdbResponse struct { Metric string `json:"metric"` DataPoints map[string]float64 `json:"dps"` }
pkg/tsdb/opentsdb/types.go
0
https://github.com/grafana/grafana/commit/ae64dcf0638e1b860dd3e56cdd97abb7c90833c0
[ 0.00019748814520426095, 0.00018370067118667066, 0.0001699132117209956, 0.00018370067118667066, 0.00001378746674163267 ]
{ "id": 0, "code_window": [ " alignmentPeriod: 'cloud-monitoring-auto',\n", " aliasBy: '',\n", " selectorName: 'select_slo_health',\n", " serviceId: '',\n", " sloId: '',\n" ], "labels": [ "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " serviceName: '',\n" ], "file_path": "public/app/plugins/datasource/cloud-monitoring/components/SLOQueryEditor.tsx", "type": "add", "edit_start_line_idx": 23 }
import React, { FunctionComponent } from 'react'; import { SvgProps } from './types'; export const HeartBreak: FunctionComponent<SvgProps> = ({ size, ...rest }) => { return ( <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width={size} height={size} {...rest}> <g id="Layer_2" data-name="Layer 2"> <g id="Layer_1-2" data-name="Layer 1"> <path d="M18.17,1.85h0A6.25,6.25,0,0,0,12.12.23L9.42,6.56l2.83.71a1,1,0,0,1,.67,1.41l-2,4a1,1,0,0,1-.9.56,1.13,1.13,0,0,1-.44-.1h0a1,1,0,0,1-.46-1.33l1.4-2.89-2.77-.7a1,1,0,0,1-.65-.53,1,1,0,0,1,0-.83L9.58,1a6.27,6.27,0,0,0-7.73,9.77L9.3,18.18a1,1,0,0,0,1.42,0h0l7.45-7.46A6.27,6.27,0,0,0,18.17,1.85Z" /> </g> </g> </svg> ); };
packages/grafana-ui/src/components/Icon/assets/HeartBreak.tsx
0
https://github.com/grafana/grafana/commit/ae64dcf0638e1b860dd3e56cdd97abb7c90833c0
[ 0.00017653308168519288, 0.00017299751925747842, 0.00016946195682976395, 0.00017299751925747842, 0.000003535562427714467 ]
{ "id": 1, "code_window": [ " sloId: '',\n", "});\n", "\n", "export function SLOQueryEditor({\n", " query,\n", " datasource,\n" ], "labels": [ "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " sloName: '',\n" ], "file_path": "public/app/plugins/datasource/cloud-monitoring/components/SLOQueryEditor.tsx", "type": "add", "edit_start_line_idx": 24 }
import React from 'react'; import { Segment, SegmentAsync } from '@grafana/ui'; import { SelectableValue } from '@grafana/data'; import { selectors } from '../constants'; import { Project, AlignmentPeriods, AliasBy, QueryInlineField } from '.'; import { SLOQuery } from '../types'; import CloudMonitoringDatasource from '../datasource'; export interface Props { usedAlignmentPeriod?: number; variableOptionGroup: SelectableValue<string>; onChange: (query: SLOQuery) => void; onRunQuery: () => void; query: SLOQuery; datasource: CloudMonitoringDatasource; } export const defaultQuery: (dataSource: CloudMonitoringDatasource) => SLOQuery = (dataSource) => ({ projectName: dataSource.getDefaultProject(), alignmentPeriod: 'cloud-monitoring-auto', aliasBy: '', selectorName: 'select_slo_health', serviceId: '', sloId: '', }); export function SLOQueryEditor({ query, datasource, onChange, variableOptionGroup, usedAlignmentPeriod, }: React.PropsWithChildren<Props>) { return ( <> <Project templateVariableOptions={variableOptionGroup.options} projectName={query.projectName} datasource={datasource} onChange={(projectName) => onChange({ ...query, projectName })} /> <QueryInlineField label="Service"> <SegmentAsync allowCustomValue value={query?.serviceId} placeholder="Select service" loadOptions={() => datasource.getSLOServices(query.projectName).then((services) => [ { label: 'Template Variables', options: variableOptionGroup.options, }, ...services, ]) } onChange={({ value: serviceId = '' }) => onChange({ ...query, serviceId, sloId: '' })} /> </QueryInlineField> <QueryInlineField label="SLO"> <SegmentAsync allowCustomValue value={query?.sloId} placeholder="Select SLO" loadOptions={() => datasource.getServiceLevelObjectives(query.projectName, query.serviceId).then((sloIds) => [ { label: 'Template Variables', options: variableOptionGroup.options, }, ...sloIds, ]) } onChange={async ({ value: sloId = '' }) => { const slos = await datasource.getServiceLevelObjectives(query.projectName, query.serviceId); const slo = slos.find(({ value }) => value === datasource.templateSrv.replace(sloId)); onChange({ ...query, sloId, goal: slo?.goal }); }} /> </QueryInlineField> <QueryInlineField label="Selector"> <Segment allowCustomValue value={[...selectors, ...variableOptionGroup.options].find((s) => s.value === query?.selectorName ?? '')} options={[ { label: 'Template Variables', options: variableOptionGroup.options, }, ...selectors, ]} onChange={({ value: selectorName }) => onChange({ ...query, selectorName })} /> </QueryInlineField> <AlignmentPeriods templateSrv={datasource.templateSrv} templateVariableOptions={variableOptionGroup.options} alignmentPeriod={query.alignmentPeriod || ''} perSeriesAligner={query.selectorName === 'select_slo_health' ? 'ALIGN_MEAN' : 'ALIGN_NEXT_OLDER'} usedAlignmentPeriod={usedAlignmentPeriod} onChange={(alignmentPeriod) => onChange({ ...query, alignmentPeriod })} /> <AliasBy value={query.aliasBy} onChange={(aliasBy) => onChange({ ...query, aliasBy })} /> </> ); }
public/app/plugins/datasource/cloud-monitoring/components/SLOQueryEditor.tsx
1
https://github.com/grafana/grafana/commit/ae64dcf0638e1b860dd3e56cdd97abb7c90833c0
[ 0.9941672086715698, 0.30319035053253174, 0.0001677096588537097, 0.02935214154422283, 0.42700836062431335 ]
{ "id": 1, "code_window": [ " sloId: '',\n", "});\n", "\n", "export function SLOQueryEditor({\n", " query,\n", " datasource,\n" ], "labels": [ "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " sloName: '',\n" ], "file_path": "public/app/plugins/datasource/cloud-monitoring/components/SLOQueryEditor.tsx", "type": "add", "edit_start_line_idx": 24 }
{ "type": "panel", "name": "Plugin list", "id": "pluginlist", "skipDataQuery": true, "info": { "description": "Plugin List for Grafana", "author": { "name": "Grafana Labs", "url": "https://grafana.com" }, "logos": { "small": "img/icn-dashlist-panel.svg", "large": "img/icn-dashlist-panel.svg" } } }
public/app/plugins/panel/pluginlist/plugin.json
0
https://github.com/grafana/grafana/commit/ae64dcf0638e1b860dd3e56cdd97abb7c90833c0
[ 0.00017222815949935466, 0.00017181964358314872, 0.00017141111311502755, 0.00017181964358314872, 4.085231921635568e-7 ]
{ "id": 1, "code_window": [ " sloId: '',\n", "});\n", "\n", "export function SLOQueryEditor({\n", " query,\n", " datasource,\n" ], "labels": [ "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " sloName: '',\n" ], "file_path": "public/app/plugins/datasource/cloud-monitoring/components/SLOQueryEditor.tsx", "type": "add", "edit_start_line_idx": 24 }
[ "grafana_wordmark", "worldping", "raintank_wordmark", "raintank_r-icn", "check-alt", "check", "collector", "dashboard", "panel", "datasources", "endpoint-tiny", "endpoint", "page", "filter", "status", "monitoring", "monitoring-tiny", "jump-to-dashboard", "warning", "nodata", "critical", "crit", "online", "event-error", "event", "sadface", "private-collector", "alert-disabled", "refresh", "save", "share", "star", "search", "remove", "video", "bulk_action", "grabber", "users", "globe", "snapshot", "play-grafana-icon", "grafana-icon", "email", "stopwatch", "skull", "probe", "apps", "scale", "pending", "verified" ]
public/sass/icons.json
0
https://github.com/grafana/grafana/commit/ae64dcf0638e1b860dd3e56cdd97abb7c90833c0
[ 0.00017906056018546224, 0.00017376255709677935, 0.00016698394028935581, 0.00017400935757905245, 0.0000035431437481747707 ]
{ "id": 1, "code_window": [ " sloId: '',\n", "});\n", "\n", "export function SLOQueryEditor({\n", " query,\n", " datasource,\n" ], "labels": [ "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " sloName: '',\n" ], "file_path": "public/app/plugins/datasource/cloud-monitoring/components/SLOQueryEditor.tsx", "type": "add", "edit_start_line_idx": 24 }
import React, { FC, useState } from 'react'; import { Organization } from 'app/types'; import { Button, ConfirmModal } from '@grafana/ui'; interface Props { orgs: Organization[]; onDelete: (orgId: number) => void; } export const AdminOrgsTable: FC<Props> = ({ orgs, onDelete }) => { const [deleteOrg, setDeleteOrg] = useState<Organization>(); return ( <table className="filter-table form-inline filter-table--hover"> <thead> <tr> <th>Id</th> <th>Name</th> <th style={{ width: '1%' }}></th> </tr> </thead> <tbody> {orgs.map((org) => ( <tr key={`${org.id}-${org.name}`}> <td className="link-td"> <a href={`admin/orgs/edit/${org.id}`}>{org.id}</a> </td> <td className="link-td"> <a href={`admin/orgs/edit/${org.id}`}>{org.name}</a> </td> <td className="text-right"> <Button variant="destructive" size="sm" icon="times" onClick={() => setDeleteOrg(org)} /> </td> </tr> ))} </tbody> {deleteOrg && ( <ConfirmModal isOpen icon="trash-alt" title="Delete" body={ <div> Are you sure you want to delete &apos;{deleteOrg.name}&apos;? <br /> <small>All dashboards for this organization will be removed!</small> </div> } confirmText="Delete" onDismiss={() => setDeleteOrg(undefined)} onConfirm={() => { onDelete(deleteOrg.id); setDeleteOrg(undefined); }} /> )} </table> ); };
public/app/features/admin/AdminOrgsTable.tsx
0
https://github.com/grafana/grafana/commit/ae64dcf0638e1b860dd3e56cdd97abb7c90833c0
[ 0.0001709700736682862, 0.0001693503581918776, 0.00016823323676362634, 0.00016920219059102237, 8.562032576264755e-7 ]
{ "id": 2, "code_window": [ " onChange={(projectName) => onChange({ ...query, projectName })}\n", " />\n", " <QueryInlineField label=\"Service\">\n", " <SegmentAsync\n", " allowCustomValue\n", " value={query?.serviceId}\n", " placeholder=\"Select service\"\n", " loadOptions={() =>\n", " datasource.getSLOServices(query.projectName).then((services) => [\n", " {\n", " label: 'Template Variables',\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " value={{ value: query?.serviceId, label: query?.serviceName || query?.serviceId }}\n" ], "file_path": "public/app/plugins/datasource/cloud-monitoring/components/SLOQueryEditor.tsx", "type": "replace", "edit_start_line_idx": 44 }
import React from 'react'; import { Segment, SegmentAsync } from '@grafana/ui'; import { SelectableValue } from '@grafana/data'; import { selectors } from '../constants'; import { Project, AlignmentPeriods, AliasBy, QueryInlineField } from '.'; import { SLOQuery } from '../types'; import CloudMonitoringDatasource from '../datasource'; export interface Props { usedAlignmentPeriod?: number; variableOptionGroup: SelectableValue<string>; onChange: (query: SLOQuery) => void; onRunQuery: () => void; query: SLOQuery; datasource: CloudMonitoringDatasource; } export const defaultQuery: (dataSource: CloudMonitoringDatasource) => SLOQuery = (dataSource) => ({ projectName: dataSource.getDefaultProject(), alignmentPeriod: 'cloud-monitoring-auto', aliasBy: '', selectorName: 'select_slo_health', serviceId: '', sloId: '', }); export function SLOQueryEditor({ query, datasource, onChange, variableOptionGroup, usedAlignmentPeriod, }: React.PropsWithChildren<Props>) { return ( <> <Project templateVariableOptions={variableOptionGroup.options} projectName={query.projectName} datasource={datasource} onChange={(projectName) => onChange({ ...query, projectName })} /> <QueryInlineField label="Service"> <SegmentAsync allowCustomValue value={query?.serviceId} placeholder="Select service" loadOptions={() => datasource.getSLOServices(query.projectName).then((services) => [ { label: 'Template Variables', options: variableOptionGroup.options, }, ...services, ]) } onChange={({ value: serviceId = '' }) => onChange({ ...query, serviceId, sloId: '' })} /> </QueryInlineField> <QueryInlineField label="SLO"> <SegmentAsync allowCustomValue value={query?.sloId} placeholder="Select SLO" loadOptions={() => datasource.getServiceLevelObjectives(query.projectName, query.serviceId).then((sloIds) => [ { label: 'Template Variables', options: variableOptionGroup.options, }, ...sloIds, ]) } onChange={async ({ value: sloId = '' }) => { const slos = await datasource.getServiceLevelObjectives(query.projectName, query.serviceId); const slo = slos.find(({ value }) => value === datasource.templateSrv.replace(sloId)); onChange({ ...query, sloId, goal: slo?.goal }); }} /> </QueryInlineField> <QueryInlineField label="Selector"> <Segment allowCustomValue value={[...selectors, ...variableOptionGroup.options].find((s) => s.value === query?.selectorName ?? '')} options={[ { label: 'Template Variables', options: variableOptionGroup.options, }, ...selectors, ]} onChange={({ value: selectorName }) => onChange({ ...query, selectorName })} /> </QueryInlineField> <AlignmentPeriods templateSrv={datasource.templateSrv} templateVariableOptions={variableOptionGroup.options} alignmentPeriod={query.alignmentPeriod || ''} perSeriesAligner={query.selectorName === 'select_slo_health' ? 'ALIGN_MEAN' : 'ALIGN_NEXT_OLDER'} usedAlignmentPeriod={usedAlignmentPeriod} onChange={(alignmentPeriod) => onChange({ ...query, alignmentPeriod })} /> <AliasBy value={query.aliasBy} onChange={(aliasBy) => onChange({ ...query, aliasBy })} /> </> ); }
public/app/plugins/datasource/cloud-monitoring/components/SLOQueryEditor.tsx
1
https://github.com/grafana/grafana/commit/ae64dcf0638e1b860dd3e56cdd97abb7c90833c0
[ 0.9949916005134583, 0.1095772311091423, 0.0001646787131903693, 0.006457123905420303, 0.2825663685798645 ]
{ "id": 2, "code_window": [ " onChange={(projectName) => onChange({ ...query, projectName })}\n", " />\n", " <QueryInlineField label=\"Service\">\n", " <SegmentAsync\n", " allowCustomValue\n", " value={query?.serviceId}\n", " placeholder=\"Select service\"\n", " loadOptions={() =>\n", " datasource.getSLOServices(query.projectName).then((services) => [\n", " {\n", " label: 'Template Variables',\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " value={{ value: query?.serviceId, label: query?.serviceName || query?.serviceId }}\n" ], "file_path": "public/app/plugins/datasource/cloud-monitoring/components/SLOQueryEditor.tsx", "type": "replace", "edit_start_line_idx": 44 }
package migrator // Notice // code based on parts from from https://github.com/go-xorm/core/blob/3e0fa232ab5c90996406c0cd7ae86ad0e5ecf85f/column.go type Column struct { Name string Type string Length int Length2 int Nullable bool IsPrimaryKey bool IsAutoIncrement bool Default string } func (col *Column) String(d Dialect) string { return d.ColString(col) } func (col *Column) StringNoPk(d Dialect) string { return d.ColStringNoPk(col) }
pkg/services/sqlstore/migrator/column.go
0
https://github.com/grafana/grafana/commit/ae64dcf0638e1b860dd3e56cdd97abb7c90833c0
[ 0.00016823083569761366, 0.00016608058649580926, 0.00016427454829681665, 0.000165736346389167, 0.0000016333857502104365 ]
{ "id": 2, "code_window": [ " onChange={(projectName) => onChange({ ...query, projectName })}\n", " />\n", " <QueryInlineField label=\"Service\">\n", " <SegmentAsync\n", " allowCustomValue\n", " value={query?.serviceId}\n", " placeholder=\"Select service\"\n", " loadOptions={() =>\n", " datasource.getSLOServices(query.projectName).then((services) => [\n", " {\n", " label: 'Template Variables',\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " value={{ value: query?.serviceId, label: query?.serviceName || query?.serviceId }}\n" ], "file_path": "public/app/plugins/datasource/cloud-monitoring/components/SLOQueryEditor.tsx", "type": "replace", "edit_start_line_idx": 44 }
package tsdb import ( "strconv" "testing" "time" . "github.com/smartystreets/goconvey/convey" ) func TestTimeRange(t *testing.T) { Convey("Time range", t, func() { now := time.Now() Convey("Can parse 5m, now", func() { tr := TimeRange{ From: "5m", To: "now", now: now, } Convey("5m ago ", func() { fiveMinAgo, err := time.ParseDuration("-5m") So(err, ShouldBeNil) expected := now.Add(fiveMinAgo) res, err := tr.ParseFrom() So(err, ShouldBeNil) So(res.Unix(), ShouldEqual, expected.Unix()) }) Convey("now ", func() { res, err := tr.ParseTo() So(err, ShouldBeNil) So(res.Unix(), ShouldEqual, now.Unix()) }) }) Convey("Can parse 5h, now-10m", func() { tr := TimeRange{ From: "5h", To: "now-10m", now: now, } Convey("5h ago ", func() { fiveHourAgo, err := time.ParseDuration("-5h") So(err, ShouldBeNil) expected := now.Add(fiveHourAgo) res, err := tr.ParseFrom() So(err, ShouldBeNil) So(res.Unix(), ShouldEqual, expected.Unix()) }) Convey("now-10m ", func() { tenMinAgo, err := time.ParseDuration("-10m") So(err, ShouldBeNil) expected := now.Add(tenMinAgo) res, err := tr.ParseTo() So(err, ShouldBeNil) So(res.Unix(), ShouldEqual, expected.Unix()) }) }) now, err := time.Parse(time.RFC3339Nano, "2020-03-26T15:12:56.000Z") So(err, ShouldBeNil) Convey("Can parse now-1M/M, now-1M/M", func() { tr := TimeRange{ From: "now-1M/M", To: "now-1M/M", now: now, } Convey("from now-1M/M ", func() { expected, err := time.Parse(time.RFC3339Nano, "2020-02-01T00:00:00.000Z") So(err, ShouldBeNil) res, err := tr.ParseFrom() So(err, ShouldBeNil) So(res, ShouldEqual, expected) }) Convey("to now-1M/M ", func() { expected, err := time.Parse(time.RFC3339Nano, "2020-02-29T23:59:59.999Z") So(err, ShouldBeNil) res, err := tr.ParseTo() So(err, ShouldBeNil) So(res, ShouldEqual, expected) }) }) Convey("Can parse now-3d, now+3w", func() { tr := TimeRange{ From: "now-3d", To: "now+3w", now: now, } Convey("now-3d ", func() { expected, err := time.Parse(time.RFC3339Nano, "2020-03-23T15:12:56.000Z") So(err, ShouldBeNil) res, err := tr.ParseFrom() So(err, ShouldBeNil) So(res, ShouldEqual, expected) }) Convey("now+3w ", func() { expected, err := time.Parse(time.RFC3339Nano, "2020-04-16T15:12:56.000Z") So(err, ShouldBeNil) res, err := tr.ParseTo() So(err, ShouldBeNil) So(res, ShouldEqual, expected) }) }) Convey("Can parse 1960-02-01T07:00:00.000Z, 1965-02-03T08:00:00.000Z", func() { tr := TimeRange{ From: "1960-02-01T07:00:00.000Z", To: "1965-02-03T08:00:00.000Z", now: now, } Convey("1960-02-01T07:00:00.000Z ", func() { expected, err := time.Parse(time.RFC3339Nano, "1960-02-01T07:00:00.000Z") So(err, ShouldBeNil) res, err := tr.ParseFrom() So(err, ShouldBeNil) So(res, ShouldEqual, expected) }) Convey("1965-02-03T08:00:00.000Z ", func() { expected, err := time.Parse(time.RFC3339Nano, "1965-02-03T08:00:00.000Z") So(err, ShouldBeNil) res, err := tr.ParseTo() So(err, ShouldBeNil) So(res, ShouldEqual, expected) }) }) Convey("Can parse negative unix epochs", func() { from := time.Date(1960, 2, 1, 7, 0, 0, 0, time.UTC) to := time.Date(1965, 2, 3, 8, 0, 0, 0, time.UTC) tr := NewTimeRange(strconv.FormatInt(from.UnixNano()/int64(time.Millisecond), 10), strconv.FormatInt(to.UnixNano()/int64(time.Millisecond), 10)) res, err := tr.ParseFrom() So(err, ShouldBeNil) So(res, ShouldEqual, from) res, err = tr.ParseTo() So(err, ShouldBeNil) So(res, ShouldEqual, to) }) Convey("can parse unix epochs", func() { var err error tr := TimeRange{ From: "1474973725473", To: "1474975757930", now: now, } res, err := tr.ParseFrom() So(err, ShouldBeNil) So(res.UnixNano()/int64(time.Millisecond), ShouldEqual, int64(1474973725473)) res, err = tr.ParseTo() So(err, ShouldBeNil) So(res.UnixNano()/int64(time.Millisecond), ShouldEqual, int64(1474975757930)) }) Convey("Cannot parse asdf", func() { var err error tr := TimeRange{ From: "asdf", To: "asdf", now: now, } _, err = tr.ParseFrom() So(err, ShouldNotBeNil) _, err = tr.ParseTo() So(err, ShouldNotBeNil) }) now, err = time.Parse(time.RFC3339Nano, "2020-07-26T15:12:56.000Z") So(err, ShouldBeNil) Convey("Can parse now-1M/M, now-1M/M with America/Chicago timezone", func() { tr := TimeRange{ From: "now-1M/M", To: "now-1M/M", now: now, } location, err := time.LoadLocation("America/Chicago") So(err, ShouldBeNil) Convey("from now-1M/M ", func() { expected, err := time.Parse(time.RFC3339Nano, "2020-06-01T00:00:00.000-05:00") So(err, ShouldBeNil) res, err := tr.ParseFromWithLocation(location) So(err, ShouldBeNil) So(res, ShouldEqual, expected) }) Convey("to now-1M/M ", func() { expected, err := time.Parse(time.RFC3339Nano, "2020-06-30T23:59:59.999-05:00") So(err, ShouldBeNil) res, err := tr.ParseToWithLocation(location) So(err, ShouldBeNil) So(res, ShouldEqual, expected) }) }) Convey("Can parse now-3h, now+2h with America/Chicago timezone", func() { tr := TimeRange{ From: "now-3h", To: "now+2h", now: now, } location, err := time.LoadLocation("America/Chicago") So(err, ShouldBeNil) Convey("now-3h ", func() { expected, err := time.Parse(time.RFC3339Nano, "2020-07-26T07:12:56.000-05:00") So(err, ShouldBeNil) res, err := tr.ParseFromWithLocation(location) So(err, ShouldBeNil) So(res, ShouldEqual, expected) }) Convey("now+2h ", func() { expected, err := time.Parse(time.RFC3339Nano, "2020-07-26T12:12:56.000-05:00") So(err, ShouldBeNil) res, err := tr.ParseToWithLocation(location) So(err, ShouldBeNil) So(res, ShouldEqual, expected) }) }) }) }
pkg/tsdb/time_range_test.go
0
https://github.com/grafana/grafana/commit/ae64dcf0638e1b860dd3e56cdd97abb7c90833c0
[ 0.00017684628255665302, 0.00017374030721839517, 0.00016923928342293948, 0.00017393811140209436, 0.0000017204224604938645 ]
{ "id": 2, "code_window": [ " onChange={(projectName) => onChange({ ...query, projectName })}\n", " />\n", " <QueryInlineField label=\"Service\">\n", " <SegmentAsync\n", " allowCustomValue\n", " value={query?.serviceId}\n", " placeholder=\"Select service\"\n", " loadOptions={() =>\n", " datasource.getSLOServices(query.projectName).then((services) => [\n", " {\n", " label: 'Template Variables',\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " value={{ value: query?.serviceId, label: query?.serviceName || query?.serviceId }}\n" ], "file_path": "public/app/plugins/datasource/cloud-monitoring/components/SLOQueryEditor.tsx", "type": "replace", "edit_start_line_idx": 44 }
import { ThemeContext, withTheme, useTheme, useStyles, mockThemeContext } from './ThemeContext'; import { getTheme, mockTheme } from './getTheme'; import { selectThemeVariant } from './selectThemeVariant'; export { stylesFactory } from './stylesFactory'; export { ThemeContext, withTheme, mockTheme, getTheme, selectThemeVariant, useTheme, mockThemeContext, useStyles }; import * as styleMixins from './mixins'; export { styleMixins };
packages/grafana-ui/src/themes/index.ts
0
https://github.com/grafana/grafana/commit/ae64dcf0638e1b860dd3e56cdd97abb7c90833c0
[ 0.00017361862410325557, 0.00017361862410325557, 0.00017361862410325557, 0.00017361862410325557, 0 ]
{ "id": 3, "code_window": [ " ...services,\n", " ])\n", " }\n", " onChange={({ value: serviceId = '' }) => onChange({ ...query, serviceId, sloId: '' })}\n", " />\n", " </QueryInlineField>\n", "\n", " <QueryInlineField label=\"SLO\">\n", " <SegmentAsync\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " onChange={({ value: serviceId = '', label: serviceName = '' }) =>\n", " onChange({ ...query, serviceId, serviceName, sloId: '' })\n", " }\n" ], "file_path": "public/app/plugins/datasource/cloud-monitoring/components/SLOQueryEditor.tsx", "type": "replace", "edit_start_line_idx": 55 }
import React from 'react'; import { Segment, SegmentAsync } from '@grafana/ui'; import { SelectableValue } from '@grafana/data'; import { selectors } from '../constants'; import { Project, AlignmentPeriods, AliasBy, QueryInlineField } from '.'; import { SLOQuery } from '../types'; import CloudMonitoringDatasource from '../datasource'; export interface Props { usedAlignmentPeriod?: number; variableOptionGroup: SelectableValue<string>; onChange: (query: SLOQuery) => void; onRunQuery: () => void; query: SLOQuery; datasource: CloudMonitoringDatasource; } export const defaultQuery: (dataSource: CloudMonitoringDatasource) => SLOQuery = (dataSource) => ({ projectName: dataSource.getDefaultProject(), alignmentPeriod: 'cloud-monitoring-auto', aliasBy: '', selectorName: 'select_slo_health', serviceId: '', sloId: '', }); export function SLOQueryEditor({ query, datasource, onChange, variableOptionGroup, usedAlignmentPeriod, }: React.PropsWithChildren<Props>) { return ( <> <Project templateVariableOptions={variableOptionGroup.options} projectName={query.projectName} datasource={datasource} onChange={(projectName) => onChange({ ...query, projectName })} /> <QueryInlineField label="Service"> <SegmentAsync allowCustomValue value={query?.serviceId} placeholder="Select service" loadOptions={() => datasource.getSLOServices(query.projectName).then((services) => [ { label: 'Template Variables', options: variableOptionGroup.options, }, ...services, ]) } onChange={({ value: serviceId = '' }) => onChange({ ...query, serviceId, sloId: '' })} /> </QueryInlineField> <QueryInlineField label="SLO"> <SegmentAsync allowCustomValue value={query?.sloId} placeholder="Select SLO" loadOptions={() => datasource.getServiceLevelObjectives(query.projectName, query.serviceId).then((sloIds) => [ { label: 'Template Variables', options: variableOptionGroup.options, }, ...sloIds, ]) } onChange={async ({ value: sloId = '' }) => { const slos = await datasource.getServiceLevelObjectives(query.projectName, query.serviceId); const slo = slos.find(({ value }) => value === datasource.templateSrv.replace(sloId)); onChange({ ...query, sloId, goal: slo?.goal }); }} /> </QueryInlineField> <QueryInlineField label="Selector"> <Segment allowCustomValue value={[...selectors, ...variableOptionGroup.options].find((s) => s.value === query?.selectorName ?? '')} options={[ { label: 'Template Variables', options: variableOptionGroup.options, }, ...selectors, ]} onChange={({ value: selectorName }) => onChange({ ...query, selectorName })} /> </QueryInlineField> <AlignmentPeriods templateSrv={datasource.templateSrv} templateVariableOptions={variableOptionGroup.options} alignmentPeriod={query.alignmentPeriod || ''} perSeriesAligner={query.selectorName === 'select_slo_health' ? 'ALIGN_MEAN' : 'ALIGN_NEXT_OLDER'} usedAlignmentPeriod={usedAlignmentPeriod} onChange={(alignmentPeriod) => onChange({ ...query, alignmentPeriod })} /> <AliasBy value={query.aliasBy} onChange={(aliasBy) => onChange({ ...query, aliasBy })} /> </> ); }
public/app/plugins/datasource/cloud-monitoring/components/SLOQueryEditor.tsx
1
https://github.com/grafana/grafana/commit/ae64dcf0638e1b860dd3e56cdd97abb7c90833c0
[ 0.9966213703155518, 0.14464512467384338, 0.00020089169265702367, 0.017193298786878586, 0.28536418080329895 ]
{ "id": 3, "code_window": [ " ...services,\n", " ])\n", " }\n", " onChange={({ value: serviceId = '' }) => onChange({ ...query, serviceId, sloId: '' })}\n", " />\n", " </QueryInlineField>\n", "\n", " <QueryInlineField label=\"SLO\">\n", " <SegmentAsync\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " onChange={({ value: serviceId = '', label: serviceName = '' }) =>\n", " onChange({ ...query, serviceId, serviceName, sloId: '' })\n", " }\n" ], "file_path": "public/app/plugins/datasource/cloud-monitoring/components/SLOQueryEditor.tsx", "type": "replace", "edit_start_line_idx": 55 }
<svg width="65" height="54" viewBox="0 0 65 54" fill="none" xmlns="http://www.w3.org/2000/svg"> <circle cx="27" cy="27" r="25" fill="#09090B" stroke="url(#paint0_linear)" stroke-width="4"/> <path d="M39 21L35 17H39V21Z" fill="url(#paint1_linear)"/> <line x1="14" y1="15" x2="14" y2="39" stroke="url(#paint2_linear)" stroke-width="2"/> <line x1="41" y1="38" x2="14" y2="38" stroke="url(#paint3_linear)" stroke-width="2"/> <path d="M37 19L28 27L25 24L16 33" stroke="url(#paint4_linear)" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> <path d="M52 37L65 26.9999L52 17L52 37Z" fill="url(#paint5_linear)"/> <defs> <linearGradient id="paint0_linear" x1="27" y1="0" x2="27" y2="54" gradientUnits="userSpaceOnUse"> <stop stop-color="#D44A3A"/> <stop offset="1" stop-color="#EB7B18"/> </linearGradient> <linearGradient id="paint1_linear" x1="37" y1="-9.62518e-07" x2="37" y2="54" gradientUnits="userSpaceOnUse"> <stop stop-color="#D44A3A"/> <stop offset="1" stop-color="#EB7B18"/> </linearGradient> <linearGradient id="paint2_linear" x1="13" y1="53.5" x2="13" y2="1.5" gradientUnits="userSpaceOnUse"> <stop stop-color="#EB7B18"/> <stop offset="1" stop-color="#D44A3A"/> </linearGradient> <linearGradient id="paint3_linear" x1="27" y1="7.21113e-07" x2="27.5" y2="54" gradientUnits="userSpaceOnUse"> <stop stop-color="#D44A3A"/> <stop offset="1" stop-color="#EB7B18"/> </linearGradient> <linearGradient id="paint4_linear" x1="27" y1="-4.4462e-08" x2="27" y2="54" gradientUnits="userSpaceOnUse"> <stop stop-color="#D44A3A"/> <stop offset="1" stop-color="#EB7B18"/> </linearGradient> <linearGradient id="paint5_linear" x1="57" y1="54" x2="57" y2="7.55191e-06" gradientUnits="userSpaceOnUse"> <stop stop-color="#EB7B18"/> <stop offset="1" stop-color="#D44A3A"/> </linearGradient> </defs> </svg>
public/img/panel-tabs/visualization-selected.svg
0
https://github.com/grafana/grafana/commit/ae64dcf0638e1b860dd3e56cdd97abb7c90833c0
[ 0.00017278888844884932, 0.00017164750897791237, 0.00016897742170840502, 0.00017241186287719756, 0.0000015586499557684874 ]
{ "id": 3, "code_window": [ " ...services,\n", " ])\n", " }\n", " onChange={({ value: serviceId = '' }) => onChange({ ...query, serviceId, sloId: '' })}\n", " />\n", " </QueryInlineField>\n", "\n", " <QueryInlineField label=\"SLO\">\n", " <SegmentAsync\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " onChange={({ value: serviceId = '', label: serviceName = '' }) =>\n", " onChange({ ...query, serviceId, serviceName, sloId: '' })\n", " }\n" ], "file_path": "public/app/plugins/datasource/cloud-monitoring/components/SLOQueryEditor.tsx", "type": "replace", "edit_start_line_idx": 55 }
export type SettingKeyOf<T extends { settings?: Record<string, unknown> }> = Extract< keyof NonNullable<T['settings']>, string >;
public/app/plugins/datasource/elasticsearch/components/types.ts
0
https://github.com/grafana/grafana/commit/ae64dcf0638e1b860dd3e56cdd97abb7c90833c0
[ 0.00017029453010763973, 0.00017029453010763973, 0.00017029453010763973, 0.00017029453010763973, 0 ]
{ "id": 3, "code_window": [ " ...services,\n", " ])\n", " }\n", " onChange={({ value: serviceId = '' }) => onChange({ ...query, serviceId, sloId: '' })}\n", " />\n", " </QueryInlineField>\n", "\n", " <QueryInlineField label=\"SLO\">\n", " <SegmentAsync\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " onChange={({ value: serviceId = '', label: serviceName = '' }) =>\n", " onChange({ ...query, serviceId, serviceName, sloId: '' })\n", " }\n" ], "file_path": "public/app/plugins/datasource/cloud-monitoring/components/SLOQueryEditor.tsx", "type": "replace", "edit_start_line_idx": 55 }
package dashboards import ( "time" "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/models" ) func MakeUserAdmin(bus bus.Bus, orgID int64, userID int64, dashboardID int64, setViewAndEditPermissions bool) error { rtEditor := models.ROLE_EDITOR rtViewer := models.ROLE_VIEWER items := []*models.DashboardAcl{ { OrgID: orgID, DashboardID: dashboardID, UserID: userID, Permission: models.PERMISSION_ADMIN, Created: time.Now(), Updated: time.Now(), }, } if setViewAndEditPermissions { items = append(items, &models.DashboardAcl{ OrgID: orgID, DashboardID: dashboardID, Role: &rtEditor, Permission: models.PERMISSION_EDIT, Created: time.Now(), Updated: time.Now(), }, &models.DashboardAcl{ OrgID: orgID, DashboardID: dashboardID, Role: &rtViewer, Permission: models.PERMISSION_VIEW, Created: time.Now(), Updated: time.Now(), }, ) } aclCmd := &models.UpdateDashboardAclCommand{ DashboardID: dashboardID, Items: items, } if err := bus.Dispatch(aclCmd); err != nil { return err } return nil }
pkg/services/dashboards/acl_service.go
0
https://github.com/grafana/grafana/commit/ae64dcf0638e1b860dd3e56cdd97abb7c90833c0
[ 0.00017336171003989875, 0.00017079782264772803, 0.0001684529852354899, 0.0001708693744149059, 0.0000017881022813526215 ]
{ "id": 4, "code_window": [ " </QueryInlineField>\n", "\n", " <QueryInlineField label=\"SLO\">\n", " <SegmentAsync\n", " allowCustomValue\n", " value={query?.sloId}\n", " placeholder=\"Select SLO\"\n", " loadOptions={() =>\n", " datasource.getServiceLevelObjectives(query.projectName, query.serviceId).then((sloIds) => [\n", " {\n", " label: 'Template Variables',\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " value={{ value: query?.sloId, label: query?.sloName || query?.sloId }}\n" ], "file_path": "public/app/plugins/datasource/cloud-monitoring/components/SLOQueryEditor.tsx", "type": "replace", "edit_start_line_idx": 62 }
import React from 'react'; import { Segment, SegmentAsync } from '@grafana/ui'; import { SelectableValue } from '@grafana/data'; import { selectors } from '../constants'; import { Project, AlignmentPeriods, AliasBy, QueryInlineField } from '.'; import { SLOQuery } from '../types'; import CloudMonitoringDatasource from '../datasource'; export interface Props { usedAlignmentPeriod?: number; variableOptionGroup: SelectableValue<string>; onChange: (query: SLOQuery) => void; onRunQuery: () => void; query: SLOQuery; datasource: CloudMonitoringDatasource; } export const defaultQuery: (dataSource: CloudMonitoringDatasource) => SLOQuery = (dataSource) => ({ projectName: dataSource.getDefaultProject(), alignmentPeriod: 'cloud-monitoring-auto', aliasBy: '', selectorName: 'select_slo_health', serviceId: '', sloId: '', }); export function SLOQueryEditor({ query, datasource, onChange, variableOptionGroup, usedAlignmentPeriod, }: React.PropsWithChildren<Props>) { return ( <> <Project templateVariableOptions={variableOptionGroup.options} projectName={query.projectName} datasource={datasource} onChange={(projectName) => onChange({ ...query, projectName })} /> <QueryInlineField label="Service"> <SegmentAsync allowCustomValue value={query?.serviceId} placeholder="Select service" loadOptions={() => datasource.getSLOServices(query.projectName).then((services) => [ { label: 'Template Variables', options: variableOptionGroup.options, }, ...services, ]) } onChange={({ value: serviceId = '' }) => onChange({ ...query, serviceId, sloId: '' })} /> </QueryInlineField> <QueryInlineField label="SLO"> <SegmentAsync allowCustomValue value={query?.sloId} placeholder="Select SLO" loadOptions={() => datasource.getServiceLevelObjectives(query.projectName, query.serviceId).then((sloIds) => [ { label: 'Template Variables', options: variableOptionGroup.options, }, ...sloIds, ]) } onChange={async ({ value: sloId = '' }) => { const slos = await datasource.getServiceLevelObjectives(query.projectName, query.serviceId); const slo = slos.find(({ value }) => value === datasource.templateSrv.replace(sloId)); onChange({ ...query, sloId, goal: slo?.goal }); }} /> </QueryInlineField> <QueryInlineField label="Selector"> <Segment allowCustomValue value={[...selectors, ...variableOptionGroup.options].find((s) => s.value === query?.selectorName ?? '')} options={[ { label: 'Template Variables', options: variableOptionGroup.options, }, ...selectors, ]} onChange={({ value: selectorName }) => onChange({ ...query, selectorName })} /> </QueryInlineField> <AlignmentPeriods templateSrv={datasource.templateSrv} templateVariableOptions={variableOptionGroup.options} alignmentPeriod={query.alignmentPeriod || ''} perSeriesAligner={query.selectorName === 'select_slo_health' ? 'ALIGN_MEAN' : 'ALIGN_NEXT_OLDER'} usedAlignmentPeriod={usedAlignmentPeriod} onChange={(alignmentPeriod) => onChange({ ...query, alignmentPeriod })} /> <AliasBy value={query.aliasBy} onChange={(aliasBy) => onChange({ ...query, aliasBy })} /> </> ); }
public/app/plugins/datasource/cloud-monitoring/components/SLOQueryEditor.tsx
1
https://github.com/grafana/grafana/commit/ae64dcf0638e1b860dd3e56cdd97abb7c90833c0
[ 0.982328474521637, 0.10658001154661179, 0.00017403547826688737, 0.00672576017677784, 0.27947553992271423 ]
{ "id": 4, "code_window": [ " </QueryInlineField>\n", "\n", " <QueryInlineField label=\"SLO\">\n", " <SegmentAsync\n", " allowCustomValue\n", " value={query?.sloId}\n", " placeholder=\"Select SLO\"\n", " loadOptions={() =>\n", " datasource.getServiceLevelObjectives(query.projectName, query.serviceId).then((sloIds) => [\n", " {\n", " label: 'Template Variables',\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " value={{ value: query?.sloId, label: query?.sloName || query?.sloId }}\n" ], "file_path": "public/app/plugins/datasource/cloud-monitoring/components/SLOQueryEditor.tsx", "type": "replace", "edit_start_line_idx": 62 }
import { DataQuery, DataSourceJsonData } from '@grafana/data'; export interface OpenTsdbQuery extends DataQuery { metric?: any; } export interface OpenTsdbOptions extends DataSourceJsonData { tsdbVersion: number; tsdbResolution: number; lookupLimit: number; }
public/app/plugins/datasource/opentsdb/types.ts
0
https://github.com/grafana/grafana/commit/ae64dcf0638e1b860dd3e56cdd97abb7c90833c0
[ 0.00017262042092625052, 0.00017120802658610046, 0.0001697956322459504, 0.00017120802658610046, 0.0000014123943401500583 ]
{ "id": 4, "code_window": [ " </QueryInlineField>\n", "\n", " <QueryInlineField label=\"SLO\">\n", " <SegmentAsync\n", " allowCustomValue\n", " value={query?.sloId}\n", " placeholder=\"Select SLO\"\n", " loadOptions={() =>\n", " datasource.getServiceLevelObjectives(query.projectName, query.serviceId).then((sloIds) => [\n", " {\n", " label: 'Template Variables',\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " value={{ value: query?.sloId, label: query?.sloName || query?.sloId }}\n" ], "file_path": "public/app/plugins/datasource/cloud-monitoring/components/SLOQueryEditor.tsx", "type": "replace", "edit_start_line_idx": 62 }
body, table.body, h1, h2, h3, h4, h5, h6, p, td { font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; } h1 {font-size: 40px;} h2 {font-size: 36px;} h3 { font-size: 22px; margin-top: 10px; margin-bottom: 10px; } h4 {font-size: 20px;} h5 {font-size: 18px;} h6 {font-size: 16px;} .emphasis { font-weight: 600; } a { color: #E67612; text-decoration: none; } a:hover { color: #ff8f2b !important; } a:active { color: #F2821E !important; } a:visited { color: #E67612 !important; } table.facebook td { background: #3b5998; border-color: #2d4473; } table.facebook:hover td { background: #2d4473 !important; } table.twitter td { background: #00acee; border-color: #0087bb; } table.twitter:hover td { background: #0087bb !important; } table.google-plus td { background-color: #DB4A39; border-color: #CC0000; } table.google-plus:hover td { background: #CC0000 !important; } .template-label { color: #ffffff; font-weight: bold; font-size: 11px; } .callout .wrapper { padding-bottom: 20px; } .callout .panel { background: #ECF8FF; border-color: #b9e5ff; } .header { margin-top:25px; margin-bottom: 25px; } .data { font-size: 16px; } .footer { background-color: #2e2e2e; color: #999999; margin-top: 20px; } @media only screen and (max-width: 600px) { table[class="body"] .right-text-pad { padding-left: 10px !important; } table[class="body"] .left-text-pad { padding-right: 10px !important; } .logo { margin-left: 10px; } } table.better-button { margin-top: 10px; margin-bottom: 20px; } table.columns td.better-button { -webkit-border-radius: 2px; -moz-border-radius: 2px; border-radius: 2px; padding-bottom: 0px; } .better-button a { text-decoration: none; -webkit-border-radius: 2px; -moz-border-radius: 2px; border-radius: 2px; padding: 12px 25px; border: 1px solid #ff8f2b; display: inline-block; color: #FFF; } .better-button:hover a { color: #FFFFFF !important; background-color: #F2821E; border: 1px solid #F2821E; } .better-button:visited a { color: #FFFFFF !important; } .better-button:active a { color: #FFFFFF !important; } table.better-button-alt { margin-top: 10px; margin-bottom: 20px; } table.columns td.better-button-alt { -webkit-border-radius: 2px; -moz-border-radius: 2px; border-radius: 2px; padding-bottom: 0px; } .better-button-alt a { text-decoration: none; -webkit-border-radius: 2px; -moz-border-radius: 2px; border-radius: 2px; padding: 12px 25px; border: 1px solid #ff8f2b; background-color: #EFEFEF; display: inline-block; color: #ff8f2b; } .better-button-alt:hover a { color: #ff8f2b !important; background-color: #DDDDDD; border: 1px solid #F2821E; } .better-button-alt:visited a { color: #ff8f2b !important; } .better-button-alt:active a { color: #ff8f2b !important; } .verification-code { background-color: #EEEEEE; padding: 3px; margin: 8px; display: inline-block; font-weight: bold; font-size: 20px; }
emails/assets/css/style.css
0
https://github.com/grafana/grafana/commit/ae64dcf0638e1b860dd3e56cdd97abb7c90833c0
[ 0.00017736588779371232, 0.0001736716367304325, 0.00016877711459528655, 0.00017369925626553595, 0.0000019697690731845796 ]
{ "id": 4, "code_window": [ " </QueryInlineField>\n", "\n", " <QueryInlineField label=\"SLO\">\n", " <SegmentAsync\n", " allowCustomValue\n", " value={query?.sloId}\n", " placeholder=\"Select SLO\"\n", " loadOptions={() =>\n", " datasource.getServiceLevelObjectives(query.projectName, query.serviceId).then((sloIds) => [\n", " {\n", " label: 'Template Variables',\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " value={{ value: query?.sloId, label: query?.sloName || query?.sloId }}\n" ], "file_path": "public/app/plugins/datasource/cloud-monitoring/components/SLOQueryEditor.tsx", "type": "replace", "edit_start_line_idx": 62 }
#!/bin/bash docker info && docker version mkdir -p ~/docker # cache some Docker images to make builds faster if [[ -e ~/docker/centos.tar ]]; then docker load -i ~/docker/centos.tar; else docker build --tag "grafana/buildcontainer" docker/buildcontainer docker save grafana/buildcontainer > ~/docker/centos.tar; fi
devenv/docker/buildcontainer/build_circle.sh
0
https://github.com/grafana/grafana/commit/ae64dcf0638e1b860dd3e56cdd97abb7c90833c0
[ 0.0001737615530146286, 0.00017018214566633105, 0.0001666027237661183, 0.00017018214566633105, 0.0000035794146242551506 ]
{ "id": 5, "code_window": [ " },\n", " ...sloIds,\n", " ])\n", " }\n", " onChange={async ({ value: sloId = '' }) => {\n", " const slos = await datasource.getServiceLevelObjectives(query.projectName, query.serviceId);\n", " const slo = slos.find(({ value }) => value === datasource.templateSrv.replace(sloId));\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " onChange={async ({ value: sloId = '', label: sloName = '' }) => {\n" ], "file_path": "public/app/plugins/datasource/cloud-monitoring/components/SLOQueryEditor.tsx", "type": "replace", "edit_start_line_idx": 73 }
import _ from 'lodash'; import { DataQueryRequest, DataSourceInstanceSettings, ScopedVars, SelectableValue, DataQueryResponse, } from '@grafana/data'; import { getTemplateSrv, TemplateSrv } from 'app/features/templating/template_srv'; import { getTimeSrv, TimeSrv } from 'app/features/dashboard/services/TimeSrv'; import { CloudMonitoringOptions, CloudMonitoringQuery, Filter, MetricDescriptor, QueryType, EditorMode } from './types'; import API from './api'; import { DataSourceWithBackend } from '@grafana/runtime'; import { CloudMonitoringVariableSupport } from './variables'; import { catchError, map, mergeMap } from 'rxjs/operators'; import { from, Observable, of, throwError } from 'rxjs'; export default class CloudMonitoringDatasource extends DataSourceWithBackend< CloudMonitoringQuery, CloudMonitoringOptions > { api: API; authenticationType: string; intervalMs: number; constructor( private instanceSettings: DataSourceInstanceSettings<CloudMonitoringOptions>, public templateSrv: TemplateSrv = getTemplateSrv(), private readonly timeSrv: TimeSrv = getTimeSrv() ) { super(instanceSettings); this.authenticationType = instanceSettings.jsonData.authenticationType || 'jwt'; this.api = new API(`${instanceSettings.url!}/cloudmonitoring/v3/projects/`); this.variables = new CloudMonitoringVariableSupport(this); } getVariables() { return this.templateSrv.getVariables().map((v) => `$${v.name}`); } query(request: DataQueryRequest<CloudMonitoringQuery>): Observable<DataQueryResponse> { request.targets = request.targets.map((t) => ({ ...this.migrateQuery(t), intervalMs: request.intervalMs, })); return super.query(request); } async annotationQuery(options: any) { await this.ensureGCEDefaultProject(); const annotation = options.annotation; const queries = [ { refId: 'annotationQuery', type: 'annotationQuery', datasourceId: this.id, view: 'FULL', crossSeriesReducer: 'REDUCE_NONE', perSeriesAligner: 'ALIGN_NONE', metricType: this.templateSrv.replace(annotation.target.metricType, options.scopedVars || {}), title: this.templateSrv.replace(annotation.target.title, options.scopedVars || {}), text: this.templateSrv.replace(annotation.target.text, options.scopedVars || {}), tags: this.templateSrv.replace(annotation.target.tags, options.scopedVars || {}), projectName: this.templateSrv.replace( annotation.target.projectName ? annotation.target.projectName : this.getDefaultProject(), options.scopedVars || {} ), filters: this.interpolateFilters(annotation.target.filters || [], options.scopedVars), }, ]; return this.api .post({ from: options.range.from.valueOf().toString(), to: options.range.to.valueOf().toString(), queries, }) .pipe( map(({ data }) => { const results = data.results['annotationQuery'].tables[0].rows.map((v: any) => { return { annotation: annotation, time: Date.parse(v[0]), title: v[1], tags: [], text: v[3], } as any; }); return results; }) ) .toPromise(); } applyTemplateVariables( { metricQuery, refId, queryType, sloQuery }: CloudMonitoringQuery, scopedVars: ScopedVars ): Record<string, any> { return { datasourceId: this.id, refId, intervalMs: this.intervalMs, type: 'timeSeriesQuery', queryType, metricQuery: { ...this.interpolateProps(metricQuery, scopedVars), projectName: this.templateSrv.replace( metricQuery.projectName ? metricQuery.projectName : this.getDefaultProject(), scopedVars ), filters: this.interpolateFilters(metricQuery.filters || [], scopedVars), groupBys: this.interpolateGroupBys(metricQuery.groupBys || [], scopedVars), view: metricQuery.view || 'FULL', editorMode: metricQuery.editorMode, }, sloQuery: sloQuery && this.interpolateProps(sloQuery, scopedVars), }; } async getLabels(metricType: string, refId: string, projectName: string, groupBys?: string[]) { const options = { targets: [ { refId, datasourceId: this.id, queryType: QueryType.METRICS, metricQuery: { projectName: this.templateSrv.replace(projectName), metricType: this.templateSrv.replace(metricType), groupBys: this.interpolateGroupBys(groupBys || [], {}), crossSeriesReducer: 'REDUCE_NONE', view: 'HEADERS', }, }, ], range: this.timeSrv.timeRange(), } as DataQueryRequest<CloudMonitoringQuery>; const queries = options.targets; if (!queries.length) { return of({ results: [] }).toPromise(); } return from(this.ensureGCEDefaultProject()) .pipe( mergeMap(() => { return this.api.post({ from: options.range.from.valueOf().toString(), to: options.range.to.valueOf().toString(), queries, }); }), map(({ data }) => { return data; }), map((response) => { const result = response.results[refId]; return result && result.meta ? result.meta.labels : {}; }) ) .toPromise(); } async testDatasource() { let status, message; const defaultErrorMessage = 'Cannot connect to Google Cloud Monitoring API'; try { await this.ensureGCEDefaultProject(); const response = await this.api.test(this.getDefaultProject()); if (response.status === 200) { status = 'success'; message = 'Successfully queried the Google Cloud Monitoring API.'; } else { status = 'error'; message = response.statusText ? response.statusText : defaultErrorMessage; } } catch (error) { status = 'error'; if (_.isString(error)) { message = error; } else { message = 'Google Cloud Monitoring: '; message += error.statusText ? error.statusText : defaultErrorMessage; if (error.data && error.data.error && error.data.error.code) { message += ': ' + error.data.error.code + '. ' + error.data.error.message; } } } finally { return { status, message, }; } } async getGCEDefaultProject() { return this.api .post({ queries: [ { refId: 'getGCEDefaultProject', type: 'getGCEDefaultProject', datasourceId: this.id, }, ], }) .pipe( map(({ data }) => { return data && data.results && data.results.getGCEDefaultProject && data.results.getGCEDefaultProject.meta ? data.results.getGCEDefaultProject.meta.defaultProject : ''; }), catchError((err) => { return throwError(err.data.error); }) ) .toPromise(); } getDefaultProject(): string { const { defaultProject, authenticationType, gceDefaultProject } = this.instanceSettings.jsonData; if (authenticationType === 'gce') { return gceDefaultProject || ''; } return defaultProject || ''; } async ensureGCEDefaultProject() { const { authenticationType, gceDefaultProject } = this.instanceSettings.jsonData; if (authenticationType === 'gce' && !gceDefaultProject) { this.instanceSettings.jsonData.gceDefaultProject = await this.getGCEDefaultProject(); } } async getMetricTypes(projectName: string): Promise<MetricDescriptor[]> { if (!projectName) { return []; } return this.api.get(`${this.templateSrv.replace(projectName)}/metricDescriptors`, { responseMap: (m: any) => { const [service] = m.type.split('/'); const [serviceShortName] = service.split('.'); m.service = service; m.serviceShortName = serviceShortName; m.displayName = m.displayName || m.type; return m; }, }) as Promise<MetricDescriptor[]>; } async getSLOServices(projectName: string): Promise<Array<SelectableValue<string>>> { return this.api.get(`${this.templateSrv.replace(projectName)}/services?pageSize=1000`, { responseMap: ({ name }: { name: string }) => ({ value: name.match(/([^\/]*)\/*$/)![1], label: name.match(/([^\/]*)\/*$/)![1], }), }); } async getServiceLevelObjectives(projectName: string, serviceId: string): Promise<Array<SelectableValue<string>>> { if (!serviceId) { return Promise.resolve([]); } let { projectName: p, serviceId: s } = this.interpolateProps({ projectName, serviceId }); return this.api.get(`${p}/services/${s}/serviceLevelObjectives`, { responseMap: ({ name, displayName, goal }: { name: string; displayName: string; goal: number }) => ({ value: name.match(/([^\/]*)\/*$/)![1], label: displayName, goal, }), }); } getProjects() { return this.api.get(`projects`, { responseMap: ({ projectId, name }: { projectId: string; name: string }) => ({ value: projectId, label: name, }), baseUrl: `${this.instanceSettings.url!}/cloudresourcemanager/v1/`, }); } migrateQuery(query: CloudMonitoringQuery): CloudMonitoringQuery { if (!query.hasOwnProperty('metricQuery')) { const { hide, refId, datasource, key, queryType, maxLines, metric, intervalMs, type, ...rest } = query as any; return { refId, intervalMs, type, hide, queryType: QueryType.METRICS, metricQuery: { ...rest, view: rest.view || 'FULL', }, }; } return query; } interpolateProps<T extends Record<string, any>>(object: T, scopedVars: ScopedVars = {}): T { return Object.entries(object).reduce((acc, [key, value]) => { return { ...acc, [key]: value && _.isString(value) ? this.templateSrv.replace(value, scopedVars) : value, }; }, {} as T); } filterQuery(query: CloudMonitoringQuery): boolean { if (query.hide) { return false; } if (query.queryType && query.queryType === QueryType.SLO && query.sloQuery) { const { selectorName, serviceId, sloId, projectName } = query.sloQuery; return !!selectorName && !!serviceId && !!sloId && !!projectName; } if (query.queryType && query.queryType === QueryType.METRICS && query.metricQuery.editorMode === EditorMode.MQL) { return !!query.metricQuery.projectName && !!query.metricQuery.query; } const { metricType } = query.metricQuery; return !!metricType; } interpolateVariablesInQueries(queries: CloudMonitoringQuery[], scopedVars: ScopedVars): CloudMonitoringQuery[] { return queries.map((query) => this.applyTemplateVariables(query, scopedVars) as CloudMonitoringQuery); } interpolateFilters(filters: string[], scopedVars: ScopedVars) { const completeFilter = _.chunk(filters, 4) .map(([key, operator, value, condition]) => ({ key, operator, value, ...(condition && { condition }), })) .reduce((res, filter) => (filter.value ? [...res, filter] : res), []); const filterArray = _.flatten( completeFilter.map(({ key, operator, value, condition }: Filter) => [ this.templateSrv.replace(key, scopedVars || {}), operator, this.templateSrv.replace(value, scopedVars || {}, 'regex'), ...(condition ? [condition] : []), ]) ); return filterArray || []; } interpolateGroupBys(groupBys: string[], scopedVars: {}): string[] { let interpolatedGroupBys: string[] = []; (groupBys || []).forEach((gb) => { const interpolated = this.templateSrv.replace(gb, scopedVars || {}, 'csv').split(','); if (Array.isArray(interpolated)) { interpolatedGroupBys = interpolatedGroupBys.concat(interpolated); } else { interpolatedGroupBys.push(interpolated); } }); return interpolatedGroupBys; } }
public/app/plugins/datasource/cloud-monitoring/datasource.ts
1
https://github.com/grafana/grafana/commit/ae64dcf0638e1b860dd3e56cdd97abb7c90833c0
[ 0.004070130176842213, 0.0008002446265891194, 0.00016367837088182569, 0.0002149953506886959, 0.0011035529896616936 ]
{ "id": 5, "code_window": [ " },\n", " ...sloIds,\n", " ])\n", " }\n", " onChange={async ({ value: sloId = '' }) => {\n", " const slos = await datasource.getServiceLevelObjectives(query.projectName, query.serviceId);\n", " const slo = slos.find(({ value }) => value === datasource.templateSrv.replace(sloId));\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " onChange={async ({ value: sloId = '', label: sloName = '' }) => {\n" ], "file_path": "public/app/plugins/datasource/cloud-monitoring/components/SLOQueryEditor.tsx", "type": "replace", "edit_start_line_idx": 73 }
import React, { FC, useState } from 'react'; import { OrgUser } from 'app/types'; import { OrgRolePicker } from '../admin/OrgRolePicker'; import { Button, ConfirmModal } from '@grafana/ui'; import { OrgRole } from '@grafana/data'; export interface Props { users: OrgUser[]; onRoleChange: (role: OrgRole, user: OrgUser) => void; onRemoveUser: (user: OrgUser) => void; } const UsersTable: FC<Props> = (props) => { const { users, onRoleChange, onRemoveUser } = props; const [showRemoveModal, setShowRemoveModal] = useState<string | boolean>(false); return ( <table className="filter-table form-inline"> <thead> <tr> <th /> <th>Login</th> <th>Email</th> <th>Name</th> <th>Seen</th> <th>Role</th> <th style={{ width: '34px' }} /> </tr> </thead> <tbody> {users.map((user, index) => { return ( <tr key={`${user.userId}-${index}`}> <td className="width-2 text-center"> <img className="filter-table__avatar" src={user.avatarUrl} /> </td> <td className="max-width-6"> <span className="ellipsis" title={user.login}> {user.login} </span> </td> <td className="max-width-5"> <span className="ellipsis" title={user.email}> {user.email} </span> </td> <td className="max-width-5"> <span className="ellipsis" title={user.name}> {user.name} </span> </td> <td className="width-1">{user.lastSeenAtAge}</td> <td className="width-8"> <OrgRolePicker value={user.role} onChange={(newRole) => onRoleChange(newRole, user)} /> </td> <td> <Button size="sm" variant="destructive" onClick={() => setShowRemoveModal(user.login)} icon="times" /> <ConfirmModal body={`Are you sure you want to delete user ${user.login}?`} confirmText="Delete" title="Delete" onDismiss={() => setShowRemoveModal(false)} isOpen={user.login === showRemoveModal} onConfirm={() => { onRemoveUser(user); }} /> </td> </tr> ); })} </tbody> </table> ); }; export default UsersTable;
public/app/features/users/UsersTable.tsx
0
https://github.com/grafana/grafana/commit/ae64dcf0638e1b860dd3e56cdd97abb7c90833c0
[ 0.00017495655629318208, 0.0001706952607491985, 0.0001654152147239074, 0.00017133759683929384, 0.0000031120493986236397 ]
{ "id": 5, "code_window": [ " },\n", " ...sloIds,\n", " ])\n", " }\n", " onChange={async ({ value: sloId = '' }) => {\n", " const slos = await datasource.getServiceLevelObjectives(query.projectName, query.serviceId);\n", " const slo = slos.find(({ value }) => value === datasource.templateSrv.replace(sloId));\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " onChange={async ({ value: sloId = '', label: sloName = '' }) => {\n" ], "file_path": "public/app/plugins/datasource/cloud-monitoring/components/SLOQueryEditor.tsx", "type": "replace", "edit_start_line_idx": 73 }
{ "version": "Testversion" }
packages/grafana-toolkit/src/config/mocks/webpack/noOverride/package.json
0
https://github.com/grafana/grafana/commit/ae64dcf0638e1b860dd3e56cdd97abb7c90833c0
[ 0.00016909718397073448, 0.00016909718397073448, 0.00016909718397073448, 0.00016909718397073448, 0 ]
{ "id": 5, "code_window": [ " },\n", " ...sloIds,\n", " ])\n", " }\n", " onChange={async ({ value: sloId = '' }) => {\n", " const slos = await datasource.getServiceLevelObjectives(query.projectName, query.serviceId);\n", " const slo = slos.find(({ value }) => value === datasource.templateSrv.replace(sloId));\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " onChange={async ({ value: sloId = '', label: sloName = '' }) => {\n" ], "file_path": "public/app/plugins/datasource/cloud-monitoring/components/SLOQueryEditor.tsx", "type": "replace", "edit_start_line_idx": 73 }
import { cloneDeep } from 'lodash'; import { cleanPickerState, hideOptions, initialState as optionsPickerInitialState, moveOptionsHighlight, OPTIONS_LIMIT, optionsPickerReducer, OptionsPickerState, showOptions, toggleAllOptions, toggleOption, toggleTag, updateOptionsAndFilter, updateOptionsFromSearch, updateSearchQuery, } from './reducer'; import { reducerTester } from '../../../../../test/core/redux/reducerTester'; import { QueryVariableModel, VariableOption, VariableTag } from '../../types'; import { ALL_VARIABLE_TEXT, ALL_VARIABLE_VALUE } from '../../state/types'; const getVariableTestContext = (extend: Partial<OptionsPickerState>) => { return { initialState: { ...optionsPickerInitialState, ...extend, }, }; }; describe('optionsPickerReducer', () => { describe('when toggleOption is dispatched', () => { const opsAll = [ { text: '$__all', value: '$__all', selected: true }, { text: 'A', value: 'A', selected: false }, { text: 'B', value: 'B', selected: false }, ]; const opsA = [ { text: '$__all', value: '$__all', selected: false }, { text: 'A', value: 'A', selected: true }, { text: 'B', value: 'B', selected: false }, ]; const opsAB = [ { text: '$__all', value: '$__all', selected: false }, { text: 'A', value: 'A', selected: true }, { text: 'B', value: 'B', selected: true }, ]; const expectToggleOptionState = (args: { options: any; multi: any; forceSelect: any; clearOthers: any; option: any; expectSelected: any; }) => { const { initialState } = getVariableTestContext({ options: args.options, multi: args.multi, selectedValues: args.options.filter((o: any) => o.selected), }); const payload = { forceSelect: args.forceSelect, clearOthers: args.clearOthers, option: { text: args.option, value: args.option, selected: true }, }; const expectedAsRecord: any = args.expectSelected.reduce((all: any, current: any) => { all[current] = current; return all; }, {}); reducerTester<OptionsPickerState>() .givenReducer(optionsPickerReducer, cloneDeep(initialState)) .whenActionIsDispatched(toggleOption(payload)) .thenStateShouldEqual({ ...initialState, selectedValues: args.expectSelected.map((value: any) => ({ value, text: value, selected: true })), options: args.options.map((option: any) => { return { ...option, selected: !!expectedAsRecord[option.value] }; }), }); }; describe('toggleOption for multi value variable', () => { const multi = true; describe('and value All is selected in options', () => { const options = opsAll; it.each` option | forceSelect | clearOthers | expectSelected ${'A'} | ${true} | ${false} | ${['A']} ${'A'} | ${false} | ${false} | ${['A']} ${'A'} | ${true} | ${true} | ${['A']} ${'A'} | ${false} | ${true} | ${['A']} ${'B'} | ${true} | ${false} | ${['B']} ${'B'} | ${false} | ${false} | ${['B']} ${'B'} | ${true} | ${true} | ${['B']} ${'B'} | ${false} | ${true} | ${['B']} ${'$__all'} | ${true} | ${false} | ${['$__all']} ${'$__all'} | ${false} | ${false} | ${['$__all']} ${'$__all'} | ${true} | ${true} | ${['$__all']} ${'$__all'} | ${false} | ${true} | ${['$__all']} `( 'and we toggle $option with options: { forceSelect: $forceSelect, clearOthers: $clearOthers } we expect $expectSelected to be selected', ({ option, forceSelect, clearOthers, expectSelected }) => expectToggleOptionState({ options, multi, option, clearOthers, forceSelect, expectSelected, }) ); }); describe('and value A is selected in options', () => { const options = opsA; it.each` option | forceSelect | clearOthers | expectSelected ${'A'} | ${true} | ${false} | ${['A']} ${'A'} | ${false} | ${false} | ${['$__all']} ${'A'} | ${true} | ${true} | ${['A']} ${'A'} | ${false} | ${true} | ${['$__all']} ${'B'} | ${true} | ${true} | ${['B']} ${'B'} | ${false} | ${true} | ${['B']} ${'B'} | ${true} | ${false} | ${['A', 'B']} ${'B'} | ${false} | ${false} | ${['A', 'B']} `( 'and we toggle $option with options: { forceSelect: $forceSelect, clearOthers: $clearOthers } we expect $expectSelected to be selected', ({ option, forceSelect, clearOthers, expectSelected }) => expectToggleOptionState({ options, multi, option, clearOthers, forceSelect, expectSelected, }) ); }); describe('and values A + B is selected in options', () => { const options = opsAB; it.each` option | forceSelect | clearOthers | expectSelected ${'A'} | ${true} | ${false} | ${['A', 'B']} ${'A'} | ${false} | ${false} | ${['B']} ${'A'} | ${true} | ${true} | ${['A']} ${'A'} | ${false} | ${true} | ${['$__all']} ${'B'} | ${true} | ${true} | ${['B']} ${'B'} | ${false} | ${true} | ${['$__all']} ${'B'} | ${true} | ${false} | ${['A', 'B']} ${'B'} | ${false} | ${false} | ${['A']} `( 'and we toggle $option with options: { forceSelect: $forceSelect, clearOthers: $clearOthers } we expect $expectSelected to be selected', ({ option, forceSelect, clearOthers, expectSelected }) => expectToggleOptionState({ options, multi, option, clearOthers, forceSelect, expectSelected, }) ); }); }); describe('toggleOption for single value variable', () => { const multi = false; describe('and value All is selected in options', () => { const options = opsAll; it.each` option | forceSelect | clearOthers | expectSelected ${'A'} | ${true} | ${false} | ${['A']} ${'A'} | ${false} | ${false} | ${['A']} ${'A'} | ${true} | ${true} | ${['A']} ${'A'} | ${false} | ${true} | ${['A']} ${'B'} | ${true} | ${false} | ${['B']} ${'B'} | ${false} | ${false} | ${['B']} ${'B'} | ${true} | ${true} | ${['B']} ${'B'} | ${false} | ${true} | ${['B']} ${'$__all'} | ${true} | ${false} | ${['$__all']} ${'$__all'} | ${false} | ${false} | ${['$__all']} ${'$__all'} | ${true} | ${true} | ${['$__all']} ${'$__all'} | ${false} | ${true} | ${['$__all']} `( 'and we toggle $option with options: { forceSelect: $forceSelect, clearOthers: $clearOthers } we expect $expectSelected to be selected', ({ option, forceSelect, clearOthers, expectSelected }) => expectToggleOptionState({ options, multi, option, clearOthers, forceSelect, expectSelected, }) ); }); describe('and value A is selected in options', () => { const options = opsA; it.each` option | forceSelect | clearOthers | expectSelected ${'A'} | ${true} | ${false} | ${['A']} ${'A'} | ${false} | ${false} | ${['$__all']} ${'A'} | ${true} | ${true} | ${['A']} ${'A'} | ${false} | ${true} | ${['$__all']} ${'B'} | ${true} | ${false} | ${['B']} ${'B'} | ${false} | ${false} | ${['B']} ${'B'} | ${true} | ${true} | ${['B']} ${'B'} | ${false} | ${true} | ${['B']} `( 'and we toggle $option with options: { forceSelect: $forceSelect, clearOthers: $clearOthers } we expect $expectSelected to be selected', ({ option, forceSelect, clearOthers, expectSelected }) => expectToggleOptionState({ options, multi, option, clearOthers, forceSelect, expectSelected, }) ); }); }); }); describe('when showOptions is dispatched', () => { it('then correct values should be selected', () => { const { initialState } = getVariableTestContext({}); const payload = { type: 'query', query: '', options: [ { text: 'All', value: '$__all', selected: false }, { text: 'A', value: 'A', selected: false }, { text: 'B', value: 'B', selected: true }, ], multi: false, id: '0', } as QueryVariableModel; reducerTester<OptionsPickerState>() .givenReducer(optionsPickerReducer, cloneDeep(initialState)) .whenActionIsDispatched(showOptions(payload)) .thenStateShouldEqual({ ...initialState, options: payload.options, id: payload.id, multi: payload.multi, selectedValues: [{ text: 'B', value: 'B', selected: true }], queryValue: '', }); }); }); describe('when showOptions is dispatched and picker has queryValue and variable has searchFilter', () => { it('then state should be correct', () => { const query = '*.__searchFilter'; const queryValue = 'a search query'; const selected = { text: 'All', value: '$__all', selected: true }; const { initialState } = getVariableTestContext({}); const payload = { type: 'query', query, options: [selected, { text: 'A', value: 'A', selected: false }, { text: 'B', value: 'B', selected: false }], multi: false, id: '0', queryValue, } as QueryVariableModel; reducerTester<OptionsPickerState>() .givenReducer(optionsPickerReducer, cloneDeep(initialState)) .whenActionIsDispatched(showOptions(payload)) .thenStateShouldEqual({ ...initialState, options: payload.options, queryValue, id: payload.id, multi: payload.multi, selectedValues: [selected], }); }); }); describe('when showOptions is dispatched and queryValue and variable has no searchFilter', () => { it('then state should be correct', () => { const query = '*.'; const queryValue: any = null; const current = { text: ALL_VARIABLE_TEXT, selected: true, value: [ALL_VARIABLE_VALUE] }; const options = [ { text: 'All', value: '$__all', selected: true }, { text: 'A', value: 'A', selected: false }, { text: 'B', value: 'B', selected: false }, ]; const { initialState } = getVariableTestContext({}); const payload = { type: 'query', id: '0', current, query, options, queryValue } as QueryVariableModel; reducerTester<OptionsPickerState>() .givenReducer(optionsPickerReducer, cloneDeep(initialState)) .whenActionIsDispatched(showOptions(payload)) .thenStateShouldEqual({ ...initialState, id: '0', queryValue: '', selectedValues: [ { text: ALL_VARIABLE_TEXT, selected: true, value: ALL_VARIABLE_VALUE, }, ], options: options, }); }); }); describe('when hideOptions is dispatched', () => { it('then state should be correct', () => { const { initialState } = getVariableTestContext({ options: [ { text: 'All', value: '$__all', selected: true }, { text: 'A', value: 'A', selected: false }, { text: 'B', value: 'B', selected: false }, ], queryValue: 'a search', highlightIndex: 1, id: '0', }); reducerTester<OptionsPickerState>() .givenReducer(optionsPickerReducer, cloneDeep(initialState)) .whenActionIsDispatched(hideOptions()) .thenStateShouldEqual({ ...optionsPickerInitialState }); }); }); describe('when toggleTag is dispatched', () => { it('then state should be correct', () => { const { initialState } = getVariableTestContext({ tags: [ { text: 'All A:s', selected: false, values: ['A', 'AA', 'AAA'] }, { text: 'All B:s', selected: false, values: ['B', 'BB', 'BBB'] }, { text: 'All C:s', selected: false, values: ['C', 'CC', 'CCC'] }, ], options: [ { text: 'A', selected: false, value: 'A' }, { text: 'AA', selected: false, value: 'AA' }, { text: 'AAA', selected: false, value: 'AAA' }, { text: 'B', selected: false, value: 'B' }, ], }); const payload: VariableTag = { text: 'All A:s', selected: false, values: ['A', 'AA', 'AAA'] }; reducerTester<OptionsPickerState>() .givenReducer(optionsPickerReducer, cloneDeep(initialState)) .whenActionIsDispatched(toggleTag(payload)) .thenStateShouldEqual({ ...initialState, options: [ { text: 'A', selected: true, value: 'A' }, { text: 'AA', selected: true, value: 'AA' }, { text: 'AAA', selected: true, value: 'AAA' }, { text: 'B', selected: false, value: 'B' }, ], tags: [ { text: 'All A:s', selected: true, values: ['A', 'AA', 'AAA'], valuesText: 'A + AA + AAA' }, { text: 'All B:s', selected: false, values: ['B', 'BB', 'BBB'] }, { text: 'All C:s', selected: false, values: ['C', 'CC', 'CCC'] }, ], selectedValues: [ { text: 'A', selected: true, value: 'A' }, { text: 'AA', selected: true, value: 'AA' }, { text: 'AAA', selected: true, value: 'AAA' }, ], }); }); }); describe('when toggleTag is dispatched when tag is selected', () => { it('then state should be correct', () => { const { initialState } = getVariableTestContext({ tags: [ { text: 'All A:s', selected: true, values: ['A', 'AA', 'AAA'] }, { text: 'All B:s', selected: false, values: ['B', 'BB', 'BBB'] }, { text: 'All C:s', selected: false, values: ['C', 'CC', 'CCC'] }, ], options: [ { text: 'A', selected: true, value: 'A' }, { text: 'AA', selected: true, value: 'AA' }, { text: 'AAA', selected: true, value: 'AAA' }, { text: 'B', selected: false, value: 'B' }, ], }); const payload: VariableTag = { text: 'All A:s', selected: true, values: ['A', 'AA', 'AAA'] }; reducerTester<OptionsPickerState>() .givenReducer(optionsPickerReducer, cloneDeep(initialState)) .whenActionIsDispatched(toggleTag(payload)) .thenStateShouldEqual({ ...initialState, options: [ { text: 'A', selected: false, value: 'A' }, { text: 'AA', selected: false, value: 'AA' }, { text: 'AAA', selected: false, value: 'AAA' }, { text: 'B', selected: false, value: 'B' }, ], tags: [ { text: 'All A:s', selected: false, values: ['A', 'AA', 'AAA'] }, { text: 'All B:s', selected: false, values: ['B', 'BB', 'BBB'] }, { text: 'All C:s', selected: false, values: ['C', 'CC', 'CCC'] }, ], selectedValues: [], }); }); }); describe('when toggleTag is dispatched and ALL is previous selected', () => { it('then state should be correct', () => { const { initialState } = getVariableTestContext({ tags: [ { text: 'All A:s', selected: false, values: ['A', 'AA', 'AAA'] }, { text: 'All B:s', selected: false, values: ['B', 'BB', 'BBB'] }, { text: 'All C:s', selected: false, values: ['C', 'CC', 'CCC'] }, ], options: [ { text: ALL_VARIABLE_TEXT, selected: true, value: ALL_VARIABLE_VALUE }, { text: 'A', selected: false, value: 'A' }, { text: 'AA', selected: false, value: 'AA' }, { text: 'AAA', selected: false, value: 'AAA' }, { text: 'B', selected: false, value: 'B' }, ], }); const payload: VariableTag = { text: 'All A:s', selected: false, values: ['A', 'AA', 'AAA'] }; reducerTester<OptionsPickerState>() .givenReducer(optionsPickerReducer, cloneDeep(initialState)) .whenActionIsDispatched(toggleTag(payload)) .thenStateShouldEqual({ ...initialState, options: [ { text: ALL_VARIABLE_TEXT, selected: false, value: ALL_VARIABLE_VALUE }, { text: 'A', selected: true, value: 'A' }, { text: 'AA', selected: true, value: 'AA' }, { text: 'AAA', selected: true, value: 'AAA' }, { text: 'B', selected: false, value: 'B' }, ], tags: [ { text: 'All A:s', selected: true, values: ['A', 'AA', 'AAA'], valuesText: 'A + AA + AAA' }, { text: 'All B:s', selected: false, values: ['B', 'BB', 'BBB'] }, { text: 'All C:s', selected: false, values: ['C', 'CC', 'CCC'] }, ], selectedValues: [ { text: 'A', selected: true, value: 'A' }, { text: 'AA', selected: true, value: 'AA' }, { text: 'AAA', selected: true, value: 'AAA' }, ], }); }); }); describe('when toggleTag is dispatched and only the tag is previous selected', () => { it('then state should be correct', () => { const { initialState } = getVariableTestContext({ tags: [ { text: 'All A:s', selected: false, values: ['A', 'AA', 'AAA'] }, { text: 'All B:s', selected: false, values: ['B', 'BB', 'BBB'] }, { text: 'All C:s', selected: false, values: ['C', 'CC', 'CCC'] }, { text: 'All D:s', selected: true, values: ['D'] }, ], options: [ { text: ALL_VARIABLE_TEXT, selected: false, value: ALL_VARIABLE_VALUE }, { text: 'A', selected: false, value: 'A' }, { text: 'AA', selected: false, value: 'AA' }, { text: 'AAA', selected: false, value: 'AAA' }, { text: 'B', selected: false, value: 'B' }, ], }); const payload: VariableTag = { text: 'All D:s', selected: true, values: ['D'] }; reducerTester<OptionsPickerState>() .givenReducer(optionsPickerReducer, cloneDeep(initialState)) .whenActionIsDispatched(toggleTag(payload)) .thenStateShouldEqual({ ...initialState, options: [ { text: ALL_VARIABLE_TEXT, selected: true, value: ALL_VARIABLE_VALUE }, { text: 'A', selected: false, value: 'A' }, { text: 'AA', selected: false, value: 'AA' }, { text: 'AAA', selected: false, value: 'AAA' }, { text: 'B', selected: false, value: 'B' }, ], tags: [ { text: 'All A:s', selected: false, values: ['A', 'AA', 'AAA'] }, { text: 'All B:s', selected: false, values: ['B', 'BB', 'BBB'] }, { text: 'All C:s', selected: false, values: ['C', 'CC', 'CCC'] }, { text: 'All D:s', selected: false, values: ['D'] }, ], selectedValues: [{ text: ALL_VARIABLE_TEXT, selected: true, value: ALL_VARIABLE_VALUE }], }); }); }); describe('when changeQueryVariableHighlightIndex is dispatched with -1 and highlightIndex is 0', () => { it('then state should be correct', () => { const { initialState } = getVariableTestContext({ highlightIndex: 0 }); reducerTester<OptionsPickerState>() .givenReducer(optionsPickerReducer, cloneDeep(initialState)) .whenActionIsDispatched(moveOptionsHighlight(-1)) .thenStateShouldEqual({ ...initialState, highlightIndex: 0, }); }); }); describe('when changeQueryVariableHighlightIndex is dispatched with -1 and highlightIndex is 1', () => { it('then state should be correct', () => { const { initialState } = getVariableTestContext({ highlightIndex: 1, options: [ { text: 'A', value: 'A', selected: false }, { text: 'B', value: 'B', selected: false }, ], }); reducerTester<OptionsPickerState>() .givenReducer(optionsPickerReducer, cloneDeep(initialState)) .whenActionIsDispatched(moveOptionsHighlight(-1)) .thenStateShouldEqual({ ...initialState, highlightIndex: 0, }); }); }); describe('when changeQueryVariableHighlightIndex is dispatched with 1 and highlightIndex is same as options.length', () => { it('then state should be correct', () => { const { initialState } = getVariableTestContext({ highlightIndex: 1, options: [ { text: 'A', value: 'A', selected: false }, { text: 'B', value: 'B', selected: false }, ], }); reducerTester<OptionsPickerState>() .givenReducer(optionsPickerReducer, cloneDeep(initialState)) .whenActionIsDispatched(moveOptionsHighlight(1)) .thenStateShouldEqual({ ...initialState, highlightIndex: 1, }); }); }); describe('when changeQueryVariableHighlightIndex is dispatched with 1 and highlightIndex is below options.length', () => { it('then state should be correct', () => { const { initialState } = getVariableTestContext({ highlightIndex: 0, options: [ { text: 'A', value: 'A', selected: false }, { text: 'B', value: 'B', selected: false }, ], }); reducerTester<OptionsPickerState>() .givenReducer(optionsPickerReducer, cloneDeep(initialState)) .whenActionIsDispatched(moveOptionsHighlight(1)) .thenStateShouldEqual({ ...initialState, highlightIndex: 1, }); }); }); describe('when toggleAllOptions is dispatched', () => { it('should toggle all values except All to true', () => { const { initialState } = getVariableTestContext({ options: [ { text: 'All', value: '$__all', selected: false }, { text: 'A', value: 'A', selected: false }, { text: 'B', value: 'B', selected: false }, ], selectedValues: [], multi: true, }); reducerTester<OptionsPickerState>() .givenReducer(optionsPickerReducer, cloneDeep(initialState)) .whenActionIsDispatched(toggleAllOptions()) .thenStateShouldEqual({ ...initialState, options: [ { text: 'All', value: '$__all', selected: false }, { text: 'A', value: 'A', selected: true }, { text: 'B', value: 'B', selected: true }, ], selectedValues: [ { text: 'A', value: 'A', selected: true }, { text: 'B', value: 'B', selected: true }, ], }); }); it('should toggle all values to false when $_all is selected', () => { const { initialState } = getVariableTestContext({ options: [ { text: 'All', value: '$__all', selected: true }, { text: 'A', value: 'A', selected: false }, { text: 'B', value: 'B', selected: false }, ], selectedValues: [{ text: 'All', value: '$__all', selected: true }], multi: true, }); reducerTester<OptionsPickerState>() .givenReducer(optionsPickerReducer, cloneDeep(initialState)) .whenActionIsDispatched(toggleAllOptions()) .thenStateShouldEqual({ ...initialState, options: [ { text: 'All', value: '$__all', selected: false }, { text: 'A', value: 'A', selected: false }, { text: 'B', value: 'B', selected: false }, ], selectedValues: [], }); }); it('should toggle all values to false when a option is selected', () => { const { initialState } = getVariableTestContext({ options: [ { text: 'All', value: '$__all', selected: false }, { text: 'A', value: 'A', selected: false }, { text: 'B', value: 'B', selected: true }, ], selectedValues: [{ text: 'B', value: 'B', selected: true }], multi: true, }); reducerTester<OptionsPickerState>() .givenReducer(optionsPickerReducer, cloneDeep(initialState)) .whenActionIsDispatched(toggleAllOptions()) .thenStateShouldEqual({ ...initialState, options: [ { text: 'All', value: '$__all', selected: false }, { text: 'A', value: 'A', selected: false }, { text: 'B', value: 'B', selected: false }, ], selectedValues: [], }); }); }); describe('when updateOptionsAndFilter is dispatched and searchFilter exists', () => { it('then state should be correct', () => { const searchQuery = 'A'; const options = [ { text: 'All', value: '$__all', selected: true }, { text: 'A', value: 'A', selected: false }, { text: 'B', value: 'B', selected: false }, ]; const { initialState } = getVariableTestContext({ queryValue: searchQuery, }); reducerTester<OptionsPickerState>() .givenReducer(optionsPickerReducer, cloneDeep(initialState)) .whenActionIsDispatched(updateOptionsAndFilter(options)) .thenStateShouldEqual({ ...initialState, options: [ { text: 'All', value: '$__all', selected: true }, { text: 'A', value: 'A', selected: false }, ], selectedValues: [{ text: 'All', value: '$__all', selected: true }], queryValue: searchQuery, highlightIndex: 0, }); }); describe('and option count is are greater then OPTIONS_LIMIT', () => { it('then state should be correct', () => { const searchQuery = 'option:1337'; const options = []; for (let index = 0; index <= OPTIONS_LIMIT + 337; index++) { options.push({ text: `option:${index}`, value: `option:${index}`, selected: false }); } const { initialState } = getVariableTestContext({ queryValue: searchQuery, }); reducerTester<OptionsPickerState>() .givenReducer(optionsPickerReducer, cloneDeep(initialState)) .whenActionIsDispatched(updateOptionsAndFilter(options)) .thenStateShouldEqual({ ...cloneDeep(initialState), options: [{ text: 'option:1337', value: 'option:1337', selected: false }], selectedValues: [], queryValue: 'option:1337', highlightIndex: 0, }); }); }); }); describe('when value is selected and filter is applied but then removed', () => { it('then state should be correct', () => { const searchQuery = 'A'; const options: VariableOption[] = [ { text: 'All', value: '$__all', selected: false }, { text: 'A', value: 'A', selected: false }, { text: 'B', value: 'B', selected: false }, ]; const { initialState } = getVariableTestContext({ options, }); reducerTester<OptionsPickerState>() .givenReducer(optionsPickerReducer, cloneDeep(initialState)) .whenActionIsDispatched(toggleOption({ option: options[2], forceSelect: false, clearOthers: false })) .thenStateShouldEqual({ ...initialState, options: [ { text: 'All', value: '$__all', selected: false }, { text: 'A', value: 'A', selected: false }, { text: 'B', value: 'B', selected: true }, ], selectedValues: [{ text: 'B', value: 'B', selected: true }], }) .whenActionIsDispatched(updateSearchQuery(searchQuery)) .thenStateShouldEqual({ ...initialState, options: [ { text: 'All', value: '$__all', selected: false }, { text: 'A', value: 'A', selected: false }, { text: 'B', value: 'B', selected: true }, ], selectedValues: [{ text: 'B', value: 'B', selected: true }], queryValue: searchQuery, }) .whenActionIsDispatched(updateOptionsAndFilter(options)) .thenStateShouldEqual({ ...initialState, options: [ { text: 'All', value: '$__all', selected: false }, { text: 'A', value: 'A', selected: false }, ], selectedValues: [{ text: 'B', value: 'B', selected: true }], queryValue: searchQuery, highlightIndex: 0, }) .whenActionIsDispatched(updateSearchQuery('')) .thenStateShouldEqual({ ...initialState, options: [ { text: 'All', value: '$__all', selected: false }, { text: 'A', value: 'A', selected: false }, ], selectedValues: [{ text: 'B', value: 'B', selected: true }], queryValue: '', highlightIndex: 0, }) .whenActionIsDispatched(updateOptionsAndFilter(options)) .thenStateShouldEqual({ ...initialState, options: [ { text: 'All', value: '$__all', selected: false }, { text: 'A', value: 'A', selected: false }, { text: 'B', value: 'B', selected: true }, ], selectedValues: [{ text: 'B', value: 'B', selected: true }], queryValue: '', highlightIndex: 0, }); }); }); describe('when value is toggled back and forth', () => { it('then state should be correct', () => { const options: VariableOption[] = [ { text: 'All', value: '$__all', selected: false }, { text: 'A', value: 'A', selected: false }, { text: 'B', value: 'B', selected: false }, ]; const toggleOptionAction = toggleOption({ option: options[2], forceSelect: false, clearOthers: false, }); const { initialState } = getVariableTestContext({ options, }); reducerTester<OptionsPickerState>() .givenReducer(optionsPickerReducer, cloneDeep(initialState)) .whenActionIsDispatched(toggleOptionAction) .thenStateShouldEqual({ ...initialState, options: [ { text: 'All', value: '$__all', selected: false }, { text: 'A', value: 'A', selected: false }, { text: 'B', value: 'B', selected: true }, ], selectedValues: [{ text: 'B', value: 'B', selected: true }], }) .whenActionIsDispatched(toggleOptionAction) .thenStateShouldEqual({ ...initialState, options: [ { text: 'All', value: '$__all', selected: true }, { text: 'A', value: 'A', selected: false }, { text: 'B', value: 'B', selected: false }, ], selectedValues: [{ text: 'All', value: '$__all', selected: true }], }); }); }); describe('when updateOptionsFromSearch is dispatched and variable has searchFilter', () => { it('then state should be correct', () => { const searchQuery = '__searchFilter'; const options = [ { text: 'All', value: '$__all', selected: true }, { text: 'A', value: 'A', selected: false }, { text: 'B', value: 'B', selected: false }, ]; const { initialState } = getVariableTestContext({ queryValue: searchQuery, }); reducerTester<OptionsPickerState>() .givenReducer(optionsPickerReducer, cloneDeep(initialState)) .whenActionIsDispatched(updateOptionsFromSearch(options)) .thenStateShouldEqual({ ...initialState, options: options, selectedValues: [{ text: 'All', value: '$__all', selected: true }], highlightIndex: 0, }); }); }); describe('when updateSearchQuery is dispatched', () => { it('then state should be correct', () => { const searchQuery = 'A'; const { initialState } = getVariableTestContext({}); reducerTester<OptionsPickerState>() .givenReducer(optionsPickerReducer, cloneDeep(initialState)) .whenActionIsDispatched(updateSearchQuery(searchQuery)) .thenStateShouldEqual({ ...initialState, queryValue: searchQuery, }); }); }); describe('when large data for updateOptionsAndFilter', () => { it('then state should be correct', () => { const searchQuery = 'option:11256'; const options: VariableOption[] = []; for (let index = 0; index <= OPTIONS_LIMIT + 11256; index++) { options.push({ text: `option:${index}`, value: `option:${index}`, selected: false }); } const { initialState } = getVariableTestContext({ queryValue: searchQuery, }); reducerTester<OptionsPickerState>() .givenReducer(optionsPickerReducer, cloneDeep(initialState)) .whenActionIsDispatched(updateOptionsAndFilter(options)) .thenStateShouldEqual({ ...cloneDeep(initialState), options: [{ text: 'option:11256', value: 'option:11256', selected: false }], selectedValues: [], queryValue: 'option:11256', highlightIndex: 0, }); }); }); describe('when large data for updateOptionsFromSearch is dispatched and variable has searchFilter', () => { it('then state should be correct', () => { const searchQuery = '__searchFilter'; const options = [{ text: 'All', value: '$__all', selected: true }]; for (let i = 0; i <= OPTIONS_LIMIT + 137; i++) { options.push({ text: `option${i}`, value: `option${i}`, selected: false }); } const { initialState } = getVariableTestContext({ queryValue: searchQuery, }); reducerTester<OptionsPickerState>() .givenReducer(optionsPickerReducer, cloneDeep(initialState)) .whenActionIsDispatched(updateOptionsFromSearch(options)) .thenStateShouldEqual({ ...initialState, options: options.slice(0, OPTIONS_LIMIT), selectedValues: [{ text: 'All', value: '$__all', selected: true }], highlightIndex: 0, }); }); }); describe('when large data for showOptions', () => { it('then state should be correct', () => { const { initialState } = getVariableTestContext({}); const payload = { type: 'query', query: '', options: [{ text: 'option0', value: 'option0', selected: false }], multi: false, id: '0', } as QueryVariableModel; const checkOptions = []; for (let index = 0; index < OPTIONS_LIMIT; index++) { checkOptions.push({ text: `option${index}`, value: `option${index}`, selected: false }); } for (let i = 1; i <= OPTIONS_LIMIT + 137; i++) { payload.options.push({ text: `option${i}`, value: `option${i}`, selected: false }); } reducerTester<OptionsPickerState>() .givenReducer(optionsPickerReducer, cloneDeep(initialState)) .whenActionIsDispatched(showOptions(payload)) .thenStateShouldEqual({ ...initialState, options: checkOptions, id: '0', multi: false, queryValue: '', }); }); }); describe('when cleanPickerState is dispatched', () => { it('then state should be correct', () => { const { initialState } = getVariableTestContext({ highlightIndex: 19, multi: true, id: 'some id', options: [{ text: 'A', value: 'A', selected: true }], queryValue: 'a query value', selectedValues: [{ text: 'A', value: 'A', selected: true }], }); reducerTester<OptionsPickerState>() .givenReducer(optionsPickerReducer, cloneDeep(initialState)) .whenActionIsDispatched(cleanPickerState()) .thenStateShouldEqual({ ...optionsPickerInitialState }); }); }); });
public/app/features/variables/pickers/OptionsPicker/reducer.test.ts
0
https://github.com/grafana/grafana/commit/ae64dcf0638e1b860dd3e56cdd97abb7c90833c0
[ 0.0012381584383547306, 0.00018884529708884656, 0.0001640317786950618, 0.00017162945005111396, 0.00011831432493636385 ]
{ "id": 6, "code_window": [ " const slos = await datasource.getServiceLevelObjectives(query.projectName, query.serviceId);\n", " const slo = slos.find(({ value }) => value === datasource.templateSrv.replace(sloId));\n", " onChange({ ...query, sloId, goal: slo?.goal });\n", " }}\n", " />\n", " </QueryInlineField>\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " onChange({ ...query, sloId, sloName, goal: slo?.goal });\n" ], "file_path": "public/app/plugins/datasource/cloud-monitoring/components/SLOQueryEditor.tsx", "type": "replace", "edit_start_line_idx": 76 }
import React from 'react'; import { Segment, SegmentAsync } from '@grafana/ui'; import { SelectableValue } from '@grafana/data'; import { selectors } from '../constants'; import { Project, AlignmentPeriods, AliasBy, QueryInlineField } from '.'; import { SLOQuery } from '../types'; import CloudMonitoringDatasource from '../datasource'; export interface Props { usedAlignmentPeriod?: number; variableOptionGroup: SelectableValue<string>; onChange: (query: SLOQuery) => void; onRunQuery: () => void; query: SLOQuery; datasource: CloudMonitoringDatasource; } export const defaultQuery: (dataSource: CloudMonitoringDatasource) => SLOQuery = (dataSource) => ({ projectName: dataSource.getDefaultProject(), alignmentPeriod: 'cloud-monitoring-auto', aliasBy: '', selectorName: 'select_slo_health', serviceId: '', sloId: '', }); export function SLOQueryEditor({ query, datasource, onChange, variableOptionGroup, usedAlignmentPeriod, }: React.PropsWithChildren<Props>) { return ( <> <Project templateVariableOptions={variableOptionGroup.options} projectName={query.projectName} datasource={datasource} onChange={(projectName) => onChange({ ...query, projectName })} /> <QueryInlineField label="Service"> <SegmentAsync allowCustomValue value={query?.serviceId} placeholder="Select service" loadOptions={() => datasource.getSLOServices(query.projectName).then((services) => [ { label: 'Template Variables', options: variableOptionGroup.options, }, ...services, ]) } onChange={({ value: serviceId = '' }) => onChange({ ...query, serviceId, sloId: '' })} /> </QueryInlineField> <QueryInlineField label="SLO"> <SegmentAsync allowCustomValue value={query?.sloId} placeholder="Select SLO" loadOptions={() => datasource.getServiceLevelObjectives(query.projectName, query.serviceId).then((sloIds) => [ { label: 'Template Variables', options: variableOptionGroup.options, }, ...sloIds, ]) } onChange={async ({ value: sloId = '' }) => { const slos = await datasource.getServiceLevelObjectives(query.projectName, query.serviceId); const slo = slos.find(({ value }) => value === datasource.templateSrv.replace(sloId)); onChange({ ...query, sloId, goal: slo?.goal }); }} /> </QueryInlineField> <QueryInlineField label="Selector"> <Segment allowCustomValue value={[...selectors, ...variableOptionGroup.options].find((s) => s.value === query?.selectorName ?? '')} options={[ { label: 'Template Variables', options: variableOptionGroup.options, }, ...selectors, ]} onChange={({ value: selectorName }) => onChange({ ...query, selectorName })} /> </QueryInlineField> <AlignmentPeriods templateSrv={datasource.templateSrv} templateVariableOptions={variableOptionGroup.options} alignmentPeriod={query.alignmentPeriod || ''} perSeriesAligner={query.selectorName === 'select_slo_health' ? 'ALIGN_MEAN' : 'ALIGN_NEXT_OLDER'} usedAlignmentPeriod={usedAlignmentPeriod} onChange={(alignmentPeriod) => onChange({ ...query, alignmentPeriod })} /> <AliasBy value={query.aliasBy} onChange={(aliasBy) => onChange({ ...query, aliasBy })} /> </> ); }
public/app/plugins/datasource/cloud-monitoring/components/SLOQueryEditor.tsx
1
https://github.com/grafana/grafana/commit/ae64dcf0638e1b860dd3e56cdd97abb7c90833c0
[ 0.9986574649810791, 0.09712932258844376, 0.00017224917246494442, 0.002833345904946327, 0.28525015711784363 ]
{ "id": 6, "code_window": [ " const slos = await datasource.getServiceLevelObjectives(query.projectName, query.serviceId);\n", " const slo = slos.find(({ value }) => value === datasource.templateSrv.replace(sloId));\n", " onChange({ ...query, sloId, goal: slo?.goal });\n", " }}\n", " />\n", " </QueryInlineField>\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " onChange({ ...query, sloId, sloName, goal: slo?.goal });\n" ], "file_path": "public/app/plugins/datasource/cloud-monitoring/components/SLOQueryEditor.tsx", "type": "replace", "edit_start_line_idx": 76 }
JSONNET_FMT="jsonnetfmt -n 2 --max-blank-lines 2 --string-style s --comment-style s"
grafana-mixin/scripts/common.sh
0
https://github.com/grafana/grafana/commit/ae64dcf0638e1b860dd3e56cdd97abb7c90833c0
[ 0.00016843419871293008, 0.00016843419871293008, 0.00016843419871293008, 0.00016843419871293008, 0 ]
{ "id": 6, "code_window": [ " const slos = await datasource.getServiceLevelObjectives(query.projectName, query.serviceId);\n", " const slo = slos.find(({ value }) => value === datasource.templateSrv.replace(sloId));\n", " onChange({ ...query, sloId, goal: slo?.goal });\n", " }}\n", " />\n", " </QueryInlineField>\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " onChange({ ...query, sloId, sloName, goal: slo?.goal });\n" ], "file_path": "public/app/plugins/datasource/cloud-monitoring/components/SLOQueryEditor.tsx", "type": "replace", "edit_start_line_idx": 76 }
export * from './DataFrameView'; export * from './FieldCache'; export * from './CircularDataFrame'; export * from './MutableDataFrame'; export * from './processDataFrame'; export * from './dimensions'; export * from './ArrowDataFrame'; export * from './ArrayDataFrame'; export * from './frameComparisons';
packages/grafana-data/src/dataframe/index.ts
0
https://github.com/grafana/grafana/commit/ae64dcf0638e1b860dd3e56cdd97abb7c90833c0
[ 0.0001721949956845492, 0.0001721949956845492, 0.0001721949956845492, 0.0001721949956845492, 0 ]
{ "id": 6, "code_window": [ " const slos = await datasource.getServiceLevelObjectives(query.projectName, query.serviceId);\n", " const slo = slos.find(({ value }) => value === datasource.templateSrv.replace(sloId));\n", " onChange({ ...query, sloId, goal: slo?.goal });\n", " }}\n", " />\n", " </QueryInlineField>\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " onChange({ ...query, sloId, sloName, goal: slo?.goal });\n" ], "file_path": "public/app/plugins/datasource/cloud-monitoring/components/SLOQueryEditor.tsx", "type": "replace", "edit_start_line_idx": 76 }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width" /> <style>body { width: 100% !important; min-width: 100%; -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; margin: 0; padding: 0; } img { outline: none; text-decoration: none; -ms-interpolation-mode: bicubic; width: auto; float: left; clear: both; display: block; } body { color: #222222; font-family: "Helvetica", "Arial", sans-serif; font-weight: normal; padding: 0; margin: 0; text-align: left; line-height: 1.3; } body { font-size: 14px; line-height: 19px; } a:hover { color: #2795b6 !important; } a:active { color: #2795b6 !important; } a:visited { color: #2ba6cb !important; } body { font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; } a:hover { color: #ff8f2b !important; } a:active { color: #F2821E !important; } a:visited { color: #E67612 !important; } .better-button:hover a { color: #FFFFFF !important; background-color: #F2821E; border: 1px solid #F2821E; } .better-button:visited a { color: #FFFFFF !important; } .better-button:active a { color: #FFFFFF !important; } .better-button-alt:hover a { color: #ff8f2b !important; background-color: #DDDDDD; border: 1px solid #F2821E; } .better-button-alt:visited a { color: #ff8f2b !important; } .better-button-alt:active a { color: #ff8f2b !important; } body { height: 100% !important; width: 100% !important; } body .copy { -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; } .ExternalClass { width: 100%; } .ExternalClass { line-height: 100%; } img { -ms-interpolation-mode: bicubic; } img { border: 0 !important; outline: none !important; text-decoration: none !important; } a:hover { text-decoration: underline; } @media only screen and (max-width: 600px) { table[class="body"] center { min-width: 0 !important; } table[class="body"] .container { width: 95% !important; } table[class="body"] .row { width: 100% !important; display: block !important; } table[class="body"] .wrapper { display: block !important; padding-right: 0 !important; } table[class="body"] .columns { table-layout: fixed !important; float: none !important; width: 100% !important; padding-right: 0px !important; padding-left: 0px !important; display: block !important; } table[class="body"] table.columns td { width: 100% !important; } table[class="body"] .columns td.six { width: 50% !important; } table[class="body"] .columns td.twelve { width: 100% !important; } table[class="body"] table.columns td.expander { width: 1px !important; } .logo { margin-left: 10px; } } @media (max-width: 600px) { table[class="email-container"] { width: 95% !important; } img[class="fluid"] { width: 100% !important; max-width: 100% !important; height: auto !important; margin: auto !important; } img[class="fluid-centered"] { width: 100% !important; max-width: 100% !important; height: auto !important; margin: auto !important; } img[class="fluid-centered"] { margin: auto !important; } td[class="comms-content"] { padding: 20px !important; } td[class="stack-column"] { display: block !important; width: 100% !important; direction: ltr !important; } td[class="stack-column-center"] { display: block !important; width: 100% !important; direction: ltr !important; } td[class="stack-column-center"] { text-align: center !important; } td[class="copy"] { font-size: 14px !important; line-height: 24px !important; padding: 0 30px !important; } td[class="copy -center"] { font-size: 14px !important; line-height: 24px !important; padding: 0 30px !important; } td[class="copy -bold"] { font-size: 14px !important; line-height: 24px !important; padding: 0 30px !important; } td[class="small-text"] { font-size: 14px !important; line-height: 24px !important; padding: 0 30px !important; } td[class="mini-centered-text"] { font-size: 14px !important; line-height: 24px !important; padding: 15px 30px !important; } td[class="copy -padd"] { padding: 0 40px !important; } span[class="sep"] { display: none !important; } td[class="mb-hide"] { display: none !important; height: 0 !important; } td[class="spacer mb-shorten"] { height: 25px !important; } .two-up td { width: 270px; } } </style></head> <body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0" class="main" style="height: 100% !important; width: 100% !important; min-width: 100%; -webkit-text-size-adjust: none; -ms-text-size-adjust: 100%; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; text-align: left; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; margin: 0 auto; padding: 0;" bgcolor="#2e2e2e"> <table class="body" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: left; height: 100%; width: 100%; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0;" bgcolor="#2e2e2e"> <tr style="vertical-align: top; padding: 0;" align="left"> <td class="center" align="center" valign="top" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0;"> <center style="width: 100%; min-width: 580px;"> <table class="row header" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: left; width: 100%; position: relative; margin-top: 25px; margin-bottom: 25px; padding: 0px;"> <tr style="vertical-align: top; padding: 0;" align="left"> <td class="center" align="center" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0;" valign="top"> <center style="width: 100%; min-width: 580px;"> <table class="container" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: inherit; width: 580px; margin: 0 auto; padding: 0;"> <tr style="vertical-align: top; padding: 0;" align="left"> <td class="wrapper last" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; position: relative; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 10px 0px 0px;" align="left" valign="top"> <table class="twelve columns" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: left; width: 580px; margin: 0 auto; padding: 0;"> <tr style="vertical-align: top; padding: 0;" align="left"> <td class="twelve sub-columns center" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; min-width: 0px; width: 100%; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0px 10px 10px 0px;" align="center" valign="top"> <img class="logo" src="http://grafana.org/assets/img/logo_new_transparent_200x48.png" style="width: 200px; display: inline; outline: none !important; text-decoration: none !important; -ms-interpolation-mode: bicubic; clear: both; border: 0;" align="none" /> </td> <td class="expander" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; visibility: hidden; width: 0px; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0;" align="left" valign="top"></td> </tr> </table> </td> </tr> </table> </center> </td> </tr> </table> <table class="container" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: inherit; width: 580px; margin: 0 auto; padding: 0;" width="600" bgcolor="#efefef"> <tr style="vertical-align: top; padding: 0;" align="left"> <td height="2" class="spacer mb-shorten" style="font-size: 0; line-height: 0; mso-table-lspace: 0pt; mso-table-rspace: 0pt; background-image: linear-gradient(to right, #ffed00 0%, #f26529 75%); height: 2px !important; word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0; border: 0;" valign="top" align="left"> </td> </tr> <tr style="vertical-align: top; padding: 0;" align="left"> <td class="mini-centered-text" style="color: #343b41; mso-table-lspace: 0pt; mso-table-rspace: 0pt; word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 25px 35px; font: 400 16px/27px 'Helvetica Neue', Helvetica, Arial, sans-serif;" align="center" valign="top"> {{Subject .Subject "{{.InvitedBy}} has invited you to join Grafana"}} <table class="row" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: left; width: 100%; position: relative; display: block; padding: 0px;"> <tr style="vertical-align: top; padding: 0;" align="left"> <td class="wrapper last" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; position: relative; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 10px 0px 0px;" align="left" valign="top"> <table class="twelve columns" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: left; width: 580px; margin: 0 auto; padding: 0;"> <tr style="vertical-align: top; padding: 0;" align="left"> <td style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0px 0px 10px;" align="left" valign="top"> <h4 class="center" style="color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 1.3; word-break: normal; font-size: 20px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0;" align="center">You're invited to join {{.OrgName}}</h4> </td> <td class="expander" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; visibility: hidden; width: 0px; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0;" align="left" valign="top"></td> </tr> </table> </td> </tr> </table> <table class="row" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: left; width: 100%; position: relative; display: block; padding: 0px;"> <tr style="vertical-align: top; padding: 0;" align="left"> <td class="wrapper last" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; position: relative; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 10px 0px 0px;" align="left" valign="top"> <table class="twelve columns" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: left; width: 580px; margin: 0 auto; padding: 0;"> <tr style="vertical-align: top; padding: 0;" align="left"> <td class="center" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0px 0px 10px;" align="center" valign="top"> <p style="color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0 0 10px; padding: 0;" align="left">You've been invited to join the <b>{{.OrgName}}</b> organization by <b>{{.InvitedBy}}</b>. To accept your invitation and join the team, please click the link below:</p> </td> </tr> <tr style="vertical-align: top; padding: 0;" align="left"> <td class="center" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0px 0px 10px;" align="center" valign="top"> <table class="better-button" align="center" border="0" cellspacing="0" cellpadding="0" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: left; margin-top: 10px; margin-bottom: 20px; padding: 0;"> <tr style="vertical-align: top; padding: 0;" align="left"> <td align="center" class="better-button" bgcolor="#ff8f2b" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; -webkit-border-radius: 2px; -moz-border-radius: 2px; border-radius: 2px; margin: 0; padding: 0px;" valign="top"><a href="{{.LinkUrl}}" target="_blank" style="color: #FFF; text-decoration: none; -webkit-border-radius: 2px; -moz-border-radius: 2px; border-radius: 2px; display: inline-block; padding: 12px 25px; border: 1px solid #ff8f2b;">Accept Invitation</a></td> </tr> </table> </td> </tr> <tr style="vertical-align: top; padding: 0;" align="left"> <td class="center" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0px 0px 10px;" align="center" valign="top"> <p style="color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0 0 10px; padding: 0;" align="left">You can also copy/paste this link into your browser directly: <a href="{{.LinkUrl}}" style="color: #E67612; text-decoration: none;">{{.LinkUrl}}</a></p> </td> <td class="expander" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; visibility: hidden; width: 0px; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0;" align="left" valign="top"></td> </tr> </table> </td> </tr> </table> </td> </tr> </table> <table class="footer center" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: center; color: #999999; margin-top: 20px; padding: 0;" bgcolor="#2e2e2e"> <tr style="vertical-align: top; padding: 0;" align="left"> <td class="wrapper last" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; position: relative; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 10px 20px 0px 0px;" align="left" valign="top"> <table class="twelve columns center" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: center; width: 580px; margin: 0 auto; padding: 0;"> <tr style="vertical-align: top; padding: 0;" align="left"> <td class="twelve" align="center" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; width: 100%; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0px 0px 10px;" valign="top"> <center style="width: 100%; min-width: 580px;"> <p style="font-size: 12px; color: #999999; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0 0 10px; padding: 0;" align="center"> Sent by <a href="{{.AppUrl}}" style="color: #E67612; text-decoration: none;">Grafana v{{.BuildVersion}}</a> <br />© 2021 Grafana Labs </p> </center> </td> <td class="expander" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; visibility: hidden; width: 0px; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0;" align="left" valign="top"></td> </tr> </table> </td> </tr> </table> </center> </td> </tr> </table> </body> </html>
public/emails/new_user_invite.html
0
https://github.com/grafana/grafana/commit/ae64dcf0638e1b860dd3e56cdd97abb7c90833c0
[ 0.00019263206922914833, 0.0001726019982015714, 0.0001642875577090308, 0.00017237225256394595, 0.000004966699179931311 ]
{ "id": 7, "code_window": [ " }\n", "\n", " async getSLOServices(projectName: string): Promise<Array<SelectableValue<string>>> {\n", " return this.api.get(`${this.templateSrv.replace(projectName)}/services?pageSize=1000`, {\n", " responseMap: ({ name }: { name: string }) => ({\n", " value: name.match(/([^\\/]*)\\/*$/)![1],\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " responseMap: ({ name, displayName }: { name: string; displayName: string }) => ({\n" ], "file_path": "public/app/plugins/datasource/cloud-monitoring/datasource.ts", "type": "replace", "edit_start_line_idx": 259 }
import React from 'react'; import { Segment, SegmentAsync } from '@grafana/ui'; import { SelectableValue } from '@grafana/data'; import { selectors } from '../constants'; import { Project, AlignmentPeriods, AliasBy, QueryInlineField } from '.'; import { SLOQuery } from '../types'; import CloudMonitoringDatasource from '../datasource'; export interface Props { usedAlignmentPeriod?: number; variableOptionGroup: SelectableValue<string>; onChange: (query: SLOQuery) => void; onRunQuery: () => void; query: SLOQuery; datasource: CloudMonitoringDatasource; } export const defaultQuery: (dataSource: CloudMonitoringDatasource) => SLOQuery = (dataSource) => ({ projectName: dataSource.getDefaultProject(), alignmentPeriod: 'cloud-monitoring-auto', aliasBy: '', selectorName: 'select_slo_health', serviceId: '', sloId: '', }); export function SLOQueryEditor({ query, datasource, onChange, variableOptionGroup, usedAlignmentPeriod, }: React.PropsWithChildren<Props>) { return ( <> <Project templateVariableOptions={variableOptionGroup.options} projectName={query.projectName} datasource={datasource} onChange={(projectName) => onChange({ ...query, projectName })} /> <QueryInlineField label="Service"> <SegmentAsync allowCustomValue value={query?.serviceId} placeholder="Select service" loadOptions={() => datasource.getSLOServices(query.projectName).then((services) => [ { label: 'Template Variables', options: variableOptionGroup.options, }, ...services, ]) } onChange={({ value: serviceId = '' }) => onChange({ ...query, serviceId, sloId: '' })} /> </QueryInlineField> <QueryInlineField label="SLO"> <SegmentAsync allowCustomValue value={query?.sloId} placeholder="Select SLO" loadOptions={() => datasource.getServiceLevelObjectives(query.projectName, query.serviceId).then((sloIds) => [ { label: 'Template Variables', options: variableOptionGroup.options, }, ...sloIds, ]) } onChange={async ({ value: sloId = '' }) => { const slos = await datasource.getServiceLevelObjectives(query.projectName, query.serviceId); const slo = slos.find(({ value }) => value === datasource.templateSrv.replace(sloId)); onChange({ ...query, sloId, goal: slo?.goal }); }} /> </QueryInlineField> <QueryInlineField label="Selector"> <Segment allowCustomValue value={[...selectors, ...variableOptionGroup.options].find((s) => s.value === query?.selectorName ?? '')} options={[ { label: 'Template Variables', options: variableOptionGroup.options, }, ...selectors, ]} onChange={({ value: selectorName }) => onChange({ ...query, selectorName })} /> </QueryInlineField> <AlignmentPeriods templateSrv={datasource.templateSrv} templateVariableOptions={variableOptionGroup.options} alignmentPeriod={query.alignmentPeriod || ''} perSeriesAligner={query.selectorName === 'select_slo_health' ? 'ALIGN_MEAN' : 'ALIGN_NEXT_OLDER'} usedAlignmentPeriod={usedAlignmentPeriod} onChange={(alignmentPeriod) => onChange({ ...query, alignmentPeriod })} /> <AliasBy value={query.aliasBy} onChange={(aliasBy) => onChange({ ...query, aliasBy })} /> </> ); }
public/app/plugins/datasource/cloud-monitoring/components/SLOQueryEditor.tsx
1
https://github.com/grafana/grafana/commit/ae64dcf0638e1b860dd3e56cdd97abb7c90833c0
[ 0.9991480112075806, 0.091513991355896, 0.00016721752763260156, 0.0001843507488956675, 0.28702154755592346 ]
{ "id": 7, "code_window": [ " }\n", "\n", " async getSLOServices(projectName: string): Promise<Array<SelectableValue<string>>> {\n", " return this.api.get(`${this.templateSrv.replace(projectName)}/services?pageSize=1000`, {\n", " responseMap: ({ name }: { name: string }) => ({\n", " value: name.match(/([^\\/]*)\\/*$/)![1],\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " responseMap: ({ name, displayName }: { name: string; displayName: string }) => ({\n" ], "file_path": "public/app/plugins/datasource/cloud-monitoring/datasource.ts", "type": "replace", "edit_start_line_idx": 259 }
package quota import ( "errors" "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/registry" "github.com/grafana/grafana/pkg/setting" ) var ErrInvalidQuotaTarget = errors.New("invalid quota target") func init() { registry.RegisterService(&QuotaService{}) } type QuotaService struct { AuthTokenService models.UserTokenService `inject:""` Cfg *setting.Cfg `inject:""` } func (qs *QuotaService) Init() error { return nil } func (qs *QuotaService) QuotaReached(c *models.ReqContext, target string) (bool, error) { if !qs.Cfg.Quota.Enabled { return false, nil } // No request context means this is a background service, like LDAP Background Sync. // TODO: we should replace the req context with a more limited interface or struct, // something that we could easily provide from background jobs. if c == nil { return false, nil } // get the list of scopes that this target is valid for. Org, User, Global scopes, err := qs.getQuotaScopes(target) if err != nil { return false, err } for _, scope := range scopes { c.Logger.Debug("Checking quota", "target", target, "scope", scope) switch scope.Name { case "global": if scope.DefaultLimit < 0 { continue } if scope.DefaultLimit == 0 { return true, nil } if target == "session" { usedSessions, err := qs.AuthTokenService.ActiveTokenCount(c.Req.Context()) if err != nil { return false, err } if usedSessions > scope.DefaultLimit { c.Logger.Debug("Sessions limit reached", "active", usedSessions, "limit", scope.DefaultLimit) return true, nil } continue } query := models.GetGlobalQuotaByTargetQuery{Target: scope.Target} if err := bus.Dispatch(&query); err != nil { return true, err } if query.Result.Used >= scope.DefaultLimit { return true, nil } case "org": if !c.IsSignedIn { continue } query := models.GetOrgQuotaByTargetQuery{OrgId: c.OrgId, Target: scope.Target, Default: scope.DefaultLimit} if err := bus.Dispatch(&query); err != nil { return true, err } if query.Result.Limit < 0 { continue } if query.Result.Limit == 0 { return true, nil } if query.Result.Used >= query.Result.Limit { return true, nil } case "user": if !c.IsSignedIn || c.UserId == 0 { continue } query := models.GetUserQuotaByTargetQuery{UserId: c.UserId, Target: scope.Target, Default: scope.DefaultLimit} if err := bus.Dispatch(&query); err != nil { return true, err } if query.Result.Limit < 0 { continue } if query.Result.Limit == 0 { return true, nil } if query.Result.Used >= query.Result.Limit { return true, nil } } } return false, nil } func (qs *QuotaService) getQuotaScopes(target string) ([]models.QuotaScope, error) { scopes := make([]models.QuotaScope, 0) switch target { case "user": scopes = append(scopes, models.QuotaScope{Name: "global", Target: target, DefaultLimit: qs.Cfg.Quota.Global.User}, models.QuotaScope{Name: "org", Target: "org_user", DefaultLimit: qs.Cfg.Quota.Org.User}, ) return scopes, nil case "org": scopes = append(scopes, models.QuotaScope{Name: "global", Target: target, DefaultLimit: qs.Cfg.Quota.Global.Org}, models.QuotaScope{Name: "user", Target: "org_user", DefaultLimit: qs.Cfg.Quota.User.Org}, ) return scopes, nil case "dashboard": scopes = append(scopes, models.QuotaScope{Name: "global", Target: target, DefaultLimit: qs.Cfg.Quota.Global.Dashboard}, models.QuotaScope{Name: "org", Target: target, DefaultLimit: qs.Cfg.Quota.Org.Dashboard}, ) return scopes, nil case "data_source": scopes = append(scopes, models.QuotaScope{Name: "global", Target: target, DefaultLimit: qs.Cfg.Quota.Global.DataSource}, models.QuotaScope{Name: "org", Target: target, DefaultLimit: qs.Cfg.Quota.Org.DataSource}, ) return scopes, nil case "api_key": scopes = append(scopes, models.QuotaScope{Name: "global", Target: target, DefaultLimit: qs.Cfg.Quota.Global.ApiKey}, models.QuotaScope{Name: "org", Target: target, DefaultLimit: qs.Cfg.Quota.Org.ApiKey}, ) return scopes, nil case "session": scopes = append(scopes, models.QuotaScope{Name: "global", Target: target, DefaultLimit: qs.Cfg.Quota.Global.Session}, ) return scopes, nil default: return scopes, ErrInvalidQuotaTarget } }
pkg/services/quota/quota.go
0
https://github.com/grafana/grafana/commit/ae64dcf0638e1b860dd3e56cdd97abb7c90833c0
[ 0.0001788941735867411, 0.0001732085511321202, 0.0001654070074437186, 0.00017483538249507546, 0.0000042879755710600875 ]
{ "id": 7, "code_window": [ " }\n", "\n", " async getSLOServices(projectName: string): Promise<Array<SelectableValue<string>>> {\n", " return this.api.get(`${this.templateSrv.replace(projectName)}/services?pageSize=1000`, {\n", " responseMap: ({ name }: { name: string }) => ({\n", " value: name.match(/([^\\/]*)\\/*$/)![1],\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " responseMap: ({ name, displayName }: { name: string; displayName: string }) => ({\n" ], "file_path": "public/app/plugins/datasource/cloud-monitoring/datasource.ts", "type": "replace", "edit_start_line_idx": 259 }
# # config file version apiVersion: 1 # notifiers: # - name: default-slack-temp # type: slack # org_name: Main Org. # is_default: true # uid: notifier1 # settings: # recipient: "XXX" # token: "xoxb" # uploadImage: true # url: https://slack.com # - name: default-email # type: email # org_id: 1 # uid: notifier2 # is_default: false # settings: # addresses: [email protected] # delete_notifiers: # - name: default-slack-temp # org_name: Main Org. # uid: notifier1
conf/provisioning/notifiers/sample.yaml
0
https://github.com/grafana/grafana/commit/ae64dcf0638e1b860dd3e56cdd97abb7c90833c0
[ 0.00017673501861281693, 0.00017542591376695782, 0.00017392548033967614, 0.00017561725690029562, 0.0000011549412874956033 ]
{ "id": 7, "code_window": [ " }\n", "\n", " async getSLOServices(projectName: string): Promise<Array<SelectableValue<string>>> {\n", " return this.api.get(`${this.templateSrv.replace(projectName)}/services?pageSize=1000`, {\n", " responseMap: ({ name }: { name: string }) => ({\n", " value: name.match(/([^\\/]*)\\/*$/)![1],\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " responseMap: ({ name, displayName }: { name: string; displayName: string }) => ({\n" ], "file_path": "public/app/plugins/datasource/cloud-monitoring/datasource.ts", "type": "replace", "edit_start_line_idx": 259 }
FROM prom/prometheus:v2.7.2 ADD prometheus.yml /etc/prometheus/ ADD recording.yml /etc/prometheus/ ADD alert.yml /etc/prometheus/
devenv/docker/blocks/prometheus2/Dockerfile
0
https://github.com/grafana/grafana/commit/ae64dcf0638e1b860dd3e56cdd97abb7c90833c0
[ 0.00017546411254443228, 0.00017546411254443228, 0.00017546411254443228, 0.00017546411254443228, 0 ]
{ "id": 8, "code_window": [ " value: name.match(/([^\\/]*)\\/*$/)![1],\n", " label: name.match(/([^\\/]*)\\/*$/)![1],\n", " }),\n", " });\n", " }\n", "\n", " async getServiceLevelObjectives(projectName: string, serviceId: string): Promise<Array<SelectableValue<string>>> {\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " label: displayName || name.match(/([^\\/]*)\\/*$/)![1],\n" ], "file_path": "public/app/plugins/datasource/cloud-monitoring/datasource.ts", "type": "replace", "edit_start_line_idx": 261 }
import React from 'react'; import { Segment, SegmentAsync } from '@grafana/ui'; import { SelectableValue } from '@grafana/data'; import { selectors } from '../constants'; import { Project, AlignmentPeriods, AliasBy, QueryInlineField } from '.'; import { SLOQuery } from '../types'; import CloudMonitoringDatasource from '../datasource'; export interface Props { usedAlignmentPeriod?: number; variableOptionGroup: SelectableValue<string>; onChange: (query: SLOQuery) => void; onRunQuery: () => void; query: SLOQuery; datasource: CloudMonitoringDatasource; } export const defaultQuery: (dataSource: CloudMonitoringDatasource) => SLOQuery = (dataSource) => ({ projectName: dataSource.getDefaultProject(), alignmentPeriod: 'cloud-monitoring-auto', aliasBy: '', selectorName: 'select_slo_health', serviceId: '', sloId: '', }); export function SLOQueryEditor({ query, datasource, onChange, variableOptionGroup, usedAlignmentPeriod, }: React.PropsWithChildren<Props>) { return ( <> <Project templateVariableOptions={variableOptionGroup.options} projectName={query.projectName} datasource={datasource} onChange={(projectName) => onChange({ ...query, projectName })} /> <QueryInlineField label="Service"> <SegmentAsync allowCustomValue value={query?.serviceId} placeholder="Select service" loadOptions={() => datasource.getSLOServices(query.projectName).then((services) => [ { label: 'Template Variables', options: variableOptionGroup.options, }, ...services, ]) } onChange={({ value: serviceId = '' }) => onChange({ ...query, serviceId, sloId: '' })} /> </QueryInlineField> <QueryInlineField label="SLO"> <SegmentAsync allowCustomValue value={query?.sloId} placeholder="Select SLO" loadOptions={() => datasource.getServiceLevelObjectives(query.projectName, query.serviceId).then((sloIds) => [ { label: 'Template Variables', options: variableOptionGroup.options, }, ...sloIds, ]) } onChange={async ({ value: sloId = '' }) => { const slos = await datasource.getServiceLevelObjectives(query.projectName, query.serviceId); const slo = slos.find(({ value }) => value === datasource.templateSrv.replace(sloId)); onChange({ ...query, sloId, goal: slo?.goal }); }} /> </QueryInlineField> <QueryInlineField label="Selector"> <Segment allowCustomValue value={[...selectors, ...variableOptionGroup.options].find((s) => s.value === query?.selectorName ?? '')} options={[ { label: 'Template Variables', options: variableOptionGroup.options, }, ...selectors, ]} onChange={({ value: selectorName }) => onChange({ ...query, selectorName })} /> </QueryInlineField> <AlignmentPeriods templateSrv={datasource.templateSrv} templateVariableOptions={variableOptionGroup.options} alignmentPeriod={query.alignmentPeriod || ''} perSeriesAligner={query.selectorName === 'select_slo_health' ? 'ALIGN_MEAN' : 'ALIGN_NEXT_OLDER'} usedAlignmentPeriod={usedAlignmentPeriod} onChange={(alignmentPeriod) => onChange({ ...query, alignmentPeriod })} /> <AliasBy value={query.aliasBy} onChange={(aliasBy) => onChange({ ...query, aliasBy })} /> </> ); }
public/app/plugins/datasource/cloud-monitoring/components/SLOQueryEditor.tsx
1
https://github.com/grafana/grafana/commit/ae64dcf0638e1b860dd3e56cdd97abb7c90833c0
[ 0.9991790652275085, 0.18180221319198608, 0.000164806901011616, 0.00017636148550081998, 0.38526204228401184 ]
{ "id": 8, "code_window": [ " value: name.match(/([^\\/]*)\\/*$/)![1],\n", " label: name.match(/([^\\/]*)\\/*$/)![1],\n", " }),\n", " });\n", " }\n", "\n", " async getServiceLevelObjectives(projectName: string, serviceId: string): Promise<Array<SelectableValue<string>>> {\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " label: displayName || name.match(/([^\\/]*)\\/*$/)![1],\n" ], "file_path": "public/app/plugins/datasource/cloud-monitoring/datasource.ts", "type": "replace", "edit_start_line_idx": 261 }
package main #Dashboard: { // Unique numeric identifier for the dashboard. (generated by the db) id: int // Unique dashboard identifier that can be generated by anyone. string (8-40) uid: string // Title of dashboard. title?: string // Description of dashboard. description?: string // Tags associated with dashboard. tags?: [...string] // Theme of dashboard. style: *"light" | "dark" // Timezone of dashboard, timezone?: *"browser" | "utc" // Whether a dashboard is editable or not. editable: bool | *true // 0 for no shared crosshair or tooltip (default). // 1 for shared crosshair. // 2 for shared crosshair AND shared tooltip. graphTooltip: int >= 0 <= 2 | *0 // Time range for dashboard, e.g. last 6 hours, last 7 days, etc time?: { from: string | *"now-6h" to: string | *"now" } // Timepicker metadata. timepicker?: { // Whether timepicker is collapsed or not. collapse: bool | *false // Whether timepicker is enabled or not. enable: bool | *true // Whether timepicker is visible or not. hidden: bool | *false // Selectable intervals for auto-refresh. refresh_intervals: [...string] | *["5s", "10s", "30s", "1m", "5m", "15m", "30m", "1h", "2h", "1d"] } // Templating. templating?: list: [...{}] // Annotations. annotations?: list: [...{ builtIn: int | *0 // Datasource to use for annotation. datasource: string // Whether annotation is enabled. enable?: bool | *true // Whether to hide annotation. hide?: bool | *false // Annotation icon color. iconColor?: string // Name of annotation. name?: string // Query for annotation data. rawQuery: string showIn: int | *0 }] | *[] // Auto-refresh interval. refresh: string // Version of the JSON schema, incremented each time a Grafana update brings // changes to said schema. schemaVersion: int | *25 // Version of the dashboard, incremented each time the dashboard is updated. version: string // Dashboard panels. panels?: [...{}] }
dashboard-schemas/Dashboard.cue
0
https://github.com/grafana/grafana/commit/ae64dcf0638e1b860dd3e56cdd97abb7c90833c0
[ 0.00017462257528677583, 0.00017247027426492423, 0.00017031922470778227, 0.00017276665312238038, 0.0000012918162610731088 ]
{ "id": 8, "code_window": [ " value: name.match(/([^\\/]*)\\/*$/)![1],\n", " label: name.match(/([^\\/]*)\\/*$/)![1],\n", " }),\n", " });\n", " }\n", "\n", " async getServiceLevelObjectives(projectName: string, serviceId: string): Promise<Array<SelectableValue<string>>> {\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " label: displayName || name.match(/([^\\/]*)\\/*$/)![1],\n" ], "file_path": "public/app/plugins/datasource/cloud-monitoring/datasource.ts", "type": "replace", "edit_start_line_idx": 261 }
import React from 'react'; import { boolean, select, text } from '@storybook/addon-knobs'; import { ButtonVariant, ValuePicker } from '@grafana/ui'; import { generateOptions } from '../Select/mockOptions'; import { getIconKnob } from '../../utils/storybook/knobs'; import { withCenteredStory } from '../../utils/storybook/withCenteredStory'; import { ComponentSize } from '../../types/size'; import mdx from './ValuePicker.mdx'; export default { title: 'Pickers and Editors/ValuePicker', component: ValuePicker, decorators: [withCenteredStory], parameters: { docs: { page: mdx, }, }, }; const VISUAL_GROUP = 'Visual options'; const variants = ['primary', 'secondary', 'destructive', 'link']; const sizes = ['sm', 'md', 'lg']; const options = generateOptions(); export const simple = () => { const label = text('Label', 'Pick an option', VISUAL_GROUP); const variant = select('Variant', variants, 'primary', VISUAL_GROUP); const size = select('Size', sizes, 'md', VISUAL_GROUP); const isFullWidth = boolean('Is full width', false, VISUAL_GROUP); const icon = getIconKnob(); const menuPlacement = select('Menu placement', ['auto', 'bottom', 'top'], 'auto', VISUAL_GROUP); return ( <div style={{ width: '200px' }}> <ValuePicker options={options} label={label} onChange={(v) => console.log(v)} variant={variant as ButtonVariant} icon={icon} isFullWidth={isFullWidth} size={size as ComponentSize} menuPlacement={menuPlacement} /> </div> ); };
packages/grafana-ui/src/components/ValuePicker/ValuePicker.story.tsx
0
https://github.com/grafana/grafana/commit/ae64dcf0638e1b860dd3e56cdd97abb7c90833c0
[ 0.0015242253430187702, 0.0004442934296093881, 0.00016938504995778203, 0.00017605116590857506, 0.0005399722140282393 ]
{ "id": 8, "code_window": [ " value: name.match(/([^\\/]*)\\/*$/)![1],\n", " label: name.match(/([^\\/]*)\\/*$/)![1],\n", " }),\n", " });\n", " }\n", "\n", " async getServiceLevelObjectives(projectName: string, serviceId: string): Promise<Array<SelectableValue<string>>> {\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " label: displayName || name.match(/([^\\/]*)\\/*$/)![1],\n" ], "file_path": "public/app/plugins/datasource/cloud-monitoring/datasource.ts", "type": "replace", "edit_start_line_idx": 261 }
.playlist-description { width: 555px; margin-bottom: 20px; } .playlist-search-container { z-index: 1000; position: relative; width: 700px; box-shadow: 0px 0px 55px 0px black; background-color: $panel-bg; .label-tag { margin-left: 6px; font-size: 11px; padding: 2px 6px; } } .playlist-search-switches { position: absolute; top: 8px; right: 11px; } .playlist-search-containerwrapper { margin-bottom: 15px; } .playlist-search-field-wrapper { input { width: 100%; padding: 8px 8px; height: 100%; box-sizing: border-box; } button { margin: 0 4px 0 0; } > span { display: block; overflow: hidden; } } .playlist-search-results-container { min-height: 100px; overflow: auto; display: block; line-height: 28px; .search-item:hover, .search-item.selected { background-color: $list-item-hover-bg; } .selected { .search-result-tag { opacity: 0.7; color: white; } } .fa-star, .fa-star-o { padding-left: 13px; } .fa-star { color: $orange; } .search-result-link { .fa { padding-right: 10px; } } .search-item { display: block; padding: 3px 10px; white-space: nowrap; background-color: $list-item-bg; margin-bottom: 4px; .search-result-icon:before { content: '\f009'; } &.search-item-dash-home .search-result-icon:before { content: '\f015'; } } .search-result-tags { float: right; } .search-result-actions { float: right; padding-left: 20px; } } .playlist-available-list { td { line-height: 28px; max-width: 335px; white-space: nowrap; text-overflow: ellipsis; overflow: hidden; } .add-dashboard { text-align: center; } .fa-star { color: $orange; } } .playlist-column-header { border-bottom: thin solid $gray-1; padding-bottom: 3px; margin-bottom: 15px; } .selected-playlistitem-settings { text-align: right; }
public/sass/pages/_playlist.scss
0
https://github.com/grafana/grafana/commit/ae64dcf0638e1b860dd3e56cdd97abb7c90833c0
[ 0.00017797017062548548, 0.00017488609591964632, 0.0001693353260634467, 0.00017524126451462507, 0.00000218029526877217 ]
{ "id": 9, "code_window": [ " perSeriesAligner?: string;\n", " aliasBy?: string;\n", " selectorName: string;\n", " serviceId: string;\n", " sloId: string;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " serviceName: string;\n" ], "file_path": "public/app/plugins/datasource/cloud-monitoring/types.ts", "type": "add", "edit_start_line_idx": 94 }
import React from 'react'; import { Segment, SegmentAsync } from '@grafana/ui'; import { SelectableValue } from '@grafana/data'; import { selectors } from '../constants'; import { Project, AlignmentPeriods, AliasBy, QueryInlineField } from '.'; import { SLOQuery } from '../types'; import CloudMonitoringDatasource from '../datasource'; export interface Props { usedAlignmentPeriod?: number; variableOptionGroup: SelectableValue<string>; onChange: (query: SLOQuery) => void; onRunQuery: () => void; query: SLOQuery; datasource: CloudMonitoringDatasource; } export const defaultQuery: (dataSource: CloudMonitoringDatasource) => SLOQuery = (dataSource) => ({ projectName: dataSource.getDefaultProject(), alignmentPeriod: 'cloud-monitoring-auto', aliasBy: '', selectorName: 'select_slo_health', serviceId: '', sloId: '', }); export function SLOQueryEditor({ query, datasource, onChange, variableOptionGroup, usedAlignmentPeriod, }: React.PropsWithChildren<Props>) { return ( <> <Project templateVariableOptions={variableOptionGroup.options} projectName={query.projectName} datasource={datasource} onChange={(projectName) => onChange({ ...query, projectName })} /> <QueryInlineField label="Service"> <SegmentAsync allowCustomValue value={query?.serviceId} placeholder="Select service" loadOptions={() => datasource.getSLOServices(query.projectName).then((services) => [ { label: 'Template Variables', options: variableOptionGroup.options, }, ...services, ]) } onChange={({ value: serviceId = '' }) => onChange({ ...query, serviceId, sloId: '' })} /> </QueryInlineField> <QueryInlineField label="SLO"> <SegmentAsync allowCustomValue value={query?.sloId} placeholder="Select SLO" loadOptions={() => datasource.getServiceLevelObjectives(query.projectName, query.serviceId).then((sloIds) => [ { label: 'Template Variables', options: variableOptionGroup.options, }, ...sloIds, ]) } onChange={async ({ value: sloId = '' }) => { const slos = await datasource.getServiceLevelObjectives(query.projectName, query.serviceId); const slo = slos.find(({ value }) => value === datasource.templateSrv.replace(sloId)); onChange({ ...query, sloId, goal: slo?.goal }); }} /> </QueryInlineField> <QueryInlineField label="Selector"> <Segment allowCustomValue value={[...selectors, ...variableOptionGroup.options].find((s) => s.value === query?.selectorName ?? '')} options={[ { label: 'Template Variables', options: variableOptionGroup.options, }, ...selectors, ]} onChange={({ value: selectorName }) => onChange({ ...query, selectorName })} /> </QueryInlineField> <AlignmentPeriods templateSrv={datasource.templateSrv} templateVariableOptions={variableOptionGroup.options} alignmentPeriod={query.alignmentPeriod || ''} perSeriesAligner={query.selectorName === 'select_slo_health' ? 'ALIGN_MEAN' : 'ALIGN_NEXT_OLDER'} usedAlignmentPeriod={usedAlignmentPeriod} onChange={(alignmentPeriod) => onChange({ ...query, alignmentPeriod })} /> <AliasBy value={query.aliasBy} onChange={(aliasBy) => onChange({ ...query, aliasBy })} /> </> ); }
public/app/plugins/datasource/cloud-monitoring/components/SLOQueryEditor.tsx
1
https://github.com/grafana/grafana/commit/ae64dcf0638e1b860dd3e56cdd97abb7c90833c0
[ 0.9985570311546326, 0.40811777114868164, 0.000171600331668742, 0.019741766154766083, 0.4541836977005005 ]
{ "id": 9, "code_window": [ " perSeriesAligner?: string;\n", " aliasBy?: string;\n", " selectorName: string;\n", " serviceId: string;\n", " sloId: string;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " serviceName: string;\n" ], "file_path": "public/app/plugins/datasource/cloud-monitoring/types.ts", "type": "add", "edit_start_line_idx": 94 }
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Render should render component 1`] = ` <Page navModel={Object {}} > <PageContents isLoading={false} > <DashboardsTable dashboards={Array []} onImport={[Function]} onRemove={[Function]} /> </PageContents> </Page> `;
public/app/features/datasources/__snapshots__/DataSourceDashboards.test.tsx.snap
0
https://github.com/grafana/grafana/commit/ae64dcf0638e1b860dd3e56cdd97abb7c90833c0
[ 0.00017652887618169188, 0.00017617637058719993, 0.00017582386499270797, 0.00017617637058719993, 3.525055944919586e-7 ]
{ "id": 9, "code_window": [ " perSeriesAligner?: string;\n", " aliasBy?: string;\n", " selectorName: string;\n", " serviceId: string;\n", " sloId: string;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " serviceName: string;\n" ], "file_path": "public/app/plugins/datasource/cloud-monitoring/types.ts", "type": "add", "edit_start_line_idx": 94 }
import React, { PureComponent } from 'react'; import { Button, ClipboardButton, Icon, Spinner, Select, Input, LinkButton, Field } from '@grafana/ui'; import { AppEvents, SelectableValue } from '@grafana/data'; import { getBackendSrv } from '@grafana/runtime'; import { DashboardModel, PanelModel } from 'app/features/dashboard/state'; import { getTimeSrv } from 'app/features/dashboard/services/TimeSrv'; import { appEvents } from 'app/core/core'; import { VariableRefresh } from '../../../variables/types'; const snapshotApiUrl = '/api/snapshots'; const expireOptions: Array<SelectableValue<number>> = [ { label: 'Never', value: 0 }, { label: '1 Hour', value: 60 * 60 }, { label: '1 Day', value: 60 * 60 * 24 }, { label: '7 Days', value: 60 * 60 * 24 * 7 }, ]; interface Props { dashboard: DashboardModel; panel?: PanelModel; onDismiss(): void; } interface State { isLoading: boolean; step: number; snapshotName: string; selectedExpireOption: SelectableValue<number>; snapshotExpires?: number; snapshotUrl: string; deleteUrl: string; timeoutSeconds: number; externalEnabled: boolean; sharingButtonText: string; } export class ShareSnapshot extends PureComponent<Props, State> { private dashboard: DashboardModel; constructor(props: Props) { super(props); this.dashboard = props.dashboard; this.state = { isLoading: false, step: 1, selectedExpireOption: expireOptions[0], snapshotExpires: expireOptions[0].value, snapshotName: props.dashboard.title, timeoutSeconds: 4, snapshotUrl: '', deleteUrl: '', externalEnabled: false, sharingButtonText: '', }; } componentDidMount() { this.getSnaphotShareOptions(); } async getSnaphotShareOptions() { const shareOptions = await getBackendSrv().get('/api/snapshot/shared-options'); this.setState({ sharingButtonText: shareOptions['externalSnapshotName'], externalEnabled: shareOptions['externalEnabled'], }); } createSnapshot = (external?: boolean) => () => { const { timeoutSeconds } = this.state; this.dashboard.snapshot = { timestamp: new Date(), }; if (!external) { this.dashboard.snapshot.originalUrl = window.location.href; } this.setState({ isLoading: true }); this.dashboard.startRefresh(); setTimeout(() => { this.saveSnapshot(this.dashboard, external); }, timeoutSeconds * 1000); }; saveSnapshot = async (dashboard: DashboardModel, external?: boolean) => { const { snapshotExpires } = this.state; const dash = this.dashboard.getSaveModelClone(); this.scrubDashboard(dash); const cmdData = { dashboard: dash, name: dash.title, expires: snapshotExpires, external: external, }; try { const results: { deleteUrl: any; url: any } = await getBackendSrv().post(snapshotApiUrl, cmdData); this.setState({ deleteUrl: results.deleteUrl, snapshotUrl: results.url, step: 2, }); } finally { this.setState({ isLoading: false }); } }; scrubDashboard = (dash: DashboardModel) => { const { panel } = this.props; const { snapshotName } = this.state; // change title dash.title = snapshotName; // make relative times absolute dash.time = getTimeSrv().timeRange(); // remove panel queries & links dash.panels.forEach((panel) => { panel.targets = []; panel.links = []; panel.datasource = null; }); // remove annotation queries const annotations = dash.annotations.list.filter((annotation) => annotation.enable); dash.annotations.list = annotations.map((annotation: any) => { return { name: annotation.name, enable: annotation.enable, iconColor: annotation.iconColor, snapshotData: annotation.snapshotData, type: annotation.type, builtIn: annotation.builtIn, hide: annotation.hide, }; }); // remove template queries dash.getVariables().forEach((variable: any) => { variable.query = ''; variable.options = variable.current ? [variable.current] : []; variable.refresh = VariableRefresh.never; }); // snapshot single panel if (panel) { const singlePanel = panel.getSaveModel(); singlePanel.gridPos.w = 24; singlePanel.gridPos.x = 0; singlePanel.gridPos.y = 0; singlePanel.gridPos.h = 20; dash.panels = [singlePanel]; } // cleanup snapshotData delete this.dashboard.snapshot; this.dashboard.forEachPanel((panel: PanelModel) => { delete panel.snapshotData; }); this.dashboard.annotations.list.forEach((annotation) => { delete annotation.snapshotData; }); }; deleteSnapshot = async () => { const { deleteUrl } = this.state; await getBackendSrv().get(deleteUrl); this.setState({ step: 3 }); }; getSnapshotUrl = () => { return this.state.snapshotUrl; }; onSnapshotNameChange = (event: React.ChangeEvent<HTMLInputElement>) => { this.setState({ snapshotName: event.target.value }); }; onTimeoutChange = (event: React.ChangeEvent<HTMLInputElement>) => { this.setState({ timeoutSeconds: Number(event.target.value) }); }; onExpireChange = (option: SelectableValue<number>) => { this.setState({ selectedExpireOption: option, snapshotExpires: option.value, }); }; onSnapshotUrlCopy = () => { appEvents.emit(AppEvents.alertSuccess, ['Content copied to clipboard']); }; renderStep1() { const { onDismiss } = this.props; const { snapshotName, selectedExpireOption, timeoutSeconds, isLoading, sharingButtonText, externalEnabled, } = this.state; return ( <> <div> <p className="share-modal-info-text"> A snapshot is an instant way to share an interactive dashboard publicly. When created, we{' '} <strong>strip sensitive data</strong> like queries (metric, template and annotation) and panel links, leaving only the visible metric data and series names embedded into your dashboard. </p> <p className="share-modal-info-text"> Keep in mind, your <strong>snapshot can be viewed by anyone</strong> that has the link and can reach the URL. Share wisely. </p> </div> <Field label="Snapshot name"> <Input width={30} value={snapshotName} onChange={this.onSnapshotNameChange} /> </Field> <Field label="Expire"> <Select width={30} options={expireOptions} value={selectedExpireOption} onChange={this.onExpireChange} /> </Field> <Field label="Timeout (seconds)" description="You may need to configure the timeout value if it takes a long time to collect your dashboard's metrics." > <Input type="number" width={21} value={timeoutSeconds} onChange={this.onTimeoutChange} /> </Field> <div className="gf-form-button-row"> <Button variant="primary" disabled={isLoading} onClick={this.createSnapshot()}> Local Snapshot </Button> {externalEnabled && ( <Button variant="secondary" disabled={isLoading} onClick={this.createSnapshot(true)}> {sharingButtonText} </Button> )} <Button variant="secondary" onClick={onDismiss}> Cancel </Button> </div> </> ); } renderStep2() { const { snapshotUrl } = this.state; return ( <> <div className="gf-form" style={{ marginTop: '40px' }}> <div className="gf-form-row"> <a href={snapshotUrl} className="large share-modal-link" target="_blank" rel="noreferrer"> <Icon name="external-link-alt" /> {snapshotUrl} </a> <br /> <ClipboardButton variant="secondary" getText={this.getSnapshotUrl} onClipboardCopy={this.onSnapshotUrlCopy}> Copy Link </ClipboardButton> </div> </div> <div className="pull-right" style={{ padding: '5px' }}> Did you make a mistake?{' '} <LinkButton variant="link" target="_blank" onClick={this.deleteSnapshot}> delete snapshot. </LinkButton> </div> </> ); } renderStep3() { return ( <div className="share-modal-header"> <p className="share-modal-info-text"> The snapshot has now been deleted. If you have already accessed it once, it might take up to an hour before it is removed from browser caches or CDN caches. </p> </div> ); } render() { const { isLoading, step } = this.state; return ( <div className="share-modal-body"> <div className="share-modal-header"> <div className="share-modal-content"> {step === 1 && this.renderStep1()} {step === 2 && this.renderStep2()} {step === 3 && this.renderStep3()} {isLoading && <Spinner inline={true} />} </div> </div> </div> ); } }
public/app/features/dashboard/components/ShareModal/ShareSnapshot.tsx
0
https://github.com/grafana/grafana/commit/ae64dcf0638e1b860dd3e56cdd97abb7c90833c0
[ 0.0001765300694387406, 0.00017240348097402602, 0.00016505080566275865, 0.00017279251187574118, 0.000002799029061861802 ]
{ "id": 9, "code_window": [ " perSeriesAligner?: string;\n", " aliasBy?: string;\n", " selectorName: string;\n", " serviceId: string;\n", " sloId: string;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " serviceName: string;\n" ], "file_path": "public/app/plugins/datasource/cloud-monitoring/types.ts", "type": "add", "edit_start_line_idx": 94 }
import { getPluginJson, validatePluginJson } from './pluginValidation'; describe('pluginValidation', () => { describe('plugin.json', () => { test('missing plugin.json file', () => { expect(() => getPluginJson(`${__dirname}/mocks/missing-plugin.json`)).toThrowError(); }); }); describe('validatePluginJson', () => { test('missing plugin.json file', () => { expect(() => validatePluginJson({})).toThrow('Plugin id is missing in plugin.json'); }); }); });
packages/grafana-toolkit/src/config/utils/pluginValidation.test.ts
0
https://github.com/grafana/grafana/commit/ae64dcf0638e1b860dd3e56cdd97abb7c90833c0
[ 0.00017728304374031723, 0.00017581661813892424, 0.00017435020708944649, 0.00017581661813892424, 0.0000014664183254353702 ]
{ "id": 10, "code_window": [ " sloId: string;\n", " goal?: number;\n", "}\n", "\n" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ " sloName: string;\n" ], "file_path": "public/app/plugins/datasource/cloud-monitoring/types.ts", "type": "add", "edit_start_line_idx": 95 }
import { DataQuery, DataSourceJsonData } from '@grafana/data'; export enum AuthType { JWT = 'jwt', GCE = 'gce', } export const authTypes = [ { value: 'Google JWT File', key: AuthType.JWT }, { value: 'GCE Default Service Account', key: AuthType.GCE }, ]; export enum MetricFindQueryTypes { Projects = 'projects', Services = 'services', DefaultProject = 'defaultProject', MetricTypes = 'metricTypes', LabelKeys = 'labelKeys', LabelValues = 'labelValues', ResourceTypes = 'resourceTypes', Aggregations = 'aggregations', Aligners = 'aligners', AlignmentPeriods = 'alignmentPeriods', Selectors = 'selectors', SLOServices = 'sloServices', SLO = 'slo', } export interface CloudMonitoringVariableQuery extends DataQuery { selectedQueryType: string; selectedService: string; selectedMetricType: string; selectedSLOService: string; labelKey: string; projects: Array<{ value: string; name: string }>; sloServices: Array<{ value: string; name: string }>; projectName: string; } export interface VariableQueryData { selectedQueryType: string; metricDescriptors: MetricDescriptor[]; selectedService: string; selectedMetricType: string; selectedSLOService: string; labels: string[]; labelKey: string; metricTypes: Array<{ value: string; name: string }>; services: Array<{ value: string; name: string }>; projects: Array<{ value: string; name: string }>; sloServices: Array<{ value: string; name: string }>; projectName: string; loading: boolean; } export enum QueryType { METRICS = 'metrics', SLO = 'slo', } export enum EditorMode { Visual = 'visual', MQL = 'mql', } export const queryTypes = [ { label: 'Metrics', value: QueryType.METRICS }, { label: 'Service Level Objectives (SLO)', value: QueryType.SLO }, ]; export interface MetricQuery { editorMode: EditorMode; projectName: string; unit?: string; metricType: string; crossSeriesReducer: string; alignmentPeriod?: string; perSeriesAligner?: string; groupBys?: string[]; filters?: string[]; aliasBy?: string; metricKind?: string; valueType?: string; view?: string; query: string; } export interface SLOQuery { projectName: string; alignmentPeriod?: string; perSeriesAligner?: string; aliasBy?: string; selectorName: string; serviceId: string; sloId: string; goal?: number; } export interface CloudMonitoringQuery extends DataQuery { datasourceId?: number; // Should not be necessary anymore queryType: QueryType; metricQuery: MetricQuery; sloQuery?: SLOQuery; intervalMs: number; type: string; } export interface CloudMonitoringOptions extends DataSourceJsonData { defaultProject?: string; gceDefaultProject?: string; authenticationType?: string; } export interface AnnotationTarget { projectName: string; metricType: string; refId: string; filters: string[]; metricKind: string; valueType: string; title: string; text: string; } export interface QueryMeta { alignmentPeriod: string; rawQuery: string; rawQueryString: string; metricLabels: { [key: string]: string[] }; resourceLabels: { [key: string]: string[] }; resourceTypes: string[]; } export interface MetricDescriptor { valueType: string; metricKind: string; type: string; unit: string; service: string; serviceShortName: string; displayName: string; description: string; } export interface Segment { type: string; value: string; } export interface Filter { key: string; operator: string; value: string; condition?: string; }
public/app/plugins/datasource/cloud-monitoring/types.ts
1
https://github.com/grafana/grafana/commit/ae64dcf0638e1b860dd3e56cdd97abb7c90833c0
[ 0.9980875849723816, 0.06436456739902496, 0.00016731690266169608, 0.0001849404798122123, 0.2411123663187027 ]
{ "id": 10, "code_window": [ " sloId: string;\n", " goal?: number;\n", "}\n", "\n" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ " sloName: string;\n" ], "file_path": "public/app/plugins/datasource/cloud-monitoring/types.ts", "type": "add", "edit_start_line_idx": 95 }
import React, { AnchorHTMLAttributes, ButtonHTMLAttributes } from 'react'; import { css, cx } from 'emotion'; import tinycolor from 'tinycolor2'; import { useTheme } from '../../themes'; import { IconName } from '../../types/icon'; import { getPropertiesForButtonSize } from '../Forms/commonStyles'; import { GrafanaTheme } from '@grafana/data'; import { ComponentSize } from '../../types/size'; import { focusCss } from '../../themes/mixins'; import { Icon } from '../Icon/Icon'; export type ButtonVariant = 'primary' | 'secondary' | 'destructive' | 'link'; type CommonProps = { size?: ComponentSize; variant?: ButtonVariant; icon?: IconName; className?: string; children?: React.ReactNode; fullWidth?: boolean; }; export type ButtonProps = CommonProps & ButtonHTMLAttributes<HTMLButtonElement>; export const Button = React.forwardRef<HTMLButtonElement, ButtonProps>( ({ variant = 'primary', size = 'md', icon, fullWidth, children, className, ...otherProps }, ref) => { const theme = useTheme(); const styles = getButtonStyles({ theme, size, variant, icon, fullWidth, children, }); return ( <button className={cx(styles.button, className)} {...otherProps} ref={ref}> {icon && <Icon name={icon} size={size} className={styles.icon} />} {children && <span className={styles.content}>{children}</span>} </button> ); } ); Button.displayName = 'Button'; type ButtonLinkProps = CommonProps & ButtonHTMLAttributes<HTMLButtonElement> & AnchorHTMLAttributes<HTMLAnchorElement>; export const LinkButton = React.forwardRef<HTMLAnchorElement, ButtonLinkProps>( ({ variant = 'primary', size = 'md', icon, fullWidth, children, className, disabled, ...otherProps }, ref) => { const theme = useTheme(); const styles = getButtonStyles({ theme, fullWidth, size, variant, icon, children, }); const linkButtonStyles = disabled && cx( disabledStyles, css` pointer-events: none; ` ); return ( <a className={cx(styles.button, linkButtonStyles, className)} {...otherProps} ref={ref} tabIndex={disabled ? -1 : 0} > {icon && <Icon name={icon} size={size} className={styles.icon} />} {children && <span className={styles.content}>{children}</span>} </a> ); } ); LinkButton.displayName = 'LinkButton'; export interface StyleProps { size: ComponentSize; variant: ButtonVariant; children?: React.ReactNode; icon?: IconName; theme: GrafanaTheme; fullWidth?: boolean; narrow?: boolean; } const disabledStyles = css` cursor: not-allowed; opacity: 0.65; box-shadow: none; `; export const getButtonStyles = (props: StyleProps) => { const { theme, variant, size, children, fullWidth } = props; const { padding, fontSize, height } = getPropertiesForButtonSize(size, theme); const { borderColor, variantStyles } = getPropertiesForVariant(theme, variant); const iconOnly = !children; return { button: css` label: button; display: inline-flex; align-items: center; font-weight: ${theme.typography.weight.semibold}; font-family: ${theme.typography.fontFamily.sansSerif}; font-size: ${fontSize}; padding: 0 ${padding}px; height: ${height}px; // Deduct border from line-height for perfect vertical centering on windows and linux line-height: ${height - 2}px; vertical-align: middle; cursor: pointer; border: 1px solid ${borderColor}; border-radius: ${theme.border.radius.sm}; ${fullWidth && ` flex-grow: 1; justify-content: center; `} ${variantStyles} &[disabled], &:disabled { ${disabledStyles}; } `, img: css` width: 16px; height: 16px; margin-right: ${theme.spacing.sm}; margin-left: -${theme.spacing.xs}; `, icon: css` margin-left: -${padding / 2}px; margin-right: ${(iconOnly ? -padding : padding) / 2}px; `, content: css` display: flex; flex-direction: row; align-items: center; white-space: nowrap; height: 100%; `, }; }; function getButtonVariantStyles(from: string, to: string, textColor: string, theme: GrafanaTheme) { return css` background: linear-gradient(180deg, ${from} 0%, ${to} 100%); color: ${textColor}; &:hover { background: ${from}; color: ${textColor}; } &:focus { background: ${from}; outline: none; ${focusCss(theme)}; } `; } export function getPropertiesForVariant(theme: GrafanaTheme, variant: ButtonVariant) { switch (variant) { case 'secondary': const from = theme.isLight ? theme.palette.gray7 : theme.palette.gray15; const to = theme.isLight ? tinycolor(from).darken(5).toString() : tinycolor(from).lighten(4).toString(); return { borderColor: theme.isLight ? theme.palette.gray85 : theme.palette.gray25, variantStyles: getButtonVariantStyles( from, to, theme.isLight ? theme.palette.gray25 : theme.palette.gray4, theme ), }; case 'destructive': return { borderColor: theme.palette.redShade, variantStyles: getButtonVariantStyles( theme.palette.redBase, theme.palette.redShade, theme.palette.white, theme ), }; case 'link': return { borderColor: 'transparent', variantStyles: css` background: transparent; color: ${theme.colors.linkExternal}; &:focus { outline: none; text-decoration: underline; } `, }; case 'primary': default: return { borderColor: theme.colors.bgBlue1, variantStyles: getButtonVariantStyles(theme.colors.bgBlue1, theme.colors.bgBlue2, theme.palette.white, theme), }; } }
packages/grafana-ui/src/components/Button/Button.tsx
0
https://github.com/grafana/grafana/commit/ae64dcf0638e1b860dd3e56cdd97abb7c90833c0
[ 0.00018449548224452883, 0.00017250495147891343, 0.0001675413514021784, 0.0001715563121251762, 0.0000038012310596968746 ]
{ "id": 10, "code_window": [ " sloId: string;\n", " goal?: number;\n", "}\n", "\n" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ " sloName: string;\n" ], "file_path": "public/app/plugins/datasource/cloud-monitoring/types.ts", "type": "add", "edit_start_line_idx": 95 }
public/app/features/profile/all.ts
0
https://github.com/grafana/grafana/commit/ae64dcf0638e1b860dd3e56cdd97abb7c90833c0
[ 0.00018401743727736175, 0.00018401743727736175, 0.00018401743727736175, 0.00018401743727736175, 0 ]
{ "id": 10, "code_window": [ " sloId: string;\n", " goal?: number;\n", "}\n", "\n" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ " sloName: string;\n" ], "file_path": "public/app/plugins/datasource/cloud-monitoring/types.ts", "type": "add", "edit_start_line_idx": 95 }
.pluginlist-section-header { margin-bottom: $spacer; color: $text-color-weak; } .pluginlist-section { margin-bottom: $spacer; } .pluginlist-link { @include list-item(); } .pluginlist-icon { vertical-align: sub; font-size: $font-size-h1; margin-right: $spacer / 2; } .pluginlist-image { width: 17px; } .pluginlist-title { margin-right: $spacer / 3; } .pluginlist-version { font-size: $font-size-sm; color: $text-color-weak; } .pluginlist-message { float: right; font-size: $font-size-sm; } .pluginlist-message--update { &:hover { border-bottom: 1px solid $text-color; } } .pluginlist-message--enable { color: $external-link-color; &:hover { border-bottom: 1px solid $external-link-color; } } .pluginlist-message--no-update { color: $text-color-weak; } .pluginlist-emphasis { font-weight: $font-weight-semi-bold; } .pluginlist-none-installed { color: $text-color-weak; font-size: $font-size-sm; } .pluginlist-inline-logo { vertical-align: sub; margin-right: $spacer / 3; width: 16px; }
public/sass/components/_panel_pluginlist.scss
0
https://github.com/grafana/grafana/commit/ae64dcf0638e1b860dd3e56cdd97abb7c90833c0
[ 0.0001762298634275794, 0.00017287149967160076, 0.000168361613759771, 0.0001731484371703118, 0.000002592031933090766 ]
{ "id": 0, "code_window": [ "// Group 6 = identifier inside parenthesis\n", "// Group 7 = \"#\"\n", "// Group 8 = identifier after \"#\"\n", "var BIND_NAME_REGEXP = RegExpWrapper.create(\n", " '^(?:(?:(bind)|(var)|(on))-(.+))|\\\\[([^\\\\]]+)\\\\]|\\\\(([^\\\\)]+)\\\\)|(#)(.+)');\n", "\n", "/**\n", " * Parses the property bindings on a single element.\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " '^(?:(?:(?:(bind)|(var)|(on))-(.+))|\\\\[([^\\\\]]+)\\\\]|\\\\(([^\\\\)]+)\\\\)|(#)(.+))$');\n" ], "file_path": "modules/angular2/src/core/compiler/pipeline/property_binding_parser.js", "type": "replace", "edit_start_line_idx": 19 }
import {describe, beforeEach, it, expect, iit, ddescribe, el} from 'angular2/test_lib'; import {PropertyBindingParser} from 'angular2/src/core/compiler/pipeline/property_binding_parser'; import {CompilePipeline} from 'angular2/src/core/compiler/pipeline/compile_pipeline'; import {MapWrapper} from 'angular2/src/facade/collection'; import {CompileElement} from 'angular2/src/core/compiler/pipeline/compile_element'; import {CompileStep} from 'angular2/src/core/compiler/pipeline/compile_step' import {CompileControl} from 'angular2/src/core/compiler/pipeline/compile_control'; import {Lexer, Parser} from 'angular2/change_detection'; export function main() { describe('PropertyBindingParser', () => { function createPipeline(ignoreBindings = false) { return new CompilePipeline([ new MockStep((parent, current, control) => { current.ignoreBindings = ignoreBindings; }), new PropertyBindingParser(new Parser(new Lexer()))]); } it('should not parse bindings when ignoreBindings is true', () => { var results = createPipeline(true).process(el('<div [a]="b"></div>')); expect(results[0].propertyBindings).toBe(null); }); it('should detect [] syntax', () => { var results = createPipeline().process(el('<div [a]="b"></div>')); expect(MapWrapper.get(results[0].propertyBindings, 'a').source).toEqual('b'); }); it('should detect bind- syntax', () => { var results = createPipeline().process(el('<div bind-a="b"></div>')); expect(MapWrapper.get(results[0].propertyBindings, 'a').source).toEqual('b'); }); it('should detect interpolation syntax', () => { // Note: we don't test all corner cases of interpolation as we assume shared functionality between text interpolation // and attribute interpolation. var results = createPipeline().process(el('<div a="{{b}}"></div>')); expect(MapWrapper.get(results[0].propertyBindings, 'a').source).toEqual('{{b}}'); }); it('should detect var- syntax', () => { var results = createPipeline().process(el('<template var-a="b"></template>')); expect(MapWrapper.get(results[0].variableBindings, 'b')).toEqual('a'); }); it('should store variable binding for a non-template element', () => { var results = createPipeline().process(el('<p var-george="washington"></p>')); expect(MapWrapper.get(results[0].variableBindings, 'washington')).toEqual('george'); }); it('should store variable binding for a non-template element using shorthand syntax', () => { var results = createPipeline().process(el('<p #george="washington"></p>')); expect(MapWrapper.get(results[0].variableBindings, 'washington')).toEqual('george'); }); it('should store a variable binding with an implicit value', () => { var results = createPipeline().process(el('<p var-george></p>')); expect(MapWrapper.get(results[0].variableBindings, '\$implicit')).toEqual('george'); }); it('should store a variable binding with an implicit value using shorthand syntax', () => { var results = createPipeline().process(el('<p #george></p>')); expect(MapWrapper.get(results[0].variableBindings, '\$implicit')).toEqual('george'); }); it('should detect () syntax', () => { var results = createPipeline().process(el('<div (click)="b()"></div>')); expect(MapWrapper.get(results[0].eventBindings, 'click').source).toEqual('b()'); // "(click[])" is not an expected syntax and is only used to validate the regexp results = createPipeline().process(el('<div (click[])="b()"></div>')); expect(MapWrapper.get(results[0].eventBindings, 'click[]').source).toEqual('b()'); }); it('should parse event handlers using () syntax as actions', () => { var results = createPipeline().process(el('<div (click)="foo=bar"></div>')); expect(MapWrapper.get(results[0].eventBindings, 'click').source).toEqual('foo=bar'); }); it('should detect on- syntax', () => { var results = createPipeline().process(el('<div on-click="b()"></div>')); expect(MapWrapper.get(results[0].eventBindings, 'click').source).toEqual('b()'); }); it('should parse event handlers using on- syntax as actions', () => { var results = createPipeline().process(el('<div on-click="foo=bar"></div>')); expect(MapWrapper.get(results[0].eventBindings, 'click').source).toEqual('foo=bar'); }); }); } class MockStep extends CompileStep { processClosure:Function; constructor(process) { super(); this.processClosure = process; } process(parent:CompileElement, current:CompileElement, control:CompileControl) { this.processClosure(parent, current, control); } }
modules/angular2/test/core/compiler/pipeline/property_binding_parser_spec.js
1
https://github.com/angular/angular/commit/e0710c4613ba51f008bc8a2f4874fb1fade9d09f
[ 0.00016887529636733234, 0.0001669766497798264, 0.00016543746460229158, 0.0001663911243667826, 0.0000014163882724460564 ]
{ "id": 0, "code_window": [ "// Group 6 = identifier inside parenthesis\n", "// Group 7 = \"#\"\n", "// Group 8 = identifier after \"#\"\n", "var BIND_NAME_REGEXP = RegExpWrapper.create(\n", " '^(?:(?:(bind)|(var)|(on))-(.+))|\\\\[([^\\\\]]+)\\\\]|\\\\(([^\\\\)]+)\\\\)|(#)(.+)');\n", "\n", "/**\n", " * Parses the property bindings on a single element.\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " '^(?:(?:(?:(bind)|(var)|(on))-(.+))|\\\\[([^\\\\]]+)\\\\]|\\\\(([^\\\\)]+)\\\\)|(#)(.+))$');\n" ], "file_path": "modules/angular2/src/core/compiler/pipeline/property_binding_parser.js", "type": "replace", "edit_start_line_idx": 19 }
import {DOM} from 'angular2/src/dom/dom_adapter'; import {Promise} from 'angular2/src/facade/async'; import {ListWrapper, MapWrapper, Map, StringMapWrapper, List} from 'angular2/src/facade/collection'; import {AST, Locals, ChangeDispatcher, ProtoChangeDetector, ChangeDetector, ChangeRecord, BindingRecord, uninitialized} from 'angular2/change_detection'; import {ProtoElementInjector, ElementInjector, PreBuiltObjects} from './element_injector'; import {BindingPropagationConfig} from './binding_propagation_config'; import {ElementBinder} from './element_binder'; import {DirectiveMetadata} from './directive_metadata'; import {SetterFn} from 'angular2/src/reflection/types'; import {IMPLEMENTS, int, isPresent, isBlank, BaseException} from 'angular2/src/facade/lang'; import {Injector} from 'angular2/di'; import {NgElement} from 'angular2/src/core/dom/element'; import {ViewContainer} from './view_container'; import {LightDom} from './shadow_dom_emulation/light_dom'; import {Content} from './shadow_dom_emulation/content_tag'; import {ShadowDomStrategy} from './shadow_dom_strategy'; import {ViewPool} from './view_pool'; import {EventManager} from 'angular2/src/core/events/event_manager'; const NG_BINDING_CLASS = 'ng-binding'; const NG_BINDING_CLASS_SELECTOR = '.ng-binding'; // TODO(rado): make this configurable/smarter. var VIEW_POOL_CAPACITY = 10000; var VIEW_POOL_PREFILL = 0; /** * Const of making objects: http://jsperf.com/instantiate-size-of-object * @publicModule angular2/angular2 */ @IMPLEMENTS(ChangeDispatcher) export class View { /// This list matches the _nodes list. It is sparse, since only Elements have ElementInjector rootElementInjectors:List<ElementInjector>; elementInjectors:List<ElementInjector>; bindElements:List; textNodes:List; changeDetector:ChangeDetector; /// When the view is part of render tree, the DocumentFragment is empty, which is why we need /// to keep track of the nodes. nodes:List; componentChildViews: List<View>; viewContainers: List<ViewContainer>; contentTags: List<Content>; preBuiltObjects: List<PreBuiltObjects>; lightDoms: List<LightDom>; proto: ProtoView; context: any; locals:Locals; constructor(proto:ProtoView, nodes:List, protoLocals:Map) { this.proto = proto; this.nodes = nodes; this.changeDetector = null; this.elementInjectors = null; this.rootElementInjectors = null; this.textNodes = null; this.bindElements = null; this.componentChildViews = null; this.viewContainers = null; this.contentTags = null; this.preBuiltObjects = null; this.lightDoms = null; this.context = null; this.locals = new Locals(null, MapWrapper.clone(protoLocals)); //TODO optimize this } init(changeDetector:ChangeDetector, elementInjectors:List, rootElementInjectors:List, textNodes: List, bindElements:List, viewContainers:List, contentTags:List, preBuiltObjects:List, componentChildViews:List, lightDoms:List<LightDom>) { this.changeDetector = changeDetector; this.elementInjectors = elementInjectors; this.rootElementInjectors = rootElementInjectors; this.textNodes = textNodes; this.bindElements = bindElements; this.viewContainers = viewContainers; this.contentTags = contentTags; this.preBuiltObjects = preBuiltObjects; this.componentChildViews = componentChildViews; this.lightDoms = lightDoms; } setLocal(contextName: string, value) { if (!this.hydrated()) throw new BaseException('Cannot set locals on dehydrated view.'); if (!MapWrapper.contains(this.proto.variableBindings, contextName)) { return; } var templateName = MapWrapper.get(this.proto.variableBindings, contextName); this.locals.set(templateName, value); } hydrated() { return isPresent(this.context); } _hydrateContext(newContext, locals) { this.context = newContext; this.locals.parent = locals; this.changeDetector.hydrate(this.context, this.locals); } _dehydrateContext() { if (isPresent(this.locals)) { this.locals.clearValues(); } this.context = null; this.changeDetector.dehydrate(); } /** * A dehydrated view is a state of the view that allows it to be moved around * the view tree, without incurring the cost of recreating the underlying * injectors and watch records. * * A dehydrated view has the following properties: * * - all element injectors are empty. * - all appInjectors are released. * - all viewcontainers are empty. * - all context locals are set to null. * - the view context is null. * * A call to hydrate/dehydrate does not attach/detach the view from the view * tree. */ hydrate(appInjector: Injector, hostElementInjector: ElementInjector, hostLightDom: LightDom, context: Object, locals:Locals) { if (this.hydrated()) throw new BaseException('The view is already hydrated.'); this._hydrateContext(context, locals); // viewContainers for (var i = 0; i < this.viewContainers.length; i++) { var vc = this.viewContainers[i]; if (isPresent(vc)) { vc.hydrate(appInjector, hostElementInjector, hostLightDom); } } var binders = this.proto.elementBinders; var componentChildViewIndex = 0; for (var i = 0; i < binders.length; ++i) { var componentDirective = binders[i].componentDirective; var shadowDomAppInjector = null; // shadowDomAppInjector if (isPresent(componentDirective)) { var services = componentDirective.annotation.services; if (isPresent(services)) shadowDomAppInjector = appInjector.createChild(services); else { shadowDomAppInjector = appInjector; } } else { shadowDomAppInjector = null; } // elementInjectors var elementInjector = this.elementInjectors[i]; if (isPresent(elementInjector)) { elementInjector.instantiateDirectives(appInjector, shadowDomAppInjector, this.preBuiltObjects[i]); // The exporting of $implicit is a special case. Since multiple elements will all export // the different values as $implicit, directly assign $implicit bindings to the variable // name. var exportImplicitName = elementInjector.getExportImplicitName(); if (elementInjector.isExportingComponent()) { this.locals.set(exportImplicitName, elementInjector.getComponent()); } else if (elementInjector.isExportingElement()) { this.locals.set(exportImplicitName, elementInjector.getNgElement().domElement); } } if (isPresent(binders[i].nestedProtoView) && isPresent(componentDirective)) { this.componentChildViews[componentChildViewIndex++].hydrate(shadowDomAppInjector, elementInjector, this.lightDoms[i], elementInjector.getComponent(), null); } } for (var i = 0; i < this.lightDoms.length; ++i) { var lightDom = this.lightDoms[i]; if (isPresent(lightDom)) { lightDom.redistribute(); } } } dehydrate() { // Note: preserve the opposite order of the hydration process. // componentChildViews for (var i = 0; i < this.componentChildViews.length; i++) { this.componentChildViews[i].dehydrate(); } // elementInjectors for (var i = 0; i < this.elementInjectors.length; i++) { if (isPresent(this.elementInjectors[i])) { this.elementInjectors[i].clearDirectives(); } } // viewContainers if (isPresent(this.viewContainers)) { for (var i = 0; i < this.viewContainers.length; i++) { var vc = this.viewContainers[i]; if (isPresent(vc)) { vc.dehydrate(); } } } this._dehydrateContext(); } /** * Triggers the event handlers for the element and the directives. * * This method is intended to be called from directive EventEmitters. * * @param {string} eventName * @param {*} eventObj * @param {int} binderIndex */ triggerEventHandlers(eventName: string, eventObj, binderIndex: int) { var handlers = this.proto.eventHandlers[binderIndex]; if (isBlank(handlers)) return; var handler = StringMapWrapper.get(handlers, eventName); if (isBlank(handler)) return; handler(eventObj, this); } onRecordChange(directiveMemento, records:List) { this._invokeMementos(records); if (directiveMemento instanceof DirectiveMemento) { this._notifyDirectiveAboutChanges(directiveMemento, records); } } _invokeMementos(records:List) { for(var i = 0; i < records.length; ++i) { this._invokeMementoFor(records[i]); } } _notifyDirectiveAboutChanges(directiveMemento, records:List) { var dir = directiveMemento.directive(this.elementInjectors); var binding = directiveMemento.directiveBinding(this.elementInjectors); if (binding.callOnChange) { dir.onChange(this._collectChanges(records)); } } // dispatch to element injector or text nodes based on context _invokeMementoFor(record:ChangeRecord) { var memento = record.bindingMemento; if (memento instanceof DirectiveBindingMemento) { var directiveMemento:DirectiveBindingMemento = memento; directiveMemento.invoke(record, this.elementInjectors); } else if (memento instanceof ElementBindingMemento) { var elementMemento:ElementBindingMemento = memento; elementMemento.invoke(record, this.bindElements); } else { // we know it refers to _textNodes. var textNodeIndex:number = memento; DOM.setText(this.textNodes[textNodeIndex], record.currentValue); } } _collectChanges(records:List) { var changes = StringMapWrapper.create(); for(var i = 0; i < records.length; ++i) { var record = records[i]; var propertyUpdate = new PropertyUpdate(record.currentValue, record.previousValue); StringMapWrapper.set(changes, record.bindingMemento._setterName, propertyUpdate); } return changes; } } /** * @publicModule angular2/angular2 */ export class ProtoView { element; elementBinders:List<ElementBinder>; protoChangeDetector:ProtoChangeDetector; variableBindings: Map; protoLocals:Map; textNodesWithBindingCount:int; elementsWithBindingCount:int; instantiateInPlace:boolean; rootBindingOffset:int; isTemplateElement:boolean; shadowDomStrategy: ShadowDomStrategy; _viewPool: ViewPool; stylePromises: List<Promise>; // List<Map<eventName, handler>>, indexed by binder index eventHandlers:List; bindingRecords:List; parentProtoView:ProtoView; _variableBindings:List; constructor( template, protoChangeDetector:ProtoChangeDetector, shadowDomStrategy:ShadowDomStrategy, parentProtoView:ProtoView = null) { this.element = template; this.elementBinders = []; this.variableBindings = MapWrapper.create(); this.protoLocals = MapWrapper.create(); this.protoChangeDetector = protoChangeDetector; this.parentProtoView = parentProtoView; this.textNodesWithBindingCount = 0; this.elementsWithBindingCount = 0; this.instantiateInPlace = false; this.rootBindingOffset = (isPresent(this.element) && DOM.hasClass(this.element, NG_BINDING_CLASS)) ? 1 : 0; this.isTemplateElement = DOM.isTemplateElement(this.element); this.shadowDomStrategy = shadowDomStrategy; this._viewPool = new ViewPool(VIEW_POOL_CAPACITY); this.stylePromises = []; this.eventHandlers = []; this.bindingRecords = []; this._variableBindings = null; } // TODO(rado): hostElementInjector should be moved to hydrate phase. instantiate(hostElementInjector: ElementInjector, eventManager: EventManager):View { if (this._viewPool.length() == 0) this._preFillPool(hostElementInjector, eventManager); var view = this._viewPool.pop(); return isPresent(view) ? view : this._instantiate(hostElementInjector, eventManager); } _preFillPool(hostElementInjector: ElementInjector, eventManager: EventManager) { for (var i = 0; i < VIEW_POOL_PREFILL; i++) { this._viewPool.push(this._instantiate(hostElementInjector, eventManager)); } } // this work should be done the constructor of ProtoView once we separate // ProtoView and ProtoViewBuilder _getVariableBindings() { if (isPresent(this._variableBindings)) { return this._variableBindings; } this._variableBindings = isPresent(this.parentProtoView) ? ListWrapper.clone(this.parentProtoView._getVariableBindings()) : []; MapWrapper.forEach(this.protoLocals, (v, local) => { ListWrapper.push(this._variableBindings, local); }); return this._variableBindings; } _instantiate(hostElementInjector: ElementInjector, eventManager: EventManager): View { var rootElementClone = this.instantiateInPlace ? this.element : DOM.importIntoDoc(this.element); var elementsWithBindingsDynamic; if (this.isTemplateElement) { elementsWithBindingsDynamic = DOM.querySelectorAll(DOM.content(rootElementClone), NG_BINDING_CLASS_SELECTOR); } else { elementsWithBindingsDynamic= DOM.getElementsByClassName(rootElementClone, NG_BINDING_CLASS); } var elementsWithBindings = ListWrapper.createFixedSize(elementsWithBindingsDynamic.length); for (var binderIdx = 0; binderIdx < elementsWithBindingsDynamic.length; ++binderIdx) { elementsWithBindings[binderIdx] = elementsWithBindingsDynamic[binderIdx]; } var viewNodes; if (this.isTemplateElement) { var childNode = DOM.firstChild(DOM.content(rootElementClone)); viewNodes = []; // TODO(perf): Should be fixed size, since we could pre-compute in in ProtoView // Note: An explicit loop is the fastest way to convert a DOM array into a JS array! while(childNode != null) { ListWrapper.push(viewNodes, childNode); childNode = DOM.nextSibling(childNode); } } else { viewNodes = [rootElementClone]; } var view = new View(this, viewNodes, this.protoLocals); var changeDetector = this.protoChangeDetector.instantiate(view, this.bindingRecords, this._getVariableBindings()); var binders = this.elementBinders; var elementInjectors = ListWrapper.createFixedSize(binders.length); var eventHandlers = ListWrapper.createFixedSize(binders.length); var rootElementInjectors = []; var textNodes = []; var elementsWithPropertyBindings = []; var preBuiltObjects = ListWrapper.createFixedSize(binders.length); var viewContainers = ListWrapper.createFixedSize(binders.length); var contentTags = ListWrapper.createFixedSize(binders.length); var componentChildViews = []; var lightDoms = ListWrapper.createFixedSize(binders.length); for (var binderIdx = 0; binderIdx < binders.length; binderIdx++) { var binder = binders[binderIdx]; var element; if (binderIdx === 0 && this.rootBindingOffset === 1) { element = rootElementClone; } else { element = elementsWithBindings[binderIdx - this.rootBindingOffset]; } var elementInjector = null; // elementInjectors and rootElementInjectors var protoElementInjector = binder.protoElementInjector; if (isPresent(protoElementInjector)) { if (isPresent(protoElementInjector.parent)) { var parentElementInjector = elementInjectors[protoElementInjector.parent.index]; elementInjector = protoElementInjector.instantiate(parentElementInjector, null); } else { elementInjector = protoElementInjector.instantiate(null, hostElementInjector); ListWrapper.push(rootElementInjectors, elementInjector); } } elementInjectors[binderIdx] = elementInjector; if (binder.hasElementPropertyBindings) { ListWrapper.push(elementsWithPropertyBindings, element); } // textNodes var textNodeIndices = binder.textNodeIndices; if (isPresent(textNodeIndices)) { var childNode = DOM.firstChild(DOM.templateAwareRoot(element)); for (var j = 0, k = 0; j < textNodeIndices.length; j++) { for(var index = textNodeIndices[j]; k < index; k++) { childNode = DOM.nextSibling(childNode); } ListWrapper.push(textNodes, childNode); } } // componentChildViews var lightDom = null; var bindingPropagationConfig = null; if (isPresent(binder.nestedProtoView) && isPresent(binder.componentDirective)) { var strategy = this.shadowDomStrategy; var childView = binder.nestedProtoView.instantiate(elementInjector, eventManager); changeDetector.addChild(childView.changeDetector); lightDom = strategy.constructLightDom(view, childView, element); strategy.attachTemplate(element, childView); bindingPropagationConfig = new BindingPropagationConfig(changeDetector); ListWrapper.push(componentChildViews, childView); } lightDoms[binderIdx] = lightDom; var destLightDom = null; if (isPresent(binder.parent) && binder.distanceToParent === 1) { destLightDom = lightDoms[binder.parent.index]; } // viewContainers var viewContainer = null; if (isPresent(binder.viewportDirective)) { viewContainer = new ViewContainer(view, element, binder.nestedProtoView, elementInjector, eventManager, destLightDom); } viewContainers[binderIdx] = viewContainer; // contentTags var contentTag = null; if (isPresent(binder.contentTagSelector)) { contentTag = new Content(destLightDom, element, binder.contentTagSelector); } contentTags[binderIdx] = contentTag; // preBuiltObjects if (isPresent(elementInjector)) { preBuiltObjects[binderIdx] = new PreBuiltObjects(view, new NgElement(element), viewContainer, bindingPropagationConfig); } // events if (isPresent(binder.events)) { eventHandlers[binderIdx] = StringMapWrapper.create(); StringMapWrapper.forEach(binder.events, (eventMap, eventName) => { var handler = ProtoView.buildEventHandler(eventMap, binderIdx); StringMapWrapper.set(eventHandlers[binderIdx], eventName, handler); if (isBlank(elementInjector) || !elementInjector.hasEventEmitter(eventName)) { eventManager.addEventListener(element, eventName, (event) => { handler(event, view); }); } }); } } this.eventHandlers = eventHandlers; view.init(changeDetector, elementInjectors, rootElementInjectors, textNodes, elementsWithPropertyBindings, viewContainers, contentTags, preBuiltObjects, componentChildViews, lightDoms); return view; } returnToPool(view: View) { this._viewPool.push(view); } /** * Creates an event handler. * * @param {Map} eventMap Map directiveIndexes to expressions * @param {int} injectorIdx * @returns {Function} */ static buildEventHandler(eventMap: Map, injectorIdx: int) { var locals = MapWrapper.create(); return (event, view) => { // Most of the time the event will be fired only when the view is in the live document. // However, in a rare circumstance the view might get dehydrated, in between the event // queuing up and firing. if (view.hydrated()) { MapWrapper.set(locals, '$event', event); MapWrapper.forEach(eventMap, (expr, directiveIndex) => { var context; if (directiveIndex === -1) { context = view.context; } else { context = view.elementInjectors[injectorIdx].getDirectiveAtIndex(directiveIndex); } expr.eval(context, new Locals(view.locals, locals)); }); } } } bindVariable(contextName:string, templateName:string) { MapWrapper.set(this.variableBindings, contextName, templateName); MapWrapper.set(this.protoLocals, templateName, null); } bindElement(parent:ElementBinder, distanceToParent:int, protoElementInjector:ProtoElementInjector, componentDirective:DirectiveMetadata = null, viewportDirective:DirectiveMetadata = null):ElementBinder { var elBinder = new ElementBinder(this.elementBinders.length, parent, distanceToParent, protoElementInjector, componentDirective, viewportDirective); ListWrapper.push(this.elementBinders, elBinder); return elBinder; } /** * Adds a text node binding for the last created ElementBinder via bindElement */ bindTextNode(indexInParent:int, expression:AST) { var elBinder = this.elementBinders[this.elementBinders.length-1]; if (isBlank(elBinder.textNodeIndices)) { elBinder.textNodeIndices = ListWrapper.create(); } ListWrapper.push(elBinder.textNodeIndices, indexInParent); var memento = this.textNodesWithBindingCount++; ListWrapper.push(this.bindingRecords, new BindingRecord(expression, memento, null)); } /** * Adds an element property binding for the last created ElementBinder via bindElement */ bindElementProperty(expression:AST, setterName:string, setter:SetterFn) { var elBinder = this.elementBinders[this.elementBinders.length-1]; if (!elBinder.hasElementPropertyBindings) { elBinder.hasElementPropertyBindings = true; this.elementsWithBindingCount++; } var memento = new ElementBindingMemento(this.elementsWithBindingCount-1, setterName, setter); ListWrapper.push(this.bindingRecords, new BindingRecord(expression, memento, null)); } /** * Adds an event binding for the last created ElementBinder via bindElement. * * If the directive index is a positive integer, the event is evaluated in the context of * the given directive. * * If the directive index is -1, the event is evaluated in the context of the enclosing view. * * @param {string} eventName * @param {AST} expression * @param {int} directiveIndex The directive index in the binder or -1 when the event is not bound * to a directive */ bindEvent(eventName:string, expression:AST, directiveIndex: int = -1) { var elBinder = this.elementBinders[this.elementBinders.length - 1]; var events = elBinder.events; if (isBlank(events)) { events = StringMapWrapper.create(); elBinder.events = events; } var event = StringMapWrapper.get(events, eventName); if (isBlank(event)) { event = MapWrapper.create(); StringMapWrapper.set(events, eventName, event); } MapWrapper.set(event, directiveIndex, expression); } /** * Adds a directive property binding for the last created ElementBinder via bindElement */ bindDirectiveProperty( directiveIndex:number, expression:AST, setterName:string, setter:SetterFn) { var bindingMemento = new DirectiveBindingMemento( this.elementBinders.length-1, directiveIndex, setterName, setter ); var directiveMemento = DirectiveMemento.get(bindingMemento); ListWrapper.push(this.bindingRecords, new BindingRecord(expression, bindingMemento, directiveMemento)); } // Create a rootView as if the compiler encountered <rootcmp></rootcmp>, // and the component template is already compiled into protoView. // Used for bootstrapping. static createRootProtoView(protoView: ProtoView, insertionElement, rootComponentAnnotatedType: DirectiveMetadata, protoChangeDetector:ProtoChangeDetector, shadowDomStrategy: ShadowDomStrategy ): ProtoView { DOM.addClass(insertionElement, NG_BINDING_CLASS); var cmpType = rootComponentAnnotatedType.type; var rootProtoView = new ProtoView(insertionElement, protoChangeDetector, shadowDomStrategy); rootProtoView.instantiateInPlace = true; var binder = rootProtoView.bindElement(null, 0, new ProtoElementInjector(null, 0, [cmpType], true)); binder.componentDirective = rootComponentAnnotatedType; binder.nestedProtoView = protoView; shadowDomStrategy.shimAppElement(rootComponentAnnotatedType, insertionElement); return rootProtoView; } } /** * @publicModule angular2/angular2 */ export class ElementBindingMemento { _elementIndex:int; _setterName:string; _setter:SetterFn; constructor(elementIndex:int, setterName:string, setter:SetterFn) { this._elementIndex = elementIndex; this._setterName = setterName; this._setter = setter; } invoke(record:ChangeRecord, bindElements:List) { var element = bindElements[this._elementIndex]; this._setter(element, record.currentValue); } } /** * @publicModule angular2/angular2 */ export class DirectiveBindingMemento { _elementInjectorIndex:int; _directiveIndex:int; _setterName:string; _setter:SetterFn; constructor( elementInjectorIndex:number, directiveIndex:number, setterName:string, setter:SetterFn) { this._elementInjectorIndex = elementInjectorIndex; this._directiveIndex = directiveIndex; this._setterName = setterName; this._setter = setter; } invoke(record:ChangeRecord, elementInjectors:List<ElementInjector>) { var elementInjector:ElementInjector = elementInjectors[this._elementInjectorIndex]; var directive = elementInjector.getDirectiveAtIndex(this._directiveIndex); this._setter(directive, record.currentValue); } } var _directiveMementos = MapWrapper.create(); class DirectiveMemento { _elementInjectorIndex:number; _directiveIndex:number; constructor(elementInjectorIndex:number, directiveIndex:number) { this._elementInjectorIndex = elementInjectorIndex; this._directiveIndex = directiveIndex; } static get(memento:DirectiveBindingMemento) { var elementInjectorIndex = memento._elementInjectorIndex; var directiveIndex = memento._directiveIndex; var id = elementInjectorIndex * 100 + directiveIndex; if (!MapWrapper.contains(_directiveMementos, id)) { MapWrapper.set(_directiveMementos, id, new DirectiveMemento(elementInjectorIndex, directiveIndex)); } return MapWrapper.get(_directiveMementos, id); } directive(elementInjectors:List<ElementInjector>) { var elementInjector:ElementInjector = elementInjectors[this._elementInjectorIndex]; return elementInjector.getDirectiveAtIndex(this._directiveIndex); } directiveBinding(elementInjectors:List<ElementInjector>) { var elementInjector:ElementInjector = elementInjectors[this._elementInjectorIndex]; return elementInjector.getDirectiveBindingAtIndex(this._directiveIndex); } } /** * @publicModule angular2/angular2 */ export class PropertyUpdate { currentValue; previousValue; constructor(currentValue, previousValue) { this.currentValue = currentValue; this.previousValue = previousValue; } static createWithoutPrevious(currentValue) { return new PropertyUpdate(currentValue, uninitialized); } }
modules/angular2/src/core/compiler/view.js
0
https://github.com/angular/angular/commit/e0710c4613ba51f008bc8a2f4874fb1fade9d09f
[ 0.0005939110415056348, 0.0001851286506280303, 0.00015996803995221853, 0.00016754615353420377, 0.00006649576243944466 ]
{ "id": 0, "code_window": [ "// Group 6 = identifier inside parenthesis\n", "// Group 7 = \"#\"\n", "// Group 8 = identifier after \"#\"\n", "var BIND_NAME_REGEXP = RegExpWrapper.create(\n", " '^(?:(?:(bind)|(var)|(on))-(.+))|\\\\[([^\\\\]]+)\\\\]|\\\\(([^\\\\)]+)\\\\)|(#)(.+)');\n", "\n", "/**\n", " * Parses the property bindings on a single element.\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " '^(?:(?:(?:(bind)|(var)|(on))-(.+))|\\\\[([^\\\\]]+)\\\\]|\\\\(([^\\\\)]+)\\\\)|(#)(.+))$');\n" ], "file_path": "modules/angular2/src/core/compiler/pipeline/property_binding_parser.js", "type": "replace", "edit_start_line_idx": 19 }
import { AsyncTestCompleter, beforeEach, ddescribe, describe, el, expect, iit, inject, IS_DARTIUM, it, xit, } from 'angular2/test_lib'; import {DOM} from 'angular2/src/dom/dom_adapter'; import {Injector} from 'angular2/di'; import {Lexer, Parser, ChangeDetector, dynamicChangeDetection} from 'angular2/change_detection'; import {Compiler, CompilerCache} from 'angular2/src/core/compiler/compiler'; import {DirectiveMetadataReader} from 'angular2/src/core/compiler/directive_metadata_reader'; import {NativeShadowDomStrategy} from 'angular2/src/core/compiler/shadow_dom_strategy'; import {TemplateLoader} from 'angular2/src/core/compiler/template_loader'; import {ComponentUrlMapper} from 'angular2/src/core/compiler/component_url_mapper'; import {UrlResolver} from 'angular2/src/core/compiler/url_resolver'; import {StyleUrlResolver} from 'angular2/src/core/compiler/style_url_resolver'; import {CssProcessor} from 'angular2/src/core/compiler/css_processor'; import {Component} from 'angular2/src/core/annotations/annotations'; import {Template} from 'angular2/src/core/annotations/template'; import {MockTemplateResolver} from 'angular2/src/mock/template_resolver_mock'; import {If} from 'angular2/src/directives/if'; export function main() { describe('if directive', () => { var view, cd, compiler, component, tplResolver; beforeEach(() => { var urlResolver = new UrlResolver(); tplResolver = new MockTemplateResolver(); compiler = new Compiler( dynamicChangeDetection, new TemplateLoader(null, null), new DirectiveMetadataReader(), new Parser(new Lexer()), new CompilerCache(), new NativeShadowDomStrategy(new StyleUrlResolver(urlResolver)), tplResolver, new ComponentUrlMapper(), urlResolver, new CssProcessor(null) ); }); function createView(pv) { component = new TestComponent(); view = pv.instantiate(null, null); view.hydrate(new Injector([]), null, null, component, null); cd = view.changeDetector; } function compileWithTemplate(html) { var template = new Template({ inline: html, directives: [If] }); tplResolver.setTemplate(TestComponent, template); return compiler.compile(TestComponent); } it('should work in a template attribute', inject([AsyncTestCompleter], (async) => { compileWithTemplate('<div><copy-me template="if booleanCondition">hello</copy-me></div>').then((pv) => { createView(pv); cd.detectChanges(); expect(DOM.querySelectorAll(view.nodes[0], 'copy-me').length).toEqual(1); expect(DOM.getText(view.nodes[0])).toEqual('hello'); async.done(); }); })); it('should work in a template element', inject([AsyncTestCompleter], (async) => { compileWithTemplate('<div><template [if]="booleanCondition"><copy-me>hello2</copy-me></template></div>').then((pv) => { createView(pv); cd.detectChanges(); expect(DOM.querySelectorAll(view.nodes[0], 'copy-me').length).toEqual(1); expect(DOM.getText(view.nodes[0])).toEqual('hello2'); async.done(); }); })); it('should toggle node when condition changes', inject([AsyncTestCompleter], (async) => { compileWithTemplate('<div><copy-me template="if booleanCondition">hello</copy-me></div>').then((pv) => { createView(pv); component.booleanCondition = false; cd.detectChanges(); expect(DOM.querySelectorAll(view.nodes[0], 'copy-me').length).toEqual(0); expect(DOM.getText(view.nodes[0])).toEqual(''); component.booleanCondition = true; cd.detectChanges(); expect(DOM.querySelectorAll(view.nodes[0], 'copy-me').length).toEqual(1); expect(DOM.getText(view.nodes[0])).toEqual('hello'); component.booleanCondition = false; cd.detectChanges(); expect(DOM.querySelectorAll(view.nodes[0], 'copy-me').length).toEqual(0); expect(DOM.getText(view.nodes[0])).toEqual(''); async.done(); }); })); it('should update several nodes with if', inject([AsyncTestCompleter], (async) => { var templateString = '<div>' + '<copy-me template="if numberCondition + 1 >= 2">helloNumber</copy-me>' + '<copy-me template="if stringCondition == \'foo\'">helloString</copy-me>' + '<copy-me template="if functionCondition(stringCondition, numberCondition)">helloFunction</copy-me>' + '</div>'; compileWithTemplate(templateString).then((pv) => { createView(pv); cd.detectChanges(); expect(DOM.querySelectorAll(view.nodes[0], 'copy-me').length).toEqual(3); expect(DOM.getText(view.nodes[0])).toEqual('helloNumberhelloStringhelloFunction'); component.numberCondition = 0; cd.detectChanges(); expect(DOM.querySelectorAll(view.nodes[0], 'copy-me').length).toEqual(1); expect(DOM.getText(view.nodes[0])).toEqual('helloString'); component.numberCondition = 1; component.stringCondition = "bar"; cd.detectChanges(); expect(DOM.querySelectorAll(view.nodes[0], 'copy-me').length).toEqual(1); expect(DOM.getText(view.nodes[0])).toEqual('helloNumber'); async.done(); }); })); if (!IS_DARTIUM) { it('should leave the element if the condition is a non-empty string (JS)', inject([AsyncTestCompleter], (async) => { compileWithTemplate('<div><copy-me template="if stringCondition">hello</copy-me></div>').then((pv) => { createView(pv); cd.detectChanges(); expect(DOM.querySelectorAll(view.nodes[0], 'copy-me').length).toEqual(1); expect(DOM.getText(view.nodes[0])).toEqual('hello'); async.done(); }); })); it('should leave the element if the condition is an object (JS)', inject([AsyncTestCompleter], (async) => { compileWithTemplate('<div><copy-me template="if objectCondition">hello</copy-me></div>').then((pv) => { createView(pv); cd.detectChanges(); expect(DOM.querySelectorAll(view.nodes[0], 'copy-me').length).toEqual(1); expect(DOM.getText(view.nodes[0])).toEqual('hello'); async.done(); }); })); it('should remove the element if the condition is null (JS)', inject([AsyncTestCompleter], (async) => { compileWithTemplate('<div><copy-me template="if nullCondition">hello</copy-me></div>').then((pv) => { createView(pv); cd.detectChanges(); expect(DOM.querySelectorAll(view.nodes[0], 'copy-me').length).toEqual(0); expect(DOM.getText(view.nodes[0])).toEqual(''); async.done(); }); })); it('should not add the element twice if the condition goes from true to true (JS)', inject([AsyncTestCompleter], (async) => { compileWithTemplate('<div><copy-me template="if numberCondition">hello</copy-me></div>').then((pv) => { createView(pv); cd.detectChanges(); expect(DOM.querySelectorAll(view.nodes[0], 'copy-me').length).toEqual(1); expect(DOM.getText(view.nodes[0])).toEqual('hello'); component.numberCondition = 2; cd.detectChanges(); expect(DOM.querySelectorAll(view.nodes[0], 'copy-me').length).toEqual(1); expect(DOM.getText(view.nodes[0])).toEqual('hello'); async.done(); }); })); it('should not recreate the element if the condition goes from true to true (JS)', inject([AsyncTestCompleter], (async) => { compileWithTemplate('<div><copy-me template="if numberCondition">hello</copy-me></div>').then((pv) => { createView(pv); cd.detectChanges(); DOM.addClass(view.nodes[0].childNodes[1], "foo"); component.numberCondition = 2; cd.detectChanges(); expect(DOM.hasClass(view.nodes[0].childNodes[1], "foo")).toBe(true); async.done(); }); })); } else { it('should not create the element if the condition is not a boolean (DART)', inject([AsyncTestCompleter], (async) => { compileWithTemplate('<div><copy-me template="if numberCondition">hello</copy-me></div>').then((pv) => { createView(pv); expect(function(){cd.detectChanges();}).toThrowError(); expect(DOM.querySelectorAll(view.nodes[0], 'copy-me').length).toEqual(0); expect(DOM.getText(view.nodes[0])).toEqual(''); async.done(); }); })); } }); } @Component({selector: 'test-cmp'}) class TestComponent { booleanCondition: boolean; numberCondition: number; stringCondition: string; functionCondition: Function; objectCondition: any; nullCondition: any; constructor() { this.booleanCondition = true; this.numberCondition = 1; this.stringCondition = "foo"; this.functionCondition = function(s, n){ return s == "foo" && n == 1; }; this.objectCondition = {}; this.nullCondition = null; } }
modules/angular2/test/directives/if_spec.js
0
https://github.com/angular/angular/commit/e0710c4613ba51f008bc8a2f4874fb1fade9d09f
[ 0.0001726760674500838, 0.00016987956769298762, 0.00016575309564359486, 0.00017034326447173953, 0.0000020522259092103923 ]
{ "id": 0, "code_window": [ "// Group 6 = identifier inside parenthesis\n", "// Group 7 = \"#\"\n", "// Group 8 = identifier after \"#\"\n", "var BIND_NAME_REGEXP = RegExpWrapper.create(\n", " '^(?:(?:(bind)|(var)|(on))-(.+))|\\\\[([^\\\\]]+)\\\\]|\\\\(([^\\\\)]+)\\\\)|(#)(.+)');\n", "\n", "/**\n", " * Parses the property bindings on a single element.\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " '^(?:(?:(?:(bind)|(var)|(on))-(.+))|\\\\[([^\\\\]]+)\\\\]|\\\\(([^\\\\)]+)\\\\)|(#)(.+))$');\n" ], "file_path": "modules/angular2/src/core/compiler/pipeline/property_binding_parser.js", "type": "replace", "edit_start_line_idx": 19 }
var _ = require('lodash'); module.exports = function processModuleDocs(log, ExportTreeVisitor, getJSDocComment) { return { $runAfter: ['files-read'], $runBefore: ['parsing-tags', 'generateDocsFromComments'], $process: function(docs) { var exportDocs = []; _.forEach(docs, function(doc) { if ( doc.docType === 'module' ) { log.debug('processing', doc.moduleTree.moduleName); doc.exports = []; if ( doc.moduleTree.visit ) { var visitor = new ExportTreeVisitor(); visitor.visit(doc.moduleTree); _.forEach(visitor.exports, function(exportDoc) { doc.exports.push(exportDoc); exportDocs.push(exportDoc); exportDoc.moduleDoc = doc; if (exportDoc.comment) { // If this export has a comment, remove it from the list of // comments collected in the module var index = doc.comments.indexOf(exportDoc.comment); if ( index !== -1 ) { doc.comments.splice(index, 1); } _.assign(exportDoc, getJSDocComment(exportDoc.comment)); } }); } } }); return docs.concat(exportDocs); } }; };
docs/dgeni-package/processors/processModuleDocs.js
0
https://github.com/angular/angular/commit/e0710c4613ba51f008bc8a2f4874fb1fade9d09f
[ 0.00016932595463003963, 0.00016733509255573153, 0.0001654295774642378, 0.00016804758342914283, 0.0000015439450180565473 ]
{ "id": 1, "code_window": [ " it('should detect [] syntax', () => {\n", " var results = createPipeline().process(el('<div [a]=\"b\"></div>'));\n", " expect(MapWrapper.get(results[0].propertyBindings, 'a').source).toEqual('b');\n", " });\n", "\n", " it('should detect bind- syntax', () => {\n", " var results = createPipeline().process(el('<div bind-a=\"b\"></div>'));\n", " expect(MapWrapper.get(results[0].propertyBindings, 'a').source).toEqual('b');\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " it('should detect [] syntax only if an attribute name starts and ends with []', () => {\n", " expect(createPipeline().process(el('<div z[a]=\"b\"></div>'))[0].propertyBindings).toBe(null);\n", " expect(createPipeline().process(el('<div [a]v=\"b\"></div>'))[0].propertyBindings).toBe(null);\n", " });\n", "\n" ], "file_path": "modules/angular2/test/core/compiler/pipeline/property_binding_parser_spec.js", "type": "add", "edit_start_line_idx": 27 }
import {describe, beforeEach, it, expect, iit, ddescribe, el} from 'angular2/test_lib'; import {PropertyBindingParser} from 'angular2/src/core/compiler/pipeline/property_binding_parser'; import {CompilePipeline} from 'angular2/src/core/compiler/pipeline/compile_pipeline'; import {MapWrapper} from 'angular2/src/facade/collection'; import {CompileElement} from 'angular2/src/core/compiler/pipeline/compile_element'; import {CompileStep} from 'angular2/src/core/compiler/pipeline/compile_step' import {CompileControl} from 'angular2/src/core/compiler/pipeline/compile_control'; import {Lexer, Parser} from 'angular2/change_detection'; export function main() { describe('PropertyBindingParser', () => { function createPipeline(ignoreBindings = false) { return new CompilePipeline([ new MockStep((parent, current, control) => { current.ignoreBindings = ignoreBindings; }), new PropertyBindingParser(new Parser(new Lexer()))]); } it('should not parse bindings when ignoreBindings is true', () => { var results = createPipeline(true).process(el('<div [a]="b"></div>')); expect(results[0].propertyBindings).toBe(null); }); it('should detect [] syntax', () => { var results = createPipeline().process(el('<div [a]="b"></div>')); expect(MapWrapper.get(results[0].propertyBindings, 'a').source).toEqual('b'); }); it('should detect bind- syntax', () => { var results = createPipeline().process(el('<div bind-a="b"></div>')); expect(MapWrapper.get(results[0].propertyBindings, 'a').source).toEqual('b'); }); it('should detect interpolation syntax', () => { // Note: we don't test all corner cases of interpolation as we assume shared functionality between text interpolation // and attribute interpolation. var results = createPipeline().process(el('<div a="{{b}}"></div>')); expect(MapWrapper.get(results[0].propertyBindings, 'a').source).toEqual('{{b}}'); }); it('should detect var- syntax', () => { var results = createPipeline().process(el('<template var-a="b"></template>')); expect(MapWrapper.get(results[0].variableBindings, 'b')).toEqual('a'); }); it('should store variable binding for a non-template element', () => { var results = createPipeline().process(el('<p var-george="washington"></p>')); expect(MapWrapper.get(results[0].variableBindings, 'washington')).toEqual('george'); }); it('should store variable binding for a non-template element using shorthand syntax', () => { var results = createPipeline().process(el('<p #george="washington"></p>')); expect(MapWrapper.get(results[0].variableBindings, 'washington')).toEqual('george'); }); it('should store a variable binding with an implicit value', () => { var results = createPipeline().process(el('<p var-george></p>')); expect(MapWrapper.get(results[0].variableBindings, '\$implicit')).toEqual('george'); }); it('should store a variable binding with an implicit value using shorthand syntax', () => { var results = createPipeline().process(el('<p #george></p>')); expect(MapWrapper.get(results[0].variableBindings, '\$implicit')).toEqual('george'); }); it('should detect () syntax', () => { var results = createPipeline().process(el('<div (click)="b()"></div>')); expect(MapWrapper.get(results[0].eventBindings, 'click').source).toEqual('b()'); // "(click[])" is not an expected syntax and is only used to validate the regexp results = createPipeline().process(el('<div (click[])="b()"></div>')); expect(MapWrapper.get(results[0].eventBindings, 'click[]').source).toEqual('b()'); }); it('should parse event handlers using () syntax as actions', () => { var results = createPipeline().process(el('<div (click)="foo=bar"></div>')); expect(MapWrapper.get(results[0].eventBindings, 'click').source).toEqual('foo=bar'); }); it('should detect on- syntax', () => { var results = createPipeline().process(el('<div on-click="b()"></div>')); expect(MapWrapper.get(results[0].eventBindings, 'click').source).toEqual('b()'); }); it('should parse event handlers using on- syntax as actions', () => { var results = createPipeline().process(el('<div on-click="foo=bar"></div>')); expect(MapWrapper.get(results[0].eventBindings, 'click').source).toEqual('foo=bar'); }); }); } class MockStep extends CompileStep { processClosure:Function; constructor(process) { super(); this.processClosure = process; } process(parent:CompileElement, current:CompileElement, control:CompileControl) { this.processClosure(parent, current, control); } }
modules/angular2/test/core/compiler/pipeline/property_binding_parser_spec.js
1
https://github.com/angular/angular/commit/e0710c4613ba51f008bc8a2f4874fb1fade9d09f
[ 0.9985132813453674, 0.3564760386943817, 0.00016866030637174845, 0.11098288744688034, 0.4200480878353119 ]
{ "id": 1, "code_window": [ " it('should detect [] syntax', () => {\n", " var results = createPipeline().process(el('<div [a]=\"b\"></div>'));\n", " expect(MapWrapper.get(results[0].propertyBindings, 'a').source).toEqual('b');\n", " });\n", "\n", " it('should detect bind- syntax', () => {\n", " var results = createPipeline().process(el('<div bind-a=\"b\"></div>'));\n", " expect(MapWrapper.get(results[0].propertyBindings, 'a').source).toEqual('b');\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " it('should detect [] syntax only if an attribute name starts and ends with []', () => {\n", " expect(createPipeline().process(el('<div z[a]=\"b\"></div>'))[0].propertyBindings).toBe(null);\n", " expect(createPipeline().process(el('<div [a]v=\"b\"></div>'))[0].propertyBindings).toBe(null);\n", " });\n", "\n" ], "file_path": "modules/angular2/test/core/compiler/pipeline/property_binding_parser_spec.js", "type": "add", "edit_start_line_idx": 27 }
import {DOM} from 'angular2/src/dom/dom_adapter'; import {Promise} from 'angular2/src/facade/async'; import {ListWrapper, MapWrapper, Map, StringMapWrapper, List} from 'angular2/src/facade/collection'; import {AST, Locals, ChangeDispatcher, ProtoChangeDetector, ChangeDetector, ChangeRecord, BindingRecord, uninitialized} from 'angular2/change_detection'; import {ProtoElementInjector, ElementInjector, PreBuiltObjects} from './element_injector'; import {BindingPropagationConfig} from './binding_propagation_config'; import {ElementBinder} from './element_binder'; import {DirectiveMetadata} from './directive_metadata'; import {SetterFn} from 'angular2/src/reflection/types'; import {IMPLEMENTS, int, isPresent, isBlank, BaseException} from 'angular2/src/facade/lang'; import {Injector} from 'angular2/di'; import {NgElement} from 'angular2/src/core/dom/element'; import {ViewContainer} from './view_container'; import {LightDom} from './shadow_dom_emulation/light_dom'; import {Content} from './shadow_dom_emulation/content_tag'; import {ShadowDomStrategy} from './shadow_dom_strategy'; import {ViewPool} from './view_pool'; import {EventManager} from 'angular2/src/core/events/event_manager'; const NG_BINDING_CLASS = 'ng-binding'; const NG_BINDING_CLASS_SELECTOR = '.ng-binding'; // TODO(rado): make this configurable/smarter. var VIEW_POOL_CAPACITY = 10000; var VIEW_POOL_PREFILL = 0; /** * Const of making objects: http://jsperf.com/instantiate-size-of-object * @publicModule angular2/angular2 */ @IMPLEMENTS(ChangeDispatcher) export class View { /// This list matches the _nodes list. It is sparse, since only Elements have ElementInjector rootElementInjectors:List<ElementInjector>; elementInjectors:List<ElementInjector>; bindElements:List; textNodes:List; changeDetector:ChangeDetector; /// When the view is part of render tree, the DocumentFragment is empty, which is why we need /// to keep track of the nodes. nodes:List; componentChildViews: List<View>; viewContainers: List<ViewContainer>; contentTags: List<Content>; preBuiltObjects: List<PreBuiltObjects>; lightDoms: List<LightDom>; proto: ProtoView; context: any; locals:Locals; constructor(proto:ProtoView, nodes:List, protoLocals:Map) { this.proto = proto; this.nodes = nodes; this.changeDetector = null; this.elementInjectors = null; this.rootElementInjectors = null; this.textNodes = null; this.bindElements = null; this.componentChildViews = null; this.viewContainers = null; this.contentTags = null; this.preBuiltObjects = null; this.lightDoms = null; this.context = null; this.locals = new Locals(null, MapWrapper.clone(protoLocals)); //TODO optimize this } init(changeDetector:ChangeDetector, elementInjectors:List, rootElementInjectors:List, textNodes: List, bindElements:List, viewContainers:List, contentTags:List, preBuiltObjects:List, componentChildViews:List, lightDoms:List<LightDom>) { this.changeDetector = changeDetector; this.elementInjectors = elementInjectors; this.rootElementInjectors = rootElementInjectors; this.textNodes = textNodes; this.bindElements = bindElements; this.viewContainers = viewContainers; this.contentTags = contentTags; this.preBuiltObjects = preBuiltObjects; this.componentChildViews = componentChildViews; this.lightDoms = lightDoms; } setLocal(contextName: string, value) { if (!this.hydrated()) throw new BaseException('Cannot set locals on dehydrated view.'); if (!MapWrapper.contains(this.proto.variableBindings, contextName)) { return; } var templateName = MapWrapper.get(this.proto.variableBindings, contextName); this.locals.set(templateName, value); } hydrated() { return isPresent(this.context); } _hydrateContext(newContext, locals) { this.context = newContext; this.locals.parent = locals; this.changeDetector.hydrate(this.context, this.locals); } _dehydrateContext() { if (isPresent(this.locals)) { this.locals.clearValues(); } this.context = null; this.changeDetector.dehydrate(); } /** * A dehydrated view is a state of the view that allows it to be moved around * the view tree, without incurring the cost of recreating the underlying * injectors and watch records. * * A dehydrated view has the following properties: * * - all element injectors are empty. * - all appInjectors are released. * - all viewcontainers are empty. * - all context locals are set to null. * - the view context is null. * * A call to hydrate/dehydrate does not attach/detach the view from the view * tree. */ hydrate(appInjector: Injector, hostElementInjector: ElementInjector, hostLightDom: LightDom, context: Object, locals:Locals) { if (this.hydrated()) throw new BaseException('The view is already hydrated.'); this._hydrateContext(context, locals); // viewContainers for (var i = 0; i < this.viewContainers.length; i++) { var vc = this.viewContainers[i]; if (isPresent(vc)) { vc.hydrate(appInjector, hostElementInjector, hostLightDom); } } var binders = this.proto.elementBinders; var componentChildViewIndex = 0; for (var i = 0; i < binders.length; ++i) { var componentDirective = binders[i].componentDirective; var shadowDomAppInjector = null; // shadowDomAppInjector if (isPresent(componentDirective)) { var services = componentDirective.annotation.services; if (isPresent(services)) shadowDomAppInjector = appInjector.createChild(services); else { shadowDomAppInjector = appInjector; } } else { shadowDomAppInjector = null; } // elementInjectors var elementInjector = this.elementInjectors[i]; if (isPresent(elementInjector)) { elementInjector.instantiateDirectives(appInjector, shadowDomAppInjector, this.preBuiltObjects[i]); // The exporting of $implicit is a special case. Since multiple elements will all export // the different values as $implicit, directly assign $implicit bindings to the variable // name. var exportImplicitName = elementInjector.getExportImplicitName(); if (elementInjector.isExportingComponent()) { this.locals.set(exportImplicitName, elementInjector.getComponent()); } else if (elementInjector.isExportingElement()) { this.locals.set(exportImplicitName, elementInjector.getNgElement().domElement); } } if (isPresent(binders[i].nestedProtoView) && isPresent(componentDirective)) { this.componentChildViews[componentChildViewIndex++].hydrate(shadowDomAppInjector, elementInjector, this.lightDoms[i], elementInjector.getComponent(), null); } } for (var i = 0; i < this.lightDoms.length; ++i) { var lightDom = this.lightDoms[i]; if (isPresent(lightDom)) { lightDom.redistribute(); } } } dehydrate() { // Note: preserve the opposite order of the hydration process. // componentChildViews for (var i = 0; i < this.componentChildViews.length; i++) { this.componentChildViews[i].dehydrate(); } // elementInjectors for (var i = 0; i < this.elementInjectors.length; i++) { if (isPresent(this.elementInjectors[i])) { this.elementInjectors[i].clearDirectives(); } } // viewContainers if (isPresent(this.viewContainers)) { for (var i = 0; i < this.viewContainers.length; i++) { var vc = this.viewContainers[i]; if (isPresent(vc)) { vc.dehydrate(); } } } this._dehydrateContext(); } /** * Triggers the event handlers for the element and the directives. * * This method is intended to be called from directive EventEmitters. * * @param {string} eventName * @param {*} eventObj * @param {int} binderIndex */ triggerEventHandlers(eventName: string, eventObj, binderIndex: int) { var handlers = this.proto.eventHandlers[binderIndex]; if (isBlank(handlers)) return; var handler = StringMapWrapper.get(handlers, eventName); if (isBlank(handler)) return; handler(eventObj, this); } onRecordChange(directiveMemento, records:List) { this._invokeMementos(records); if (directiveMemento instanceof DirectiveMemento) { this._notifyDirectiveAboutChanges(directiveMemento, records); } } _invokeMementos(records:List) { for(var i = 0; i < records.length; ++i) { this._invokeMementoFor(records[i]); } } _notifyDirectiveAboutChanges(directiveMemento, records:List) { var dir = directiveMemento.directive(this.elementInjectors); var binding = directiveMemento.directiveBinding(this.elementInjectors); if (binding.callOnChange) { dir.onChange(this._collectChanges(records)); } } // dispatch to element injector or text nodes based on context _invokeMementoFor(record:ChangeRecord) { var memento = record.bindingMemento; if (memento instanceof DirectiveBindingMemento) { var directiveMemento:DirectiveBindingMemento = memento; directiveMemento.invoke(record, this.elementInjectors); } else if (memento instanceof ElementBindingMemento) { var elementMemento:ElementBindingMemento = memento; elementMemento.invoke(record, this.bindElements); } else { // we know it refers to _textNodes. var textNodeIndex:number = memento; DOM.setText(this.textNodes[textNodeIndex], record.currentValue); } } _collectChanges(records:List) { var changes = StringMapWrapper.create(); for(var i = 0; i < records.length; ++i) { var record = records[i]; var propertyUpdate = new PropertyUpdate(record.currentValue, record.previousValue); StringMapWrapper.set(changes, record.bindingMemento._setterName, propertyUpdate); } return changes; } } /** * @publicModule angular2/angular2 */ export class ProtoView { element; elementBinders:List<ElementBinder>; protoChangeDetector:ProtoChangeDetector; variableBindings: Map; protoLocals:Map; textNodesWithBindingCount:int; elementsWithBindingCount:int; instantiateInPlace:boolean; rootBindingOffset:int; isTemplateElement:boolean; shadowDomStrategy: ShadowDomStrategy; _viewPool: ViewPool; stylePromises: List<Promise>; // List<Map<eventName, handler>>, indexed by binder index eventHandlers:List; bindingRecords:List; parentProtoView:ProtoView; _variableBindings:List; constructor( template, protoChangeDetector:ProtoChangeDetector, shadowDomStrategy:ShadowDomStrategy, parentProtoView:ProtoView = null) { this.element = template; this.elementBinders = []; this.variableBindings = MapWrapper.create(); this.protoLocals = MapWrapper.create(); this.protoChangeDetector = protoChangeDetector; this.parentProtoView = parentProtoView; this.textNodesWithBindingCount = 0; this.elementsWithBindingCount = 0; this.instantiateInPlace = false; this.rootBindingOffset = (isPresent(this.element) && DOM.hasClass(this.element, NG_BINDING_CLASS)) ? 1 : 0; this.isTemplateElement = DOM.isTemplateElement(this.element); this.shadowDomStrategy = shadowDomStrategy; this._viewPool = new ViewPool(VIEW_POOL_CAPACITY); this.stylePromises = []; this.eventHandlers = []; this.bindingRecords = []; this._variableBindings = null; } // TODO(rado): hostElementInjector should be moved to hydrate phase. instantiate(hostElementInjector: ElementInjector, eventManager: EventManager):View { if (this._viewPool.length() == 0) this._preFillPool(hostElementInjector, eventManager); var view = this._viewPool.pop(); return isPresent(view) ? view : this._instantiate(hostElementInjector, eventManager); } _preFillPool(hostElementInjector: ElementInjector, eventManager: EventManager) { for (var i = 0; i < VIEW_POOL_PREFILL; i++) { this._viewPool.push(this._instantiate(hostElementInjector, eventManager)); } } // this work should be done the constructor of ProtoView once we separate // ProtoView and ProtoViewBuilder _getVariableBindings() { if (isPresent(this._variableBindings)) { return this._variableBindings; } this._variableBindings = isPresent(this.parentProtoView) ? ListWrapper.clone(this.parentProtoView._getVariableBindings()) : []; MapWrapper.forEach(this.protoLocals, (v, local) => { ListWrapper.push(this._variableBindings, local); }); return this._variableBindings; } _instantiate(hostElementInjector: ElementInjector, eventManager: EventManager): View { var rootElementClone = this.instantiateInPlace ? this.element : DOM.importIntoDoc(this.element); var elementsWithBindingsDynamic; if (this.isTemplateElement) { elementsWithBindingsDynamic = DOM.querySelectorAll(DOM.content(rootElementClone), NG_BINDING_CLASS_SELECTOR); } else { elementsWithBindingsDynamic= DOM.getElementsByClassName(rootElementClone, NG_BINDING_CLASS); } var elementsWithBindings = ListWrapper.createFixedSize(elementsWithBindingsDynamic.length); for (var binderIdx = 0; binderIdx < elementsWithBindingsDynamic.length; ++binderIdx) { elementsWithBindings[binderIdx] = elementsWithBindingsDynamic[binderIdx]; } var viewNodes; if (this.isTemplateElement) { var childNode = DOM.firstChild(DOM.content(rootElementClone)); viewNodes = []; // TODO(perf): Should be fixed size, since we could pre-compute in in ProtoView // Note: An explicit loop is the fastest way to convert a DOM array into a JS array! while(childNode != null) { ListWrapper.push(viewNodes, childNode); childNode = DOM.nextSibling(childNode); } } else { viewNodes = [rootElementClone]; } var view = new View(this, viewNodes, this.protoLocals); var changeDetector = this.protoChangeDetector.instantiate(view, this.bindingRecords, this._getVariableBindings()); var binders = this.elementBinders; var elementInjectors = ListWrapper.createFixedSize(binders.length); var eventHandlers = ListWrapper.createFixedSize(binders.length); var rootElementInjectors = []; var textNodes = []; var elementsWithPropertyBindings = []; var preBuiltObjects = ListWrapper.createFixedSize(binders.length); var viewContainers = ListWrapper.createFixedSize(binders.length); var contentTags = ListWrapper.createFixedSize(binders.length); var componentChildViews = []; var lightDoms = ListWrapper.createFixedSize(binders.length); for (var binderIdx = 0; binderIdx < binders.length; binderIdx++) { var binder = binders[binderIdx]; var element; if (binderIdx === 0 && this.rootBindingOffset === 1) { element = rootElementClone; } else { element = elementsWithBindings[binderIdx - this.rootBindingOffset]; } var elementInjector = null; // elementInjectors and rootElementInjectors var protoElementInjector = binder.protoElementInjector; if (isPresent(protoElementInjector)) { if (isPresent(protoElementInjector.parent)) { var parentElementInjector = elementInjectors[protoElementInjector.parent.index]; elementInjector = protoElementInjector.instantiate(parentElementInjector, null); } else { elementInjector = protoElementInjector.instantiate(null, hostElementInjector); ListWrapper.push(rootElementInjectors, elementInjector); } } elementInjectors[binderIdx] = elementInjector; if (binder.hasElementPropertyBindings) { ListWrapper.push(elementsWithPropertyBindings, element); } // textNodes var textNodeIndices = binder.textNodeIndices; if (isPresent(textNodeIndices)) { var childNode = DOM.firstChild(DOM.templateAwareRoot(element)); for (var j = 0, k = 0; j < textNodeIndices.length; j++) { for(var index = textNodeIndices[j]; k < index; k++) { childNode = DOM.nextSibling(childNode); } ListWrapper.push(textNodes, childNode); } } // componentChildViews var lightDom = null; var bindingPropagationConfig = null; if (isPresent(binder.nestedProtoView) && isPresent(binder.componentDirective)) { var strategy = this.shadowDomStrategy; var childView = binder.nestedProtoView.instantiate(elementInjector, eventManager); changeDetector.addChild(childView.changeDetector); lightDom = strategy.constructLightDom(view, childView, element); strategy.attachTemplate(element, childView); bindingPropagationConfig = new BindingPropagationConfig(changeDetector); ListWrapper.push(componentChildViews, childView); } lightDoms[binderIdx] = lightDom; var destLightDom = null; if (isPresent(binder.parent) && binder.distanceToParent === 1) { destLightDom = lightDoms[binder.parent.index]; } // viewContainers var viewContainer = null; if (isPresent(binder.viewportDirective)) { viewContainer = new ViewContainer(view, element, binder.nestedProtoView, elementInjector, eventManager, destLightDom); } viewContainers[binderIdx] = viewContainer; // contentTags var contentTag = null; if (isPresent(binder.contentTagSelector)) { contentTag = new Content(destLightDom, element, binder.contentTagSelector); } contentTags[binderIdx] = contentTag; // preBuiltObjects if (isPresent(elementInjector)) { preBuiltObjects[binderIdx] = new PreBuiltObjects(view, new NgElement(element), viewContainer, bindingPropagationConfig); } // events if (isPresent(binder.events)) { eventHandlers[binderIdx] = StringMapWrapper.create(); StringMapWrapper.forEach(binder.events, (eventMap, eventName) => { var handler = ProtoView.buildEventHandler(eventMap, binderIdx); StringMapWrapper.set(eventHandlers[binderIdx], eventName, handler); if (isBlank(elementInjector) || !elementInjector.hasEventEmitter(eventName)) { eventManager.addEventListener(element, eventName, (event) => { handler(event, view); }); } }); } } this.eventHandlers = eventHandlers; view.init(changeDetector, elementInjectors, rootElementInjectors, textNodes, elementsWithPropertyBindings, viewContainers, contentTags, preBuiltObjects, componentChildViews, lightDoms); return view; } returnToPool(view: View) { this._viewPool.push(view); } /** * Creates an event handler. * * @param {Map} eventMap Map directiveIndexes to expressions * @param {int} injectorIdx * @returns {Function} */ static buildEventHandler(eventMap: Map, injectorIdx: int) { var locals = MapWrapper.create(); return (event, view) => { // Most of the time the event will be fired only when the view is in the live document. // However, in a rare circumstance the view might get dehydrated, in between the event // queuing up and firing. if (view.hydrated()) { MapWrapper.set(locals, '$event', event); MapWrapper.forEach(eventMap, (expr, directiveIndex) => { var context; if (directiveIndex === -1) { context = view.context; } else { context = view.elementInjectors[injectorIdx].getDirectiveAtIndex(directiveIndex); } expr.eval(context, new Locals(view.locals, locals)); }); } } } bindVariable(contextName:string, templateName:string) { MapWrapper.set(this.variableBindings, contextName, templateName); MapWrapper.set(this.protoLocals, templateName, null); } bindElement(parent:ElementBinder, distanceToParent:int, protoElementInjector:ProtoElementInjector, componentDirective:DirectiveMetadata = null, viewportDirective:DirectiveMetadata = null):ElementBinder { var elBinder = new ElementBinder(this.elementBinders.length, parent, distanceToParent, protoElementInjector, componentDirective, viewportDirective); ListWrapper.push(this.elementBinders, elBinder); return elBinder; } /** * Adds a text node binding for the last created ElementBinder via bindElement */ bindTextNode(indexInParent:int, expression:AST) { var elBinder = this.elementBinders[this.elementBinders.length-1]; if (isBlank(elBinder.textNodeIndices)) { elBinder.textNodeIndices = ListWrapper.create(); } ListWrapper.push(elBinder.textNodeIndices, indexInParent); var memento = this.textNodesWithBindingCount++; ListWrapper.push(this.bindingRecords, new BindingRecord(expression, memento, null)); } /** * Adds an element property binding for the last created ElementBinder via bindElement */ bindElementProperty(expression:AST, setterName:string, setter:SetterFn) { var elBinder = this.elementBinders[this.elementBinders.length-1]; if (!elBinder.hasElementPropertyBindings) { elBinder.hasElementPropertyBindings = true; this.elementsWithBindingCount++; } var memento = new ElementBindingMemento(this.elementsWithBindingCount-1, setterName, setter); ListWrapper.push(this.bindingRecords, new BindingRecord(expression, memento, null)); } /** * Adds an event binding for the last created ElementBinder via bindElement. * * If the directive index is a positive integer, the event is evaluated in the context of * the given directive. * * If the directive index is -1, the event is evaluated in the context of the enclosing view. * * @param {string} eventName * @param {AST} expression * @param {int} directiveIndex The directive index in the binder or -1 when the event is not bound * to a directive */ bindEvent(eventName:string, expression:AST, directiveIndex: int = -1) { var elBinder = this.elementBinders[this.elementBinders.length - 1]; var events = elBinder.events; if (isBlank(events)) { events = StringMapWrapper.create(); elBinder.events = events; } var event = StringMapWrapper.get(events, eventName); if (isBlank(event)) { event = MapWrapper.create(); StringMapWrapper.set(events, eventName, event); } MapWrapper.set(event, directiveIndex, expression); } /** * Adds a directive property binding for the last created ElementBinder via bindElement */ bindDirectiveProperty( directiveIndex:number, expression:AST, setterName:string, setter:SetterFn) { var bindingMemento = new DirectiveBindingMemento( this.elementBinders.length-1, directiveIndex, setterName, setter ); var directiveMemento = DirectiveMemento.get(bindingMemento); ListWrapper.push(this.bindingRecords, new BindingRecord(expression, bindingMemento, directiveMemento)); } // Create a rootView as if the compiler encountered <rootcmp></rootcmp>, // and the component template is already compiled into protoView. // Used for bootstrapping. static createRootProtoView(protoView: ProtoView, insertionElement, rootComponentAnnotatedType: DirectiveMetadata, protoChangeDetector:ProtoChangeDetector, shadowDomStrategy: ShadowDomStrategy ): ProtoView { DOM.addClass(insertionElement, NG_BINDING_CLASS); var cmpType = rootComponentAnnotatedType.type; var rootProtoView = new ProtoView(insertionElement, protoChangeDetector, shadowDomStrategy); rootProtoView.instantiateInPlace = true; var binder = rootProtoView.bindElement(null, 0, new ProtoElementInjector(null, 0, [cmpType], true)); binder.componentDirective = rootComponentAnnotatedType; binder.nestedProtoView = protoView; shadowDomStrategy.shimAppElement(rootComponentAnnotatedType, insertionElement); return rootProtoView; } } /** * @publicModule angular2/angular2 */ export class ElementBindingMemento { _elementIndex:int; _setterName:string; _setter:SetterFn; constructor(elementIndex:int, setterName:string, setter:SetterFn) { this._elementIndex = elementIndex; this._setterName = setterName; this._setter = setter; } invoke(record:ChangeRecord, bindElements:List) { var element = bindElements[this._elementIndex]; this._setter(element, record.currentValue); } } /** * @publicModule angular2/angular2 */ export class DirectiveBindingMemento { _elementInjectorIndex:int; _directiveIndex:int; _setterName:string; _setter:SetterFn; constructor( elementInjectorIndex:number, directiveIndex:number, setterName:string, setter:SetterFn) { this._elementInjectorIndex = elementInjectorIndex; this._directiveIndex = directiveIndex; this._setterName = setterName; this._setter = setter; } invoke(record:ChangeRecord, elementInjectors:List<ElementInjector>) { var elementInjector:ElementInjector = elementInjectors[this._elementInjectorIndex]; var directive = elementInjector.getDirectiveAtIndex(this._directiveIndex); this._setter(directive, record.currentValue); } } var _directiveMementos = MapWrapper.create(); class DirectiveMemento { _elementInjectorIndex:number; _directiveIndex:number; constructor(elementInjectorIndex:number, directiveIndex:number) { this._elementInjectorIndex = elementInjectorIndex; this._directiveIndex = directiveIndex; } static get(memento:DirectiveBindingMemento) { var elementInjectorIndex = memento._elementInjectorIndex; var directiveIndex = memento._directiveIndex; var id = elementInjectorIndex * 100 + directiveIndex; if (!MapWrapper.contains(_directiveMementos, id)) { MapWrapper.set(_directiveMementos, id, new DirectiveMemento(elementInjectorIndex, directiveIndex)); } return MapWrapper.get(_directiveMementos, id); } directive(elementInjectors:List<ElementInjector>) { var elementInjector:ElementInjector = elementInjectors[this._elementInjectorIndex]; return elementInjector.getDirectiveAtIndex(this._directiveIndex); } directiveBinding(elementInjectors:List<ElementInjector>) { var elementInjector:ElementInjector = elementInjectors[this._elementInjectorIndex]; return elementInjector.getDirectiveBindingAtIndex(this._directiveIndex); } } /** * @publicModule angular2/angular2 */ export class PropertyUpdate { currentValue; previousValue; constructor(currentValue, previousValue) { this.currentValue = currentValue; this.previousValue = previousValue; } static createWithoutPrevious(currentValue) { return new PropertyUpdate(currentValue, uninitialized); } }
modules/angular2/src/core/compiler/view.js
0
https://github.com/angular/angular/commit/e0710c4613ba51f008bc8a2f4874fb1fade9d09f
[ 0.0029157318640500307, 0.0002276731829624623, 0.0001602431439096108, 0.00017022796964738518, 0.0003396343090571463 ]
{ "id": 1, "code_window": [ " it('should detect [] syntax', () => {\n", " var results = createPipeline().process(el('<div [a]=\"b\"></div>'));\n", " expect(MapWrapper.get(results[0].propertyBindings, 'a').source).toEqual('b');\n", " });\n", "\n", " it('should detect bind- syntax', () => {\n", " var results = createPipeline().process(el('<div bind-a=\"b\"></div>'));\n", " expect(MapWrapper.get(results[0].propertyBindings, 'a').source).toEqual('b');\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " it('should detect [] syntax only if an attribute name starts and ends with []', () => {\n", " expect(createPipeline().process(el('<div z[a]=\"b\"></div>'))[0].propertyBindings).toBe(null);\n", " expect(createPipeline().process(el('<div [a]v=\"b\"></div>'))[0].propertyBindings).toBe(null);\n", " });\n", "\n" ], "file_path": "modules/angular2/test/core/compiler/pipeline/property_binding_parser_spec.js", "type": "add", "edit_start_line_idx": 27 }
import {int, isBlank, BaseException} from 'angular2/src/facade/lang'; import * as eiModule from './element_injector'; import {DirectiveMetadata} from './directive_metadata'; import {List, StringMap} from 'angular2/src/facade/collection'; import * as viewModule from './view'; export class ElementBinder { protoElementInjector:eiModule.ProtoElementInjector; componentDirective:DirectiveMetadata; viewportDirective:DirectiveMetadata; textNodeIndices:List<int>; hasElementPropertyBindings:boolean; nestedProtoView: viewModule.ProtoView; events:StringMap; contentTagSelector:string; parent:ElementBinder; index:int; distanceToParent:int; constructor( index:int, parent:ElementBinder, distanceToParent: int, protoElementInjector: eiModule.ProtoElementInjector, componentDirective:DirectiveMetadata, viewportDirective:DirectiveMetadata) { if (isBlank(index)) { throw new BaseException('null index not allowed.'); } this.protoElementInjector = protoElementInjector; this.componentDirective = componentDirective; this.viewportDirective = viewportDirective; this.parent = parent; this.index = index; this.distanceToParent = distanceToParent; // updated later when events are bound this.events = null; // updated later when text nodes are bound this.textNodeIndices = null; // updated later when element properties are bound this.hasElementPropertyBindings = false; // updated later, so we are able to resolve cycles this.nestedProtoView = null; // updated later in the compilation pipeline this.contentTagSelector = null; } }
modules/angular2/src/core/compiler/element_binder.js
0
https://github.com/angular/angular/commit/e0710c4613ba51f008bc8a2f4874fb1fade9d09f
[ 0.00017481199756730348, 0.00017171839135698974, 0.00016617690562270582, 0.0001722984598018229, 0.0000031546044283459196 ]
{ "id": 1, "code_window": [ " it('should detect [] syntax', () => {\n", " var results = createPipeline().process(el('<div [a]=\"b\"></div>'));\n", " expect(MapWrapper.get(results[0].propertyBindings, 'a').source).toEqual('b');\n", " });\n", "\n", " it('should detect bind- syntax', () => {\n", " var results = createPipeline().process(el('<div bind-a=\"b\"></div>'));\n", " expect(MapWrapper.get(results[0].propertyBindings, 'a').source).toEqual('b');\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " it('should detect [] syntax only if an attribute name starts and ends with []', () => {\n", " expect(createPipeline().process(el('<div z[a]=\"b\"></div>'))[0].propertyBindings).toBe(null);\n", " expect(createPipeline().process(el('<div [a]v=\"b\"></div>'))[0].propertyBindings).toBe(null);\n", " });\n", "\n" ], "file_path": "modules/angular2/test/core/compiler/pipeline/property_binding_parser_spec.js", "type": "add", "edit_start_line_idx": 27 }
// # Assert.js // A run-time type assertion library for JavaScript. Designed to be used with [Traceur](https://github.com/google/traceur-compiler). // - [Basic Type Check](#basic-type-check) // - [Custom Check](#custom-check) // - [Primitive Values](#primitive-values) // - [Describing more complex types](#describing-more-complex-types) // - [assert.arrayOf](#assert-arrayof) // - [assert.structure](#assert-structure) // - [Integrating with Traceur](#integrating-with-traceur) // Note: `assert` gets automatically included by traceur! export function main() { describe('prettyPrint', () => { class Type {}; it('should limit the number of printed properties', () => { var o = {}; for (var i = 0; i < 100; i++) { o['p_' + i] = i; } try { assert.type(o, Type); throw 'fail!'; } catch (e) { expect(e.message.indexOf('p_0')).toBeGreaterThan(-1); expect(e.message.indexOf('...')).toBeGreaterThan(-1); expect(e.message.indexOf('p_20')).toBe(-1); } }); it('should limit the depth of printed properties', () => { var o = {l1: {l2: {l3: {l4: {l5: {l6: 'deep'}}}}}}; expect(() => { assert.type(o, Type); }).toThrowError('Expected an instance of Type, got {l1: {l2: {l3: {l4: [...]}}}}!'); }); }); // ## Basic Type Check // By default, `instanceof` is used to check the type. // // Note that you can use `assert.type()` in unit tests or anywhere in your code. // Most of the time, you will use it with Traceur. // Jump to the [Traceur section](#integrating-with-traceur) to see an example of that. describe('basic type check', function() { class Type {} it('should pass', function() { assert.type(new Type(), Type); }); it('should fail', function() { expect(() => assert.type(123, Type)) .toThrowError('Expected an instance of Type, got 123!'); }); it('should allow null', function() { assert.type(null, Type); }); }); // ## Custom Check // Often, `instanceof` is not flexible enough. // In that case, your type can define its own `assert` method which will be used instead. // // See [Describing More Complex Types](#describing-more-complex-types) for examples how to // define custom checks using `assert.define()`. describe('custom check', function() { class Type {} // the basic check can just return true/false, without specifying any reason it('should pass when returns true', function() { Type.assert = function(value) { return true; }; assert.type({}, Type); }); it('should fail when returns false', function() { Type.assert = function(value) { return false; }; expect(() => assert.type({}, Type)) .toThrowError('Expected an instance of Type, got {}!'); }); // Using `assert.fail()` allows to report even multiple errors. it('should fail when calls assert.fail()', function() { Type.assert = function(value) { assert.fail('not smart enough'); assert.fail('not blue enough'); }; expect(() => assert.type({}, Type)) .toThrowError('Expected an instance of Type, got {}!\n' + ' - not smart enough\n' + ' - not blue enough'); }); it('should fail when throws an exception', function() { Type.assert = function(value) { throw new Error('not long enough'); }; expect(function() { assert.type(12345, Type); }).toThrowError('Expected an instance of Type, got 12345!\n' + ' - not long enough'); }); }); // ## Primitive Values // You don't want to check primitive values (such as strings, numbers, or booleans) using `typeof` rather than // `instanceof`. // // Again, you probably won't write this code and rather use Traceur to do it for you, simply based on type annotations. describe('primitive value check', function() { var primitive = $traceurRuntime.type; describe('string', function() { it('should pass', function() { assert.type('xxx', primitive.string); }); it('should fail', function() { expect(() => assert.type(12345, primitive.string)) .toThrowError('Expected an instance of string, got 12345!'); }); it('should allow null', function() { assert.type(null, primitive.string); }); }); describe('number', function() { it('should pass', function() { assert.type(123, primitive.number); }); it('should fail', function() { expect(() => assert.type(false, primitive.number)) .toThrowError('Expected an instance of number, got false!'); }); it('should allow null', function() { assert.type(null, primitive.number); }); }); describe('boolean', function() { it('should pass', function() { expect(assert.type(true, primitive.boolean)).toBe(true); expect(assert.type(false, primitive.boolean)).toBe(false); }); it('should fail', function() { expect(() => assert.type(123, primitive.boolean)) .toThrowError('Expected an instance of boolean, got 123!'); }); it('should allow null', function() { assert.type(null, primitive.boolean); }); }); }); // ## Describing more complex types // // Often, a simple type check using `instanceof` or `typeof` is not enough. // That's why you can define custom checks using this DSL. // The goal was to make them easy to compose and as descriptive as possible. // Of course you can write your own DSL on the top of this. describe('define', function() { // If the first argument to `assert.define()` is a type (function), it will define `assert` method on that function. // // In this example, being a type of Type means being a either a function or object. it('should define assert for an existing type', function() { class Type {} assert.define(Type, function(value) { assert(value).is(Function, Object); }); assert.type({}, Type); assert.type(function() {}, Type); expect(() => assert.type('str', Type)) .toThrowError('Expected an instance of Type, got "str"!\n' + ' - "str" is not instance of Function\n' + ' - "str" is not instance of Object'); }); // If the first argument to `assert.define()` is a string, // it will create an interface - basically an empty class with `assert` method. it('should define an interface', function() { var User = assert.define('MyUser', function(user) { assert(user).is(Object); }); assert.type({}, User); expect(() => assert.type(12345, User)) .toThrowError('Expected an instance of MyUser, got 12345!\n' + ' - 12345 is not instance of Object'); }); // Here are a couple of more APIs to describe your custom types... // // ### assert.arrayOf // Checks if the value is an array and if so, it checks whether all the items are one the given types. // These types can be composed types, not just simple ones. describe('arrayOf', function() { var Titles = assert.define('ListOfTitles', function(value) { assert(value).is(assert.arrayOf(assert.string, assert.number)); }); it('should pass', function () { assert.type(['one', 55, 'two'], Titles); }); it('should fail when non-array given', function () { expect(() => assert.type('foo', Titles)) .toThrowError('Expected an instance of ListOfTitles, got "foo"!\n' + ' - "foo" is not instance of array of string/number\n' + ' - "foo" is not instance of Array'); }); it('should fail when an invalid item in the array', function () { expect(() => assert.type(['aaa', true], Titles)) .toThrowError('Expected an instance of ListOfTitles, got ["aaa", true]!\n' + ' - ["aaa", true] is not instance of array of string/number\n' + ' - true is not instance of string\n' + ' - true is not instance of number'); }); }); // ### assert.structure // Similar to `assert.arrayOf` which checks a content of an array, // `assert.structure` checks if the value is an object with specific properties. describe('structure', function() { var User = assert.define('MyUser', function(value) { assert(value).is(assert.structure({ name: assert.string, age: assert.number })); }); it('should pass', function () { assert.type({name: 'Vojta', age: 28}, User); }); it('should fail when non-object given', function () { expect(() => assert.type(123, User)) .toThrowError('Expected an instance of MyUser, got 123!\n' + ' - 123 is not instance of object with properties name, age\n' + ' - 123 is not instance of Object'); }); it('should fail when an invalid property', function () { expect(() => assert.type({name: 'Vojta', age: true}, User)) .toThrowError('Expected an instance of MyUser, got {name: "Vojta", age: true}!\n' + ' - {name: "Vojta", age: true} is not instance of object with properties name, age\n' + ' - true is not instance of number'); }); }); }); // ## Integrating with Traceur // // Manually calling `assert.type()` in your code is cumbersome. Most of the time, you'll want to // have Traceur add the calls to `assert.type()` to your code based on type annotations. // // This has several advantages: // - it's shorter and nicer, // - you can easily ignore it when generating production code. // // You'll need to run Traceur with `--types=true --type-assertions=true --type-assertion-module="path/to/assert"`. describe('Traceur', function() { describe('arguments', function() { function reverse(str: string) { return str ? reverse(str.substring(1)) + str[0] : '' } it('should pass', function() { expect(reverse('angular')).toBe('ralugna'); }); it('should fail', function() { expect(() => reverse(123)) .toThrowError('Invalid arguments given!\n' + ' - 1st argument has to be an instance of string, got 123'); }); }); describe('return value', function() { function foo(bar): number { return bar; } it('should pass', function() { expect(foo(123)).toBe(123); }); it('should fail', function() { expect(() => foo('bar')) .toThrowError('Expected to return an instance of number, got "bar"!'); }); }); describe('variables', function() { it('should pass', function() { var count:number = 1; }); it('should fail', function() { expect(() => { var count: number = true; }).toThrowError('Expected an instance of number, got true!'); }); }); describe('void', function() { function foo(bar): void { return bar; } it('should pass when not defined', function() { function nonReturn(): void {} function returnNothing(): void { return; } function returnUndefined(): void { return undefined; } foo(); foo(undefined); nonReturn(); returnNothing(); returnUndefined(); }); it('should fail when a value returned', function() { expect(() => foo('bar')) .toThrowError('Expected to return an instance of void, got "bar"!'); }); it('should fail when null returned', function() { expect(() => foo(null)) .toThrowError('Expected to return an instance of void, got null!'); }); }); describe('generics', function() { it('should pass', function() { var list:Array<string> = []; }); // TODO(tbosch): add assertions based on generics to rtts_assert }); }); }
modules/rtts_assert/test/rtts_assert_spec.es6
0
https://github.com/angular/angular/commit/e0710c4613ba51f008bc8a2f4874fb1fade9d09f
[ 0.00017595784447621554, 0.0001688509073574096, 0.0001617620582692325, 0.00016935520397964865, 0.000003106200438196538 ]
{ "id": 2, "code_window": [ " it('should detect bind- syntax', () => {\n", " var results = createPipeline().process(el('<div bind-a=\"b\"></div>'));\n", " expect(MapWrapper.get(results[0].propertyBindings, 'a').source).toEqual('b');\n", " });\n", "\n", " it('should detect interpolation syntax', () => {\n", " // Note: we don't test all corner cases of interpolation as we assume shared functionality between text interpolation\n", " // and attribute interpolation.\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " it('should detect bind- syntax only if an attribute name starts with bind', () => {\n", " expect(createPipeline().process(el('<div _bind-a=\"b\"></div>'))[0].propertyBindings).toBe(null);\n", " });\n", "\n" ], "file_path": "modules/angular2/test/core/compiler/pipeline/property_binding_parser_spec.js", "type": "add", "edit_start_line_idx": 32 }
import {describe, beforeEach, it, expect, iit, ddescribe, el} from 'angular2/test_lib'; import {PropertyBindingParser} from 'angular2/src/core/compiler/pipeline/property_binding_parser'; import {CompilePipeline} from 'angular2/src/core/compiler/pipeline/compile_pipeline'; import {MapWrapper} from 'angular2/src/facade/collection'; import {CompileElement} from 'angular2/src/core/compiler/pipeline/compile_element'; import {CompileStep} from 'angular2/src/core/compiler/pipeline/compile_step' import {CompileControl} from 'angular2/src/core/compiler/pipeline/compile_control'; import {Lexer, Parser} from 'angular2/change_detection'; export function main() { describe('PropertyBindingParser', () => { function createPipeline(ignoreBindings = false) { return new CompilePipeline([ new MockStep((parent, current, control) => { current.ignoreBindings = ignoreBindings; }), new PropertyBindingParser(new Parser(new Lexer()))]); } it('should not parse bindings when ignoreBindings is true', () => { var results = createPipeline(true).process(el('<div [a]="b"></div>')); expect(results[0].propertyBindings).toBe(null); }); it('should detect [] syntax', () => { var results = createPipeline().process(el('<div [a]="b"></div>')); expect(MapWrapper.get(results[0].propertyBindings, 'a').source).toEqual('b'); }); it('should detect bind- syntax', () => { var results = createPipeline().process(el('<div bind-a="b"></div>')); expect(MapWrapper.get(results[0].propertyBindings, 'a').source).toEqual('b'); }); it('should detect interpolation syntax', () => { // Note: we don't test all corner cases of interpolation as we assume shared functionality between text interpolation // and attribute interpolation. var results = createPipeline().process(el('<div a="{{b}}"></div>')); expect(MapWrapper.get(results[0].propertyBindings, 'a').source).toEqual('{{b}}'); }); it('should detect var- syntax', () => { var results = createPipeline().process(el('<template var-a="b"></template>')); expect(MapWrapper.get(results[0].variableBindings, 'b')).toEqual('a'); }); it('should store variable binding for a non-template element', () => { var results = createPipeline().process(el('<p var-george="washington"></p>')); expect(MapWrapper.get(results[0].variableBindings, 'washington')).toEqual('george'); }); it('should store variable binding for a non-template element using shorthand syntax', () => { var results = createPipeline().process(el('<p #george="washington"></p>')); expect(MapWrapper.get(results[0].variableBindings, 'washington')).toEqual('george'); }); it('should store a variable binding with an implicit value', () => { var results = createPipeline().process(el('<p var-george></p>')); expect(MapWrapper.get(results[0].variableBindings, '\$implicit')).toEqual('george'); }); it('should store a variable binding with an implicit value using shorthand syntax', () => { var results = createPipeline().process(el('<p #george></p>')); expect(MapWrapper.get(results[0].variableBindings, '\$implicit')).toEqual('george'); }); it('should detect () syntax', () => { var results = createPipeline().process(el('<div (click)="b()"></div>')); expect(MapWrapper.get(results[0].eventBindings, 'click').source).toEqual('b()'); // "(click[])" is not an expected syntax and is only used to validate the regexp results = createPipeline().process(el('<div (click[])="b()"></div>')); expect(MapWrapper.get(results[0].eventBindings, 'click[]').source).toEqual('b()'); }); it('should parse event handlers using () syntax as actions', () => { var results = createPipeline().process(el('<div (click)="foo=bar"></div>')); expect(MapWrapper.get(results[0].eventBindings, 'click').source).toEqual('foo=bar'); }); it('should detect on- syntax', () => { var results = createPipeline().process(el('<div on-click="b()"></div>')); expect(MapWrapper.get(results[0].eventBindings, 'click').source).toEqual('b()'); }); it('should parse event handlers using on- syntax as actions', () => { var results = createPipeline().process(el('<div on-click="foo=bar"></div>')); expect(MapWrapper.get(results[0].eventBindings, 'click').source).toEqual('foo=bar'); }); }); } class MockStep extends CompileStep { processClosure:Function; constructor(process) { super(); this.processClosure = process; } process(parent:CompileElement, current:CompileElement, control:CompileControl) { this.processClosure(parent, current, control); } }
modules/angular2/test/core/compiler/pipeline/property_binding_parser_spec.js
1
https://github.com/angular/angular/commit/e0710c4613ba51f008bc8a2f4874fb1fade9d09f
[ 0.9980353713035583, 0.20840415358543396, 0.00016611890168860555, 0.010275272652506828, 0.3910134732723236 ]
{ "id": 2, "code_window": [ " it('should detect bind- syntax', () => {\n", " var results = createPipeline().process(el('<div bind-a=\"b\"></div>'));\n", " expect(MapWrapper.get(results[0].propertyBindings, 'a').source).toEqual('b');\n", " });\n", "\n", " it('should detect interpolation syntax', () => {\n", " // Note: we don't test all corner cases of interpolation as we assume shared functionality between text interpolation\n", " // and attribute interpolation.\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " it('should detect bind- syntax only if an attribute name starts with bind', () => {\n", " expect(createPipeline().process(el('<div _bind-a=\"b\"></div>'))[0].propertyBindings).toBe(null);\n", " });\n", "\n" ], "file_path": "modules/angular2/test/core/compiler/pipeline/property_binding_parser_spec.js", "type": "add", "edit_start_line_idx": 32 }
var _ = require('lodash'); module.exports = function processClassDocs(log, getJSDocComment) { return { $runAfter: ['processModuleDocs'], $runBefore: ['parsing-tags', 'generateDocsFromComments'], ignorePrivateMembers: false, $process: function(docs) { var memberDocs = []; var ignorePrivateMembers = this.ignorePrivateMembers; _.forEach(docs, function(classDoc) { if ( classDoc.docType === 'class' ) { classDoc.members = []; // Create a new doc for each member of the class _.forEach(classDoc.elements, function(memberDoc) { if (ignorePrivateMembers && memberDoc.name.literalToken.value.charAt(0) === '_') return; classDoc.members.push(memberDoc); memberDocs.push(memberDoc); memberDoc.docType = 'member'; memberDoc.classDoc = classDoc; memberDoc.name = memberDoc.name.literalToken.value; if (memberDoc.commentBefore ) { // If this export has a comment, remove it from the list of // comments collected in the module var index = classDoc.moduleDoc.comments.indexOf(memberDoc.commentBefore); if ( index !== -1 ) { classDoc.moduleDoc.comments.splice(index, 1); } _.assign(memberDoc, getJSDocComment(memberDoc.commentBefore)); } }); } }); return docs.concat(memberDocs); } }; };
docs/dgeni-package/processors/processClassDocs.js
0
https://github.com/angular/angular/commit/e0710c4613ba51f008bc8a2f4874fb1fade9d09f
[ 0.00017326833039987832, 0.00017047050641849637, 0.00016708875773474574, 0.00017061099060811102, 0.000001982704816327896 ]
{ "id": 2, "code_window": [ " it('should detect bind- syntax', () => {\n", " var results = createPipeline().process(el('<div bind-a=\"b\"></div>'));\n", " expect(MapWrapper.get(results[0].propertyBindings, 'a').source).toEqual('b');\n", " });\n", "\n", " it('should detect interpolation syntax', () => {\n", " // Note: we don't test all corner cases of interpolation as we assume shared functionality between text interpolation\n", " // and attribute interpolation.\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " it('should detect bind- syntax only if an attribute name starts with bind', () => {\n", " expect(createPipeline().process(el('<div _bind-a=\"b\"></div>'))[0].propertyBindings).toBe(null);\n", " });\n", "\n" ], "file_path": "modules/angular2/test/core/compiler/pipeline/property_binding_parser_spec.js", "type": "add", "edit_start_line_idx": 32 }
/** * Define public API for Angular here. */ export * from './change_detection'; export * from './core'; export * from './directives'; export * from './forms';
modules/angular2/angular2.js
0
https://github.com/angular/angular/commit/e0710c4613ba51f008bc8a2f4874fb1fade9d09f
[ 0.0001674595841905102, 0.0001674595841905102, 0.0001674595841905102, 0.0001674595841905102, 0 ]
{ "id": 2, "code_window": [ " it('should detect bind- syntax', () => {\n", " var results = createPipeline().process(el('<div bind-a=\"b\"></div>'));\n", " expect(MapWrapper.get(results[0].propertyBindings, 'a').source).toEqual('b');\n", " });\n", "\n", " it('should detect interpolation syntax', () => {\n", " // Note: we don't test all corner cases of interpolation as we assume shared functionality between text interpolation\n", " // and attribute interpolation.\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " it('should detect bind- syntax only if an attribute name starts with bind', () => {\n", " expect(createPipeline().process(el('<div _bind-a=\"b\"></div>'))[0].propertyBindings).toBe(null);\n", " });\n", "\n" ], "file_path": "modules/angular2/test/core/compiler/pipeline/property_binding_parser_spec.js", "type": "add", "edit_start_line_idx": 32 }
library bar; import 'package:angular2/src/core/annotations/annotations.dart'; import 'package:angular2/src/core/annotations/template.dart'; @Component(selector: '[soup]') @Template(inline: 'Salad') class MyComponent { MyComponent(); }
modules/angular2/test/transform/integration/two_annotations_files/bar.dart
0
https://github.com/angular/angular/commit/e0710c4613ba51f008bc8a2f4874fb1fade9d09f
[ 0.00017179694259539247, 0.00016963743837550282, 0.0001674779487075284, 0.00016963743837550282, 0.0000021594969439320266 ]
{ "id": 3, "code_window": [ " expect(MapWrapper.get(results[0].variableBindings, '\\$implicit')).toEqual('george');\n", " });\n", "\n", " it('should detect () syntax', () => {\n", " var results = createPipeline().process(el('<div (click)=\"b()\"></div>'));\n", " expect(MapWrapper.get(results[0].eventBindings, 'click').source).toEqual('b()');\n", " // \"(click[])\" is not an expected syntax and is only used to validate the regexp\n", " results = createPipeline().process(el('<div (click[])=\"b()\"></div>'));\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " it('should detect variable bindings only if an attribute name starts with #', () => {\n", " var results = createPipeline().process(el('<p b#george></p>'));\n", " expect(results[0].variableBindings).toBe(null);\n", " });\n", "\n" ], "file_path": "modules/angular2/test/core/compiler/pipeline/property_binding_parser_spec.js", "type": "add", "edit_start_line_idx": 64 }
import {describe, beforeEach, it, expect, iit, ddescribe, el} from 'angular2/test_lib'; import {PropertyBindingParser} from 'angular2/src/core/compiler/pipeline/property_binding_parser'; import {CompilePipeline} from 'angular2/src/core/compiler/pipeline/compile_pipeline'; import {MapWrapper} from 'angular2/src/facade/collection'; import {CompileElement} from 'angular2/src/core/compiler/pipeline/compile_element'; import {CompileStep} from 'angular2/src/core/compiler/pipeline/compile_step' import {CompileControl} from 'angular2/src/core/compiler/pipeline/compile_control'; import {Lexer, Parser} from 'angular2/change_detection'; export function main() { describe('PropertyBindingParser', () => { function createPipeline(ignoreBindings = false) { return new CompilePipeline([ new MockStep((parent, current, control) => { current.ignoreBindings = ignoreBindings; }), new PropertyBindingParser(new Parser(new Lexer()))]); } it('should not parse bindings when ignoreBindings is true', () => { var results = createPipeline(true).process(el('<div [a]="b"></div>')); expect(results[0].propertyBindings).toBe(null); }); it('should detect [] syntax', () => { var results = createPipeline().process(el('<div [a]="b"></div>')); expect(MapWrapper.get(results[0].propertyBindings, 'a').source).toEqual('b'); }); it('should detect bind- syntax', () => { var results = createPipeline().process(el('<div bind-a="b"></div>')); expect(MapWrapper.get(results[0].propertyBindings, 'a').source).toEqual('b'); }); it('should detect interpolation syntax', () => { // Note: we don't test all corner cases of interpolation as we assume shared functionality between text interpolation // and attribute interpolation. var results = createPipeline().process(el('<div a="{{b}}"></div>')); expect(MapWrapper.get(results[0].propertyBindings, 'a').source).toEqual('{{b}}'); }); it('should detect var- syntax', () => { var results = createPipeline().process(el('<template var-a="b"></template>')); expect(MapWrapper.get(results[0].variableBindings, 'b')).toEqual('a'); }); it('should store variable binding for a non-template element', () => { var results = createPipeline().process(el('<p var-george="washington"></p>')); expect(MapWrapper.get(results[0].variableBindings, 'washington')).toEqual('george'); }); it('should store variable binding for a non-template element using shorthand syntax', () => { var results = createPipeline().process(el('<p #george="washington"></p>')); expect(MapWrapper.get(results[0].variableBindings, 'washington')).toEqual('george'); }); it('should store a variable binding with an implicit value', () => { var results = createPipeline().process(el('<p var-george></p>')); expect(MapWrapper.get(results[0].variableBindings, '\$implicit')).toEqual('george'); }); it('should store a variable binding with an implicit value using shorthand syntax', () => { var results = createPipeline().process(el('<p #george></p>')); expect(MapWrapper.get(results[0].variableBindings, '\$implicit')).toEqual('george'); }); it('should detect () syntax', () => { var results = createPipeline().process(el('<div (click)="b()"></div>')); expect(MapWrapper.get(results[0].eventBindings, 'click').source).toEqual('b()'); // "(click[])" is not an expected syntax and is only used to validate the regexp results = createPipeline().process(el('<div (click[])="b()"></div>')); expect(MapWrapper.get(results[0].eventBindings, 'click[]').source).toEqual('b()'); }); it('should parse event handlers using () syntax as actions', () => { var results = createPipeline().process(el('<div (click)="foo=bar"></div>')); expect(MapWrapper.get(results[0].eventBindings, 'click').source).toEqual('foo=bar'); }); it('should detect on- syntax', () => { var results = createPipeline().process(el('<div on-click="b()"></div>')); expect(MapWrapper.get(results[0].eventBindings, 'click').source).toEqual('b()'); }); it('should parse event handlers using on- syntax as actions', () => { var results = createPipeline().process(el('<div on-click="foo=bar"></div>')); expect(MapWrapper.get(results[0].eventBindings, 'click').source).toEqual('foo=bar'); }); }); } class MockStep extends CompileStep { processClosure:Function; constructor(process) { super(); this.processClosure = process; } process(parent:CompileElement, current:CompileElement, control:CompileControl) { this.processClosure(parent, current, control); } }
modules/angular2/test/core/compiler/pipeline/property_binding_parser_spec.js
1
https://github.com/angular/angular/commit/e0710c4613ba51f008bc8a2f4874fb1fade9d09f
[ 0.9981322884559631, 0.19604738056659698, 0.00016704652807675302, 0.03873785585165024, 0.31281188130378723 ]
{ "id": 3, "code_window": [ " expect(MapWrapper.get(results[0].variableBindings, '\\$implicit')).toEqual('george');\n", " });\n", "\n", " it('should detect () syntax', () => {\n", " var results = createPipeline().process(el('<div (click)=\"b()\"></div>'));\n", " expect(MapWrapper.get(results[0].eventBindings, 'click').source).toEqual('b()');\n", " // \"(click[])\" is not an expected syntax and is only used to validate the regexp\n", " results = createPipeline().process(el('<div (click[])=\"b()\"></div>'));\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " it('should detect variable bindings only if an attribute name starts with #', () => {\n", " var results = createPipeline().process(el('<p b#george></p>'));\n", " expect(results[0].variableBindings).toBe(null);\n", " });\n", "\n" ], "file_path": "modules/angular2/test/core/compiler/pipeline/property_binding_parser_spec.js", "type": "add", "edit_start_line_idx": 64 }
import {isPresent, isBlank, BaseException, Type, isString} from 'angular2/src/facade/lang'; import {List, ListWrapper, MapWrapper, StringMapWrapper} from 'angular2/src/facade/collection'; import { AccessMember, Assignment, AST, ASTWithSource, AstVisitor, Binary, Chain, Conditional, Pipe, FunctionCall, ImplicitReceiver, Interpolation, KeyedAccess, LiteralArray, LiteralMap, LiteralPrimitive, MethodCall, PrefixNot } from './parser/ast'; import {ChangeRecord, ChangeDispatcher, ChangeDetector} from './interfaces'; import {ChangeDetectionUtil} from './change_detection_util'; import {DynamicChangeDetector} from './dynamic_change_detector'; import {ChangeDetectorJITGenerator} from './change_detection_jit_generator'; import {PipeRegistry} from './pipes/pipe_registry'; import {coalesce} from './coalesce'; import { ProtoRecord, RECORD_TYPE_SELF, RECORD_TYPE_PROPERTY, RECORD_TYPE_LOCAL, RECORD_TYPE_INVOKE_METHOD, RECORD_TYPE_CONST, RECORD_TYPE_INVOKE_CLOSURE, RECORD_TYPE_PRIMITIVE_OP, RECORD_TYPE_KEYED_ACCESS, RECORD_TYPE_PIPE, RECORD_TYPE_INTERPOLATE } from './proto_record'; export class ProtoChangeDetector { addAst(ast:AST, bindingMemento:any, directiveMemento:any = null){} instantiate(dispatcher:any, bindingRecords:List, variableBindings:List):ChangeDetector{ return null; } } export class BindingRecord { ast:AST; bindingMemento:any; directiveMemento:any; constructor(ast:AST, bindingMemento:any, directiveMemento:any) { this.ast = ast; this.bindingMemento = bindingMemento; this.directiveMemento = directiveMemento; } } export class DynamicProtoChangeDetector extends ProtoChangeDetector { _pipeRegistry:PipeRegistry; _records:List<ProtoRecord>; constructor(pipeRegistry:PipeRegistry) { super(); this._pipeRegistry = pipeRegistry; } instantiate(dispatcher:any, bindingRecords:List, variableBindings:List) { this._createRecordsIfNecessary(bindingRecords, variableBindings); return new DynamicChangeDetector(dispatcher, this._pipeRegistry, this._records); } _createRecordsIfNecessary(bindingRecords:List, variableBindings:List) { if (isBlank(this._records)) { var recordBuilder = new ProtoRecordBuilder(); ListWrapper.forEach(bindingRecords, (r) => { recordBuilder.addAst(r.ast, r.bindingMemento, r.directiveMemento, variableBindings); }); this._records = coalesce(recordBuilder.records); } } } var _jitProtoChangeDetectorClassCounter:number = 0; export class JitProtoChangeDetector extends ProtoChangeDetector { _factory:Function; _pipeRegistry; constructor(pipeRegistry) { super(); this._pipeRegistry = pipeRegistry; this._factory = null; } instantiate(dispatcher:any, bindingRecords:List, variableBindings:List) { this._createFactoryIfNecessary(bindingRecords, variableBindings); return this._factory(dispatcher, this._pipeRegistry); } _createFactoryIfNecessary(bindingRecords:List, variableBindings:List) { if (isBlank(this._factory)) { var recordBuilder = new ProtoRecordBuilder(); ListWrapper.forEach(bindingRecords, (r) => { recordBuilder.addAst(r.ast, r.bindingMemento, r.directiveMemento, variableBindings); }); var c = _jitProtoChangeDetectorClassCounter++; var records = coalesce(recordBuilder.records); var typeName = `ChangeDetector${c}`; this._factory = new ChangeDetectorJITGenerator(typeName, records).generate(); } } } class ProtoRecordBuilder { records:List<ProtoRecord>; constructor() { this.records = []; } addAst(ast:AST, bindingMemento:any, directiveMemento:any = null, variableBindings:List = null) { var last = ListWrapper.last(this.records); if (isPresent(last) && last.directiveMemento == directiveMemento) { last.lastInDirective = false; } var pr = _ConvertAstIntoProtoRecords.convert(ast, bindingMemento, directiveMemento, this.records.length, variableBindings); if (! ListWrapper.isEmpty(pr)) { var last = ListWrapper.last(pr); last.lastInBinding = true; last.lastInDirective = true; this.records = ListWrapper.concat(this.records, pr); } } } class _ConvertAstIntoProtoRecords { protoRecords:List; bindingMemento:any; directiveMemento:any; variableBindings:List; contextIndex:number; expressionAsString:string; constructor(bindingMemento:any, directiveMemento:any, contextIndex:number, expressionAsString:string, variableBindings:List) { this.protoRecords = []; this.bindingMemento = bindingMemento; this.directiveMemento = directiveMemento; this.contextIndex = contextIndex; this.expressionAsString = expressionAsString; this.variableBindings = variableBindings; } static convert(ast:AST, bindingMemento:any, directiveMemento:any, contextIndex:number, variableBindings:List) { var c = new _ConvertAstIntoProtoRecords(bindingMemento, directiveMemento, contextIndex, ast.toString(), variableBindings); ast.visit(c); return c.protoRecords; } visitImplicitReceiver(ast:ImplicitReceiver) { return 0; } visitInterpolation(ast:Interpolation) { var args = this._visitAll(ast.expressions); return this._addRecord(RECORD_TYPE_INTERPOLATE, "interpolate", _interpolationFn(ast.strings), args, ast.strings, 0); } visitLiteralPrimitive(ast:LiteralPrimitive) { return this._addRecord(RECORD_TYPE_CONST, "literal", ast.value, [], null, 0); } visitAccessMember(ast:AccessMember) { var receiver = ast.receiver.visit(this); if (isPresent(this.variableBindings) && ListWrapper.contains(this.variableBindings, ast.name)) { return this._addRecord(RECORD_TYPE_LOCAL, ast.name, ast.name, [], null, receiver); } else { return this._addRecord(RECORD_TYPE_PROPERTY, ast.name, ast.getter, [], null, receiver); } } visitMethodCall(ast:MethodCall) {; var receiver = ast.receiver.visit(this); var args = this._visitAll(ast.args); if (isPresent(this.variableBindings) && ListWrapper.contains(this.variableBindings, ast.name)) { var target = this._addRecord(RECORD_TYPE_LOCAL, ast.name, ast.name, [], null, receiver); return this._addRecord(RECORD_TYPE_INVOKE_CLOSURE, "closure", null, args, null, target); } else { return this._addRecord(RECORD_TYPE_INVOKE_METHOD, ast.name, ast.fn, args, null, receiver); } } visitFunctionCall(ast:FunctionCall) { var target = ast.target.visit(this); var args = this._visitAll(ast.args); return this._addRecord(RECORD_TYPE_INVOKE_CLOSURE, "closure", null, args, null, target); } visitLiteralArray(ast:LiteralArray) { var primitiveName = `arrayFn${ast.expressions.length}`; return this._addRecord(RECORD_TYPE_PRIMITIVE_OP, primitiveName, _arrayFn(ast.expressions.length), this._visitAll(ast.expressions), null, 0); } visitLiteralMap(ast:LiteralMap) { return this._addRecord(RECORD_TYPE_PRIMITIVE_OP, _mapPrimitiveName(ast.keys), ChangeDetectionUtil.mapFn(ast.keys), this._visitAll(ast.values), null, 0); } visitBinary(ast:Binary) { var left = ast.left.visit(this); var right = ast.right.visit(this); return this._addRecord(RECORD_TYPE_PRIMITIVE_OP, _operationToPrimitiveName(ast.operation), _operationToFunction(ast.operation), [left, right], null, 0); } visitPrefixNot(ast:PrefixNot) { var exp = ast.expression.visit(this) return this._addRecord(RECORD_TYPE_PRIMITIVE_OP, "operation_negate", ChangeDetectionUtil.operation_negate, [exp], null, 0); } visitConditional(ast:Conditional) { var c = ast.condition.visit(this); var t = ast.trueExp.visit(this); var f = ast.falseExp.visit(this); return this._addRecord(RECORD_TYPE_PRIMITIVE_OP, "cond", ChangeDetectionUtil.cond, [c,t,f], null, 0); } visitPipe(ast:Pipe) { var value = ast.exp.visit(this); return this._addRecord(RECORD_TYPE_PIPE, ast.name, ast.name, [], null, value); } visitKeyedAccess(ast:KeyedAccess) { var obj = ast.obj.visit(this); var key = ast.key.visit(this); return this._addRecord(RECORD_TYPE_KEYED_ACCESS, "keyedAccess", ChangeDetectionUtil.keyedAccess, [key], null, obj); } _visitAll(asts:List) { var res = ListWrapper.createFixedSize(asts.length); for (var i = 0; i < asts.length; ++i) { res[i] = asts[i].visit(this); } return res; } _addRecord(type, name, funcOrValue, args, fixedArgs, context) { var selfIndex = ++ this.contextIndex; ListWrapper.push(this.protoRecords, new ProtoRecord(type, name, funcOrValue, args, fixedArgs, context, selfIndex, this.bindingMemento, this.directiveMemento, this.expressionAsString, false, false)); return selfIndex; } } function _arrayFn(length:number):Function { switch (length) { case 0: return ChangeDetectionUtil.arrayFn0; case 1: return ChangeDetectionUtil.arrayFn1; case 2: return ChangeDetectionUtil.arrayFn2; case 3: return ChangeDetectionUtil.arrayFn3; case 4: return ChangeDetectionUtil.arrayFn4; case 5: return ChangeDetectionUtil.arrayFn5; case 6: return ChangeDetectionUtil.arrayFn6; case 7: return ChangeDetectionUtil.arrayFn7; case 8: return ChangeDetectionUtil.arrayFn8; case 9: return ChangeDetectionUtil.arrayFn9; default: throw new BaseException(`Does not support literal maps with more than 9 elements`); } } function _mapPrimitiveName(keys:List) { var stringifiedKeys = ListWrapper.join( ListWrapper.map(keys, (k) => isString(k) ? `"${k}"` : `${k}`), ", "); return `mapFn([${stringifiedKeys}])`; } function _operationToPrimitiveName(operation:string):string { switch(operation) { case '+' : return "operation_add"; case '-' : return "operation_subtract"; case '*' : return "operation_multiply"; case '/' : return "operation_divide"; case '%' : return "operation_remainder"; case '==' : return "operation_equals"; case '!=' : return "operation_not_equals"; case '<' : return "operation_less_then"; case '>' : return "operation_greater_then"; case '<=' : return "operation_less_or_equals_then"; case '>=' : return "operation_greater_or_equals_then"; case '&&' : return "operation_logical_and"; case '||' : return "operation_logical_or"; default: throw new BaseException(`Unsupported operation ${operation}`); } } function _operationToFunction(operation:string):Function { switch(operation) { case '+' : return ChangeDetectionUtil.operation_add; case '-' : return ChangeDetectionUtil.operation_subtract; case '*' : return ChangeDetectionUtil.operation_multiply; case '/' : return ChangeDetectionUtil.operation_divide; case '%' : return ChangeDetectionUtil.operation_remainder; case '==' : return ChangeDetectionUtil.operation_equals; case '!=' : return ChangeDetectionUtil.operation_not_equals; case '<' : return ChangeDetectionUtil.operation_less_then; case '>' : return ChangeDetectionUtil.operation_greater_then; case '<=' : return ChangeDetectionUtil.operation_less_or_equals_then; case '>=' : return ChangeDetectionUtil.operation_greater_or_equals_then; case '&&' : return ChangeDetectionUtil.operation_logical_and; case '||' : return ChangeDetectionUtil.operation_logical_or; default: throw new BaseException(`Unsupported operation ${operation}`); } } function s(v) { return isPresent(v) ? `${v}` : ''; } function _interpolationFn(strings:List) { var length = strings.length; var c0 = length > 0 ? strings[0] : null; var c1 = length > 1 ? strings[1] : null; var c2 = length > 2 ? strings[2] : null; var c3 = length > 3 ? strings[3] : null; var c4 = length > 4 ? strings[4] : null; var c5 = length > 5 ? strings[5] : null; var c6 = length > 6 ? strings[6] : null; var c7 = length > 7 ? strings[7] : null; var c8 = length > 8 ? strings[8] : null; var c9 = length > 9 ? strings[9] : null; switch (length - 1) { case 1: return (a1) => c0 + s(a1) + c1; case 2: return (a1, a2) => c0 + s(a1) + c1 + s(a2) + c2; case 3: return (a1, a2, a3) => c0 + s(a1) + c1 + s(a2) + c2 + s(a3) + c3; case 4: return (a1, a2, a3, a4) => c0 + s(a1) + c1 + s(a2) + c2 + s(a3) + c3 + s(a4) + c4; case 5: return (a1, a2, a3, a4, a5) => c0 + s(a1) + c1 + s(a2) + c2 + s(a3) + c3 + s(a4) + c4 + s(a5) + c5; case 6: return (a1, a2, a3, a4, a5, a6) => c0 + s(a1) + c1 + s(a2) + c2 + s(a3) + c3 + s(a4) + c4 + s(a5) + c5 + s(a6) + c6; case 7: return (a1, a2, a3, a4, a5, a6, a7) => c0 + s(a1) + c1 + s(a2) + c2 + s(a3) + c3 + s(a4) + c4 + s(a5) + c5 + s(a6) + c6 + s(a7) + c7; case 8: return (a1, a2, a3, a4, a5, a6, a7, a8) => c0 + s(a1) + c1 + s(a2) + c2 + s(a3) + c3 + s(a4) + c4 + s(a5) + c5 + s(a6) + c6 + s(a7) + c7 + s(a8) + c8; case 9: return (a1, a2, a3, a4, a5, a6, a7, a8, a9) => c0 + s(a1) + c1 + s(a2) + c2 + s(a3) + c3 + s(a4) + c4 + s(a5) + c5 + s(a6) + c6 + s(a7) + c7 + s(a8) + c8 + s(a9) + c9; default: throw new BaseException(`Does not support more than 9 expressions`); } }
modules/angular2/src/change_detection/proto_change_detector.js
0
https://github.com/angular/angular/commit/e0710c4613ba51f008bc8a2f4874fb1fade9d09f
[ 0.0024519816506654024, 0.0004589568416122347, 0.00016220888937823474, 0.00017269165255129337, 0.0005742143257521093 ]
{ "id": 3, "code_window": [ " expect(MapWrapper.get(results[0].variableBindings, '\\$implicit')).toEqual('george');\n", " });\n", "\n", " it('should detect () syntax', () => {\n", " var results = createPipeline().process(el('<div (click)=\"b()\"></div>'));\n", " expect(MapWrapper.get(results[0].eventBindings, 'click').source).toEqual('b()');\n", " // \"(click[])\" is not an expected syntax and is only used to validate the regexp\n", " results = createPipeline().process(el('<div (click[])=\"b()\"></div>'));\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " it('should detect variable bindings only if an attribute name starts with #', () => {\n", " var results = createPipeline().process(el('<p b#george></p>'));\n", " expect(results[0].variableBindings).toBe(null);\n", " });\n", "\n" ], "file_path": "modules/angular2/test/core/compiler/pipeline/property_binding_parser_spec.js", "type": "add", "edit_start_line_idx": 64 }
import { bind } from 'angular2/di'; import { Promise, PromiseWrapper } from 'angular2/src/facade/async'; import { ABSTRACT, BaseException } from 'angular2/src/facade/lang'; import { MeasureValues } from './measure_values'; /** * A reporter reports measure values and the valid sample. */ @ABSTRACT() export class Reporter { static bindTo(delegateToken) { return [ bind(Reporter).toFactory( (delegate) => delegate, [delegateToken] ) ]; } reportMeasureValues(values:MeasureValues):Promise { throw new BaseException('NYI'); } reportSample(completeSample:List<MeasureValues>, validSample:List<MeasureValues>):Promise { throw new BaseException('NYI'); } }
modules/benchpress/src/reporter.js
0
https://github.com/angular/angular/commit/e0710c4613ba51f008bc8a2f4874fb1fade9d09f
[ 0.00017656254931353033, 0.00017192662926390767, 0.00016717115067876875, 0.00017198642308358103, 0.000003327376134620863 ]
{ "id": 3, "code_window": [ " expect(MapWrapper.get(results[0].variableBindings, '\\$implicit')).toEqual('george');\n", " });\n", "\n", " it('should detect () syntax', () => {\n", " var results = createPipeline().process(el('<div (click)=\"b()\"></div>'));\n", " expect(MapWrapper.get(results[0].eventBindings, 'click').source).toEqual('b()');\n", " // \"(click[])\" is not an expected syntax and is only used to validate the regexp\n", " results = createPipeline().process(el('<div (click[])=\"b()\"></div>'));\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " it('should detect variable bindings only if an attribute name starts with #', () => {\n", " var results = createPipeline().process(el('<p b#george></p>'));\n", " expect(results[0].variableBindings).toBe(null);\n", " });\n", "\n" ], "file_path": "modules/angular2/test/core/compiler/pipeline/property_binding_parser_spec.js", "type": "add", "edit_start_line_idx": 64 }
import {int, StringWrapper} from 'angular2/src/facade/lang'; import {List, ListWrapper} from 'angular2/src/facade/collection'; import {CustomDate, Offering, Company, Opportunity, Account, STATUS_LIST, AAT_STATUS_LIST} from './common'; export function generateOfferings(count:int):List<Offering> { var res = []; for(var i = 0; i < count; i++) { ListWrapper.push(res, generateOffering(i)); } return res; } export function generateOffering(seed:int):Offering { var res = new Offering(); res.name = generateName(seed++); res.company = generateCompany(seed++); res.opportunity = generateOpportunity(seed++); res.account = generateAccount(seed++); res.basePoints = seed % 10; res.kickerPoints = seed % 4; res.status = STATUS_LIST[seed % STATUS_LIST.length]; res.bundles = randomString(seed++); res.dueDate = randomDate(seed++); res.endDate = randomDate(seed++, res.dueDate); res.aatStatus = AAT_STATUS_LIST[seed % AAT_STATUS_LIST.length]; return res; } export function generateCompany(seed:int):Company { var res = new Company(); res.name = generateName(seed); return res; } export function generateOpportunity(seed:int):Opportunity { var res = new Opportunity(); res.name = generateName(seed); return res; } export function generateAccount(seed:int):Account { var res = new Account(); res.accountId = seed; return res; } var names = [ 'Foo', 'Bar', 'Baz', 'Qux', 'Quux', 'Garply', 'Waldo', 'Fred', 'Plugh', 'Xyzzy', 'Thud', 'Cruft', 'Stuff' ]; function generateName(seed:int):string { return names[seed % names.length]; } var offsets = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; function randomDate(seed:int, minDate:CustomDate = null):CustomDate { if (minDate == null) { minDate = CustomDate.now(); } return minDate.addDays(offsets[seed % offsets.length]); } var stringLengths = [5, 7, 9, 11, 13]; var charCodeOffsets = [0, 1, 2, 3, 4, 5, 6, 7, 8]; function randomString(seed:int):string { var len = stringLengths[seed % 5]; var str = ''; for (var i = 0; i < len; i++) { str += StringWrapper.fromCharCode(97 + charCodeOffsets[seed % 9] + i); } return str; }
modules/benchmarks/src/naive_infinite_scroll/random_data.js
0
https://github.com/angular/angular/commit/e0710c4613ba51f008bc8a2f4874fb1fade9d09f
[ 0.00017722338088788092, 0.00017267603834625334, 0.00016777028213255107, 0.0001725804468151182, 0.000002598338596726535 ]
{ "id": 4, "code_window": [ " results = createPipeline().process(el('<div (click[])=\"b()\"></div>'));\n", " expect(MapWrapper.get(results[0].eventBindings, 'click[]').source).toEqual('b()');\n", " });\n", "\n", " it('should parse event handlers using () syntax as actions', () => {\n", " var results = createPipeline().process(el('<div (click)=\"foo=bar\"></div>'));\n", " expect(MapWrapper.get(results[0].eventBindings, 'click').source).toEqual('foo=bar');\n", " });\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " it('should detect () syntax only if an attribute name starts and ends with ()', () => {\n", " expect(createPipeline().process(el('<div z(a)=\"b()\"></div>'))[0].propertyBindings).toBe(null);\n", " expect(createPipeline().process(el('<div (a)v=\"b()\"></div>'))[0].propertyBindings).toBe(null);\n", " });\n", "\n" ], "file_path": "modules/angular2/test/core/compiler/pipeline/property_binding_parser_spec.js", "type": "add", "edit_start_line_idx": 72 }
import {describe, beforeEach, it, expect, iit, ddescribe, el} from 'angular2/test_lib'; import {PropertyBindingParser} from 'angular2/src/core/compiler/pipeline/property_binding_parser'; import {CompilePipeline} from 'angular2/src/core/compiler/pipeline/compile_pipeline'; import {MapWrapper} from 'angular2/src/facade/collection'; import {CompileElement} from 'angular2/src/core/compiler/pipeline/compile_element'; import {CompileStep} from 'angular2/src/core/compiler/pipeline/compile_step' import {CompileControl} from 'angular2/src/core/compiler/pipeline/compile_control'; import {Lexer, Parser} from 'angular2/change_detection'; export function main() { describe('PropertyBindingParser', () => { function createPipeline(ignoreBindings = false) { return new CompilePipeline([ new MockStep((parent, current, control) => { current.ignoreBindings = ignoreBindings; }), new PropertyBindingParser(new Parser(new Lexer()))]); } it('should not parse bindings when ignoreBindings is true', () => { var results = createPipeline(true).process(el('<div [a]="b"></div>')); expect(results[0].propertyBindings).toBe(null); }); it('should detect [] syntax', () => { var results = createPipeline().process(el('<div [a]="b"></div>')); expect(MapWrapper.get(results[0].propertyBindings, 'a').source).toEqual('b'); }); it('should detect bind- syntax', () => { var results = createPipeline().process(el('<div bind-a="b"></div>')); expect(MapWrapper.get(results[0].propertyBindings, 'a').source).toEqual('b'); }); it('should detect interpolation syntax', () => { // Note: we don't test all corner cases of interpolation as we assume shared functionality between text interpolation // and attribute interpolation. var results = createPipeline().process(el('<div a="{{b}}"></div>')); expect(MapWrapper.get(results[0].propertyBindings, 'a').source).toEqual('{{b}}'); }); it('should detect var- syntax', () => { var results = createPipeline().process(el('<template var-a="b"></template>')); expect(MapWrapper.get(results[0].variableBindings, 'b')).toEqual('a'); }); it('should store variable binding for a non-template element', () => { var results = createPipeline().process(el('<p var-george="washington"></p>')); expect(MapWrapper.get(results[0].variableBindings, 'washington')).toEqual('george'); }); it('should store variable binding for a non-template element using shorthand syntax', () => { var results = createPipeline().process(el('<p #george="washington"></p>')); expect(MapWrapper.get(results[0].variableBindings, 'washington')).toEqual('george'); }); it('should store a variable binding with an implicit value', () => { var results = createPipeline().process(el('<p var-george></p>')); expect(MapWrapper.get(results[0].variableBindings, '\$implicit')).toEqual('george'); }); it('should store a variable binding with an implicit value using shorthand syntax', () => { var results = createPipeline().process(el('<p #george></p>')); expect(MapWrapper.get(results[0].variableBindings, '\$implicit')).toEqual('george'); }); it('should detect () syntax', () => { var results = createPipeline().process(el('<div (click)="b()"></div>')); expect(MapWrapper.get(results[0].eventBindings, 'click').source).toEqual('b()'); // "(click[])" is not an expected syntax and is only used to validate the regexp results = createPipeline().process(el('<div (click[])="b()"></div>')); expect(MapWrapper.get(results[0].eventBindings, 'click[]').source).toEqual('b()'); }); it('should parse event handlers using () syntax as actions', () => { var results = createPipeline().process(el('<div (click)="foo=bar"></div>')); expect(MapWrapper.get(results[0].eventBindings, 'click').source).toEqual('foo=bar'); }); it('should detect on- syntax', () => { var results = createPipeline().process(el('<div on-click="b()"></div>')); expect(MapWrapper.get(results[0].eventBindings, 'click').source).toEqual('b()'); }); it('should parse event handlers using on- syntax as actions', () => { var results = createPipeline().process(el('<div on-click="foo=bar"></div>')); expect(MapWrapper.get(results[0].eventBindings, 'click').source).toEqual('foo=bar'); }); }); } class MockStep extends CompileStep { processClosure:Function; constructor(process) { super(); this.processClosure = process; } process(parent:CompileElement, current:CompileElement, control:CompileControl) { this.processClosure(parent, current, control); } }
modules/angular2/test/core/compiler/pipeline/property_binding_parser_spec.js
1
https://github.com/angular/angular/commit/e0710c4613ba51f008bc8a2f4874fb1fade9d09f
[ 0.9963995218276978, 0.2768361270427704, 0.00015957409050315619, 0.010141503065824509, 0.4191340208053589 ]
{ "id": 4, "code_window": [ " results = createPipeline().process(el('<div (click[])=\"b()\"></div>'));\n", " expect(MapWrapper.get(results[0].eventBindings, 'click[]').source).toEqual('b()');\n", " });\n", "\n", " it('should parse event handlers using () syntax as actions', () => {\n", " var results = createPipeline().process(el('<div (click)=\"foo=bar\"></div>'));\n", " expect(MapWrapper.get(results[0].eventBindings, 'click').source).toEqual('foo=bar');\n", " });\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " it('should detect () syntax only if an attribute name starts and ends with ()', () => {\n", " expect(createPipeline().process(el('<div z(a)=\"b()\"></div>'))[0].propertyBindings).toBe(null);\n", " expect(createPipeline().process(el('<div (a)v=\"b()\"></div>'))[0].propertyBindings).toBe(null);\n", " });\n", "\n" ], "file_path": "modules/angular2/test/core/compiler/pipeline/property_binding_parser_spec.js", "type": "add", "edit_start_line_idx": 72 }
var mockPackage = require('../mocks/mockPackage'); var Dgeni = require('dgeni'); describe('atParser service', function() { var dgeni, injector, parser; var fileContent = 'import {CONST} from "facade/lang";\n' + '\n' + '/**\n' + '* A parameter annotation that creates a synchronous eager dependency.\n' + '*\n' + '* class AComponent {\n' + '* constructor(@Inject("aServiceToken") aService) {}\n' + '* }\n' + '*\n' + '*/\n' + 'export class Inject {\n' + 'token;\n' + '@CONST()\n' + 'constructor({a,b}:{a:string, b:string}) {\n' + 'this.token = a;\n' + '}\n' + '}'; beforeEach(function() { dgeni = new Dgeni([mockPackage()]); injector = dgeni.configureInjector(); parser = injector.get('atParser'); }); it('should extract the comments from the file', function() { var result = parser.parseModule({ content: fileContent, relativePath: 'di/src/annotations.js' }); expect(result.comments[0].range.toString()).toEqual( '/**\n' + '* A parameter annotation that creates a synchronous eager dependency.\n' + '*\n' + '* class AComponent {\n' + '* constructor(@Inject("aServiceToken") aService) {}\n' + '* }\n' + '*\n' + '*/' ); }); it('should extract a module AST from the file', function() { var result = parser.parseModule({ content: fileContent, relativePath: 'di/src/annotations.js' }); expect(result.moduleTree.moduleName).toEqual('di/src/annotations'); expect(result.moduleTree.scriptItemList[0].type).toEqual('IMPORT_DECLARATION'); expect(result.moduleTree.scriptItemList[1].type).toEqual('EXPORT_DECLARATION'); }); it('should attach comments to their following AST', function() { var result = parser.parseModule({ content: fileContent, relativePath: 'di/src/annotations.js' }); expect(result.moduleTree.scriptItemList[1].commentBefore.range.toString()).toEqual( '/**\n' + '* A parameter annotation that creates a synchronous eager dependency.\n' + '*\n' + '* class AComponent {\n' + '* constructor(@Inject("aServiceToken") aService) {}\n' + '* }\n' + '*\n' + '*/' ); }); });
docs/dgeni-package/services/atParser.spec.js
0
https://github.com/angular/angular/commit/e0710c4613ba51f008bc8a2f4874fb1fade9d09f
[ 0.0001743515458656475, 0.0001706900802673772, 0.0001644797157496214, 0.0001722073066048324, 0.0000032722678042773623 ]
{ "id": 4, "code_window": [ " results = createPipeline().process(el('<div (click[])=\"b()\"></div>'));\n", " expect(MapWrapper.get(results[0].eventBindings, 'click[]').source).toEqual('b()');\n", " });\n", "\n", " it('should parse event handlers using () syntax as actions', () => {\n", " var results = createPipeline().process(el('<div (click)=\"foo=bar\"></div>'));\n", " expect(MapWrapper.get(results[0].eventBindings, 'click').source).toEqual('foo=bar');\n", " });\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " it('should detect () syntax only if an attribute name starts and ends with ()', () => {\n", " expect(createPipeline().process(el('<div z(a)=\"b()\"></div>'))[0].propertyBindings).toBe(null);\n", " expect(createPipeline().process(el('<div (a)v=\"b()\"></div>'))[0].propertyBindings).toBe(null);\n", " });\n", "\n" ], "file_path": "modules/angular2/test/core/compiler/pipeline/property_binding_parser_spec.js", "type": "add", "edit_start_line_idx": 72 }
library angular2.src.transform.common.options; const ENTRY_POINT_PARAM = 'entry_point'; const REFLECTION_ENTRY_POINT_PARAM = 'reflection_entry_point'; /// Provides information necessary to transform an Angular2 app. class TransformerOptions { /// The path to the file where the application's call to [bootstrap] is. // TODO(kegluneq): Allow multiple entry points. final String entryPoint; /// The reflection entry point, that is, the path to the file where the /// application's [ReflectionCapabilities] are set. final String reflectionEntryPoint; TransformerOptions._internal(this.entryPoint, this.reflectionEntryPoint); factory TransformerOptions(String entryPoint, {String reflectionEntryPoint}) { if (entryPoint == null) { throw new ArgumentError.notNull(ENTRY_POINT_PARAM); } else if (entryPoint.isEmpty) { throw new ArgumentError.value(entryPoint, 'entryPoint'); } if (reflectionEntryPoint == null || entryPoint.isEmpty) { reflectionEntryPoint = entryPoint; } return new TransformerOptions._internal(entryPoint, reflectionEntryPoint); } }
modules/angular2/src/transform/common/options.dart
0
https://github.com/angular/angular/commit/e0710c4613ba51f008bc8a2f4874fb1fade9d09f
[ 0.00017555415979586542, 0.0001718372805044055, 0.00016560364747419953, 0.00017435403424315155, 0.000004434990387380822 ]
{ "id": 4, "code_window": [ " results = createPipeline().process(el('<div (click[])=\"b()\"></div>'));\n", " expect(MapWrapper.get(results[0].eventBindings, 'click[]').source).toEqual('b()');\n", " });\n", "\n", " it('should parse event handlers using () syntax as actions', () => {\n", " var results = createPipeline().process(el('<div (click)=\"foo=bar\"></div>'));\n", " expect(MapWrapper.get(results[0].eventBindings, 'click').source).toEqual('foo=bar');\n", " });\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " it('should detect () syntax only if an attribute name starts and ends with ()', () => {\n", " expect(createPipeline().process(el('<div z(a)=\"b()\"></div>'))[0].propertyBindings).toBe(null);\n", " expect(createPipeline().process(el('<div (a)v=\"b()\"></div>'))[0].propertyBindings).toBe(null);\n", " });\n", "\n" ], "file_path": "modules/angular2/test/core/compiler/pipeline/property_binding_parser_spec.js", "type": "add", "edit_start_line_idx": 72 }
<!doctype html> <html> <body> <h2>Params</h2> <form> Elements: <input type="number" name="elements" placeholder="elements" value="150"> <br> <button>Apply</button> </form> <h2>Actions</h2> <p> <button id="compileWithBindings">CompileWithBindings</button> <button id="compileNoBindings">CompileNoBindings</button> </p> <template id="templateNoBindings"> <div class="class0 class1 class2 class3 class4 " nodir0="" attr0="value0" nodir1="" attr1="value1" nodir2="" attr2="value2" nodir3="" attr3="value3" nodir4="" attr4="value4"> <div class="class0 class1 class2 class3 class4 " nodir0="" attr0="value0" nodir1="" attr1="value1" nodir2="" attr2="value2" nodir3="" attr3="value3" nodir4="" attr4="value4"> <div class="class0 class1 class2 class3 class4 " nodir0="" attr0="value0" nodir1="" attr1="value1" nodir2="" attr2="value2" nodir3="" attr3="value3" nodir4="" attr4="value4"> <div class="class0 class1 class2 class3 class4 " nodir0="" attr0="value0" nodir1="" attr1="value1" nodir2="" attr2="value2" nodir3="" attr3="value3" nodir4="" attr4="value4"> <div class="class0 class1 class2 class3 class4 " nodir0="" attr0="value0" nodir1="" attr1="value1" nodir2="" attr2="value2" nodir3="" attr3="value3" nodir4="" attr4="value4"> </div> </div> </div> </div> </div> </template> <template id="templateWithBindings"> <div class="class0 class1 class2 class3 class4 " dir0="" [attr0]="value0" dir1="" [attr1]="value1" dir2="" [attr2]="value2" dir3="" [attr3]="value3" dir4="" [attr4]="value4"> {{inter0}}{{inter1}}{{inter2}}{{inter3}}{{inter4}} <div class="class0 class1 class2 class3 class4 " dir0="" [attr0]="value0" dir1="" [attr1]="value1" dir2="" [attr2]="value2" dir3="" [attr3]="value3" dir4="" [attr4]="value4"> {{inter0}}{{inter1}}{{inter2}}{{inter3}}{{inter4}} <div class="class0 class1 class2 class3 class4 " dir0="" [attr0]="value0" dir1="" [attr1]="value1" dir2="" [attr2]="value2" dir3="" [attr3]="value3" dir4="" [attr4]="value4"> {{inter0}}{{inter1}}{{inter2}}{{inter3}}{{inter4}} <div class="class0 class1 class2 class3 class4 " dir0="" [attr0]="value0" dir1="" [attr1]="value1" dir2="" [attr2]="value2" dir3="" [attr3]="value3" dir4="" [attr4]="value4"> {{inter0}}{{inter1}}{{inter2}}{{inter3}}{{inter4}} <div class="class0 class1 class2 class3 class4 " dir0="" [attr0]="value0" dir1="" [attr1]="value1" dir2="" [attr2]="value2" dir3="" [attr3]="value3" dir4="" [attr4]="value4"> {{inter0}}{{inter1}}{{inter2}}{{inter3}}{{inter4}} </div> </div> </div> </div> </div> </template> $SCRIPTS$ </body> </html>
modules/benchmarks_external/src/compiler/compiler_benchmark.html
0
https://github.com/angular/angular/commit/e0710c4613ba51f008bc8a2f4874fb1fade9d09f
[ 0.0011470627505332232, 0.0003322489792481065, 0.00016640967805869877, 0.0001690891367616132, 0.00036440216354094446 ]
{ "id": 0, "code_window": [ " * Licensed under the MIT License. See License.txt in the project root for license information.\n", " *--------------------------------------------------------------------------------------------*/\n", "'use strict';\n", "\n", "import {IThreadService} from 'vs/workbench/services/thread/common/threadService';\n", "import {IMarkerData} from 'vs/platform/markers/common/markers';\n", "import URI from 'vs/base/common/uri';\n", "import Severity from 'vs/base/common/severity';\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "import {localize} from 'vs/nls';\n" ], "file_path": "src/vs/workbench/api/node/extHostDiagnostics.ts", "type": "add", "edit_start_line_idx": 6 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as assert from 'assert'; import URI from 'vs/base/common/uri'; import Severity from 'vs/base/common/severity'; import {DiagnosticCollection} from 'vs/workbench/api/node/extHostDiagnostics'; import {Diagnostic, DiagnosticSeverity, Range} from 'vs/workbench/api/node/extHostTypes'; import {MainThreadDiagnosticsShape} from 'vs/workbench/api/node/extHost.protocol'; import {TPromise} from 'vs/base/common/winjs.base'; import {IMarkerData} from 'vs/platform/markers/common/markers'; suite('ExtHostDiagnostics', () => { class DiagnosticsShape extends MainThreadDiagnosticsShape { $changeMany(owner: string, entries: [URI, IMarkerData[]][]): TPromise<any> { return TPromise.as(null); } $clear(owner: string): TPromise<any> { return TPromise.as(null); } }; test('disposeCheck', function () { const collection = new DiagnosticCollection('test', new DiagnosticsShape()); collection.dispose(); collection.dispose(); // that's OK assert.throws(() => collection.name); assert.throws(() => collection.clear()); assert.throws(() => collection.delete(URI.parse('aa:bb'))); assert.throws(() => collection.forEach(() => { ; })); assert.throws(() => collection.get(URI.parse('aa:bb'))); assert.throws(() => collection.has(URI.parse('aa:bb'))); assert.throws(() => collection.set(URI.parse('aa:bb'), [])); assert.throws(() => collection.set(URI.parse('aa:bb'), undefined)); }); test('diagnostic collection, forEach, clear, has', function () { let collection = new DiagnosticCollection('test', new DiagnosticsShape()); assert.equal(collection.name, 'test'); collection.dispose(); assert.throws(() => collection.name); let c = 0; collection = new DiagnosticCollection('test', new DiagnosticsShape()); collection.forEach(() => c++); assert.equal(c, 0); collection.set(URI.parse('foo:bar'), [ new Diagnostic(new Range(0, 0, 1, 1), 'message-1'), new Diagnostic(new Range(0, 0, 1, 1), 'message-2') ]); collection.forEach(() => c++); assert.equal(c, 1); c = 0; collection.clear(); collection.forEach(() => c++); assert.equal(c, 0); collection.set(URI.parse('foo:bar1'), [ new Diagnostic(new Range(0, 0, 1, 1), 'message-1'), new Diagnostic(new Range(0, 0, 1, 1), 'message-2') ]); collection.set(URI.parse('foo:bar2'), [ new Diagnostic(new Range(0, 0, 1, 1), 'message-1'), new Diagnostic(new Range(0, 0, 1, 1), 'message-2') ]); collection.forEach(() => c++); assert.equal(c, 2); assert.ok(collection.has(URI.parse('foo:bar1'))); assert.ok(collection.has(URI.parse('foo:bar2'))); assert.ok(!collection.has(URI.parse('foo:bar3'))); collection.delete(URI.parse('foo:bar1')); assert.ok(!collection.has(URI.parse('foo:bar1'))); collection.dispose(); }); test('diagnostic collection, immutable read', function () { let collection = new DiagnosticCollection('test', new DiagnosticsShape()); collection.set(URI.parse('foo:bar'), [ new Diagnostic(new Range(0, 0, 1, 1), 'message-1'), new Diagnostic(new Range(0, 0, 1, 1), 'message-2') ]); let array = collection.get(URI.parse('foo:bar')); assert.throws(() => array.length = 0); assert.throws(() => array.pop()); assert.throws(() => array[0] = new Diagnostic(new Range(0, 0, 0, 0), 'evil')); collection.forEach((uri, array) => { assert.throws(() => array.length = 0); assert.throws(() => array.pop()); assert.throws(() => array[0] = new Diagnostic(new Range(0, 0, 0, 0), 'evil')); }); array = collection.get(URI.parse('foo:bar')); assert.equal(array.length, 2); collection.dispose(); }); test('diagnostics collection, set with dupliclated tuples', function () { let collection = new DiagnosticCollection('test', new DiagnosticsShape()); let uri = URI.parse('sc:hightower'); collection.set([ [uri, [new Diagnostic(new Range(0, 0, 0, 1), 'message-1')]], [URI.parse('some:thing'), [new Diagnostic(new Range(0, 0, 1, 1), 'something')]], [uri, [new Diagnostic(new Range(0, 0, 0, 1), 'message-2')]], ]); let array = collection.get(uri); assert.equal(array.length, 2); let [first, second] = array; assert.equal(first.message, 'message-1'); assert.equal(second.message, 'message-2'); // clear collection.delete(uri); assert.ok(!collection.has(uri)); // bad tuple clears 1/2 collection.set([ [uri, [new Diagnostic(new Range(0, 0, 0, 1), 'message-1')]], [URI.parse('some:thing'), [new Diagnostic(new Range(0, 0, 1, 1), 'something')]], [uri, undefined] ]); assert.ok(!collection.has(uri)); // clear collection.delete(uri); assert.ok(!collection.has(uri)); // bad tuple clears 2/2 collection.set([ [uri, [new Diagnostic(new Range(0, 0, 0, 1), 'message-1')]], [URI.parse('some:thing'), [new Diagnostic(new Range(0, 0, 1, 1), 'something')]], [uri, undefined], [uri, [new Diagnostic(new Range(0, 0, 0, 1), 'message-2')]], [uri, [new Diagnostic(new Range(0, 0, 0, 1), 'message-3')]], ]); array = collection.get(uri); assert.equal(array.length, 2); [first, second] = array; assert.equal(first.message, 'message-2'); assert.equal(second.message, 'message-3'); collection.dispose(); }); test('diagnostic capping', function () { let lastEntries: [URI, IMarkerData[]][]; let collection = new DiagnosticCollection('test', new class extends DiagnosticsShape { $changeMany(owner: string, entries: [URI, IMarkerData[]][]): TPromise<any> { lastEntries = entries; return super.$changeMany(owner, entries); } }); let uri = URI.parse('aa:bb'); let diagnostics: Diagnostic[] = []; for (let i = 0; i < 500; i++) { diagnostics.push(new Diagnostic(new Range(i, 0, i + 1, 0), `error#${i}`, i < 300 ? DiagnosticSeverity.Warning : DiagnosticSeverity.Error)); } collection.set(uri, diagnostics); assert.equal(collection.get(uri).length, 500); assert.equal(lastEntries.length, 1); assert.equal(lastEntries[0][1].length, 250); assert.equal(lastEntries[0][1][0].severity, Severity.Error); assert.equal(lastEntries[0][1][200].severity, Severity.Warning); }); });
src/vs/workbench/test/node/api/extHostDiagnostics.test.ts
1
https://github.com/microsoft/vscode/commit/fe8bb5b4849061ed88b97dcf76e09ebcce3a6d82
[ 0.00019114003225695342, 0.00017465428391005844, 0.00016375268751289696, 0.00017563266737852246, 0.000005580834113061428 ]
{ "id": 0, "code_window": [ " * Licensed under the MIT License. See License.txt in the project root for license information.\n", " *--------------------------------------------------------------------------------------------*/\n", "'use strict';\n", "\n", "import {IThreadService} from 'vs/workbench/services/thread/common/threadService';\n", "import {IMarkerData} from 'vs/platform/markers/common/markers';\n", "import URI from 'vs/base/common/uri';\n", "import Severity from 'vs/base/common/severity';\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "import {localize} from 'vs/nls';\n" ], "file_path": "src/vs/workbench/api/node/extHostDiagnostics.ts", "type": "add", "edit_start_line_idx": 6 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "editorCommands": "편집기 명령", "entryAriaLabel": "{0}, 선택기 도움말", "globalCommands": "전역 명령" }
i18n/kor/src/vs/workbench/parts/quickopen/browser/helpHandler.i18n.json
0
https://github.com/microsoft/vscode/commit/fe8bb5b4849061ed88b97dcf76e09ebcce3a6d82
[ 0.0001761725579854101, 0.00017149175982922316, 0.00016681097622495145, 0.00017149175982922316, 0.000004680790880229324 ]
{ "id": 0, "code_window": [ " * Licensed under the MIT License. See License.txt in the project root for license information.\n", " *--------------------------------------------------------------------------------------------*/\n", "'use strict';\n", "\n", "import {IThreadService} from 'vs/workbench/services/thread/common/threadService';\n", "import {IMarkerData} from 'vs/platform/markers/common/markers';\n", "import URI from 'vs/base/common/uri';\n", "import Severity from 'vs/base/common/severity';\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "import {localize} from 'vs/nls';\n" ], "file_path": "src/vs/workbench/api/node/extHostDiagnostics.ts", "type": "add", "edit_start_line_idx": 6 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "disabled": "在设置中禁用 GIT。" }
i18n/chs/src/vs/workbench/parts/git/browser/views/disabled/disabledView.i18n.json
0
https://github.com/microsoft/vscode/commit/fe8bb5b4849061ed88b97dcf76e09ebcce3a6d82
[ 0.00016786147898528725, 0.00016786147898528725, 0.00016786147898528725, 0.00016786147898528725, 0 ]
{ "id": 0, "code_window": [ " * Licensed under the MIT License. See License.txt in the project root for license information.\n", " *--------------------------------------------------------------------------------------------*/\n", "'use strict';\n", "\n", "import {IThreadService} from 'vs/workbench/services/thread/common/threadService';\n", "import {IMarkerData} from 'vs/platform/markers/common/markers';\n", "import URI from 'vs/base/common/uri';\n", "import Severity from 'vs/base/common/severity';\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "import {localize} from 'vs/nls';\n" ], "file_path": "src/vs/workbench/api/node/extHostDiagnostics.ts", "type": "add", "edit_start_line_idx": 6 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "activateBreakpoints": "ブレークポイントのアクティブ化", "addConditionalBreakpoint": "条件付きブレークポイントの追加", "addFunctionBreakpoint": "関数ブレークポイントの追加", "addToWatchExpressions": "ウォッチに追加", "addWatchExpression": "式の追加", "clearRepl": "コンソールのクリア", "continueDebug": "続行", "copy": "コピー", "copyValue": "値のコピー", "deactivateBreakpoints": "ブレークポイントの非アクティブ化", "debugActionLabelAndKeybinding": "{0} ({1})", "debugConsoleAction": "デバッグ コンソール", "disableAllBreakpoints": "すべてのブレークポイントを無効にする", "disconnectDebug": "切断", "editConditionalBreakpoint": "ブレークポイントの編集", "enableAllBreakpoints": "すべてのブレークポイントを有効にする", "openLaunchJson": "{0} を開く", "pauseDebug": "一時停止", "reapplyAllBreakpoints": "すべてのブレークポイントを再適用する", "reconnectDebug": "再接続", "removeAllBreakpoints": "すべてのブレークポイントを削除する", "removeAllWatchExpressions": "すべての式を削除する", "removeBreakpoint": "ブレークポイントの削除", "removeWatchExpression": "式の削除", "renameFunctionBreakpoint": "関数ブレークポイントの名前変更", "renameWatchExpression": "式の名前変更", "restartDebug": "再起動", "selectConfig": "構成の選択", "startDebug": "デバッグの開始", "startWithoutDebugging": "デバッグなしで開始", "stepIntoDebug": "ステップ インする", "stepOutDebug": "ステップ アウト", "stepOverDebug": "ステップ オーバー", "stopDebug": "停止", "toggleEnablement": "ブレークポイントの有効化/無効化" }
i18n/jpn/src/vs/workbench/parts/debug/electron-browser/debugActions.i18n.json
0
https://github.com/microsoft/vscode/commit/fe8bb5b4849061ed88b97dcf76e09ebcce3a6d82
[ 0.00017408194253221154, 0.0001708578784018755, 0.0001672607468208298, 0.00017092280904762447, 0.0000022225499378691893 ]
{ "id": 1, "code_window": [ "import {IMarkerData} from 'vs/platform/markers/common/markers';\n", "import URI from 'vs/base/common/uri';\n", "import Severity from 'vs/base/common/severity';\n", "import * as vscode from 'vscode';\n", "import {MainContext, MainThreadDiagnosticsShape, ExtHostDiagnosticsShape} from './extHost.protocol';\n", "import {Diagnostic} from './extHostTypes';\n", "\n", "export class DiagnosticCollection implements vscode.DiagnosticCollection {\n", "\n", "\tprivate static _maxDiagnosticsPerFile: number = 250;\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import {DiagnosticSeverity} from './extHostTypes';\n" ], "file_path": "src/vs/workbench/api/node/extHostDiagnostics.ts", "type": "replace", "edit_start_line_idx": 12 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import {IThreadService} from 'vs/workbench/services/thread/common/threadService'; import {IMarkerData} from 'vs/platform/markers/common/markers'; import URI from 'vs/base/common/uri'; import Severity from 'vs/base/common/severity'; import * as vscode from 'vscode'; import {MainContext, MainThreadDiagnosticsShape, ExtHostDiagnosticsShape} from './extHost.protocol'; import {Diagnostic} from './extHostTypes'; export class DiagnosticCollection implements vscode.DiagnosticCollection { private static _maxDiagnosticsPerFile: number = 250; private _name: string; private _proxy: MainThreadDiagnosticsShape; private _isDisposed = false; private _data: {[uri:string]: vscode.Diagnostic[]} = Object.create(null); constructor(name: string, proxy: MainThreadDiagnosticsShape) { this._name = name; this._proxy = proxy; } dispose(): void { if (!this._isDisposed) { this._proxy.$clear(this.name); this._proxy = undefined; this._data = undefined; this._isDisposed = true; } } get name(): string { this._checkDisposed(); return this._name; } set(uri: vscode.Uri, diagnostics: vscode.Diagnostic[]): void; set(entries: [vscode.Uri, vscode.Diagnostic[]][]): void; set(first: vscode.Uri | [vscode.Uri, vscode.Diagnostic[]][], diagnostics?: vscode.Diagnostic[]) { if (!first) { // this set-call is a clear-call this.clear(); return; } // the actual implementation for #set this._checkDisposed(); let toSync: vscode.Uri[]; if (first instanceof URI) { if (!diagnostics) { // remove this entry this.delete(first); return; } // update single row this._data[first.toString()] = diagnostics; toSync = [first]; } else if (Array.isArray(first)) { // update many rows toSync = []; for (let entry of first) { let [uri, diagnostics] = entry; toSync.push(uri); if (!diagnostics) { // [Uri, undefined] means clear this delete this._data[uri.toString()]; } else { // set or merge diagnostics let existing = this._data[uri.toString()]; if (existing) { existing.push(...diagnostics); } else { this._data[uri.toString()] = diagnostics; } } } } // compute change and send to main side const entries: [URI, IMarkerData[]][] = []; for (let uri of toSync) { let marker: IMarkerData[]; let diagnostics = this._data[uri.toString()]; if (diagnostics) { // no more than 250 diagnostics per file if (diagnostics.length > DiagnosticCollection._maxDiagnosticsPerFile) { console.warn('diagnostics for %s will be capped to %d (actually is %d)', uri.toString(), DiagnosticCollection._maxDiagnosticsPerFile, diagnostics.length); marker = []; const sorted = diagnostics.slice(0).sort(Diagnostic.compare); for (let i = 0; i < DiagnosticCollection._maxDiagnosticsPerFile; i++) { marker.push(DiagnosticCollection._toMarkerData(sorted[i])); } } else { marker = diagnostics.map(DiagnosticCollection._toMarkerData); } } entries.push([<URI> uri, marker]); } this._proxy.$changeMany(this.name, entries); } delete(uri: vscode.Uri): void { this._checkDisposed(); delete this._data[uri.toString()]; this._proxy.$changeMany(this.name, [[<URI> uri, undefined]]); } clear(): void { this._checkDisposed(); this._data = Object.create(null); this._proxy.$clear(this.name); } forEach(callback: (uri: URI, diagnostics: vscode.Diagnostic[], collection: DiagnosticCollection) => any, thisArg?: any): void { this._checkDisposed(); for (let key in this._data) { let uri = URI.parse(key); callback.apply(thisArg, [uri, this.get(uri), this]); } } get(uri: URI): vscode.Diagnostic[] { this._checkDisposed(); let result = this._data[uri.toString()]; if (Array.isArray(result)) { return Object.freeze(result.slice(0)); } } has(uri: URI): boolean { this._checkDisposed(); return Array.isArray(this._data[uri.toString()]); } private _checkDisposed() { if (this._isDisposed) { throw new Error('illegal state - object is disposed'); } } private static _toMarkerData(diagnostic: vscode.Diagnostic): IMarkerData { let range = diagnostic.range; return <IMarkerData>{ startLineNumber: range.start.line + 1, startColumn: range.start.character + 1, endLineNumber: range.end.line + 1, endColumn: range.end.character + 1, message: diagnostic.message, source: diagnostic.source, severity: DiagnosticCollection._convertDiagnosticsSeverity(diagnostic.severity), code: String(diagnostic.code) }; } private static _convertDiagnosticsSeverity(severity: number): Severity { switch (severity) { case 0: return Severity.Error; case 1: return Severity.Warning; case 2: return Severity.Info; case 3: return Severity.Ignore; default: return Severity.Error; } } } export class ExtHostDiagnostics extends ExtHostDiagnosticsShape { private static _idPool: number = 0; private _proxy: MainThreadDiagnosticsShape; private _collections: DiagnosticCollection[]; constructor(threadService: IThreadService) { super(); this._proxy = threadService.get(MainContext.MainThreadDiagnostics); this._collections = []; } createDiagnosticCollection(name: string): vscode.DiagnosticCollection { if (!name) { name = '_generated_diagnostic_collection_name_#' + ExtHostDiagnostics._idPool++; } const {_collections, _proxy} = this; const result = new class extends DiagnosticCollection { constructor() { super(name, _proxy); _collections.push(this); } dispose() { super.dispose(); let idx = _collections.indexOf(this); if (idx !== -1) { _collections.splice(idx, 1); } } }; return result; } forEach(callback: (collection: DiagnosticCollection) => any): void { this._collections.forEach(callback); } }
src/vs/workbench/api/node/extHostDiagnostics.ts
1
https://github.com/microsoft/vscode/commit/fe8bb5b4849061ed88b97dcf76e09ebcce3a6d82
[ 0.99906986951828, 0.3911769390106201, 0.00016227357264142483, 0.001320350100286305, 0.48664554953575134 ]
{ "id": 1, "code_window": [ "import {IMarkerData} from 'vs/platform/markers/common/markers';\n", "import URI from 'vs/base/common/uri';\n", "import Severity from 'vs/base/common/severity';\n", "import * as vscode from 'vscode';\n", "import {MainContext, MainThreadDiagnosticsShape, ExtHostDiagnosticsShape} from './extHost.protocol';\n", "import {Diagnostic} from './extHostTypes';\n", "\n", "export class DiagnosticCollection implements vscode.DiagnosticCollection {\n", "\n", "\tprivate static _maxDiagnosticsPerFile: number = 250;\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import {DiagnosticSeverity} from './extHostTypes';\n" ], "file_path": "src/vs/workbench/api/node/extHostDiagnostics.ts", "type": "replace", "edit_start_line_idx": 12 }
all: hello hello: main.o factorial.o hello.o g++ main.o factorial.o hello.o -o hello main.o: main.cpp g++ -c main.cpp factorial.o: factorial.cpp g++ -c factorial.cpp hello.o: hello.cpp g++ -c hello.cpp clean: rm *o hello
extensions/make/test/colorize-fixtures/makefile
0
https://github.com/microsoft/vscode/commit/fe8bb5b4849061ed88b97dcf76e09ebcce3a6d82
[ 0.0001767016656231135, 0.00017492900951765478, 0.00017315636796411127, 0.00017492900951765478, 0.0000017726488295011222 ]
{ "id": 1, "code_window": [ "import {IMarkerData} from 'vs/platform/markers/common/markers';\n", "import URI from 'vs/base/common/uri';\n", "import Severity from 'vs/base/common/severity';\n", "import * as vscode from 'vscode';\n", "import {MainContext, MainThreadDiagnosticsShape, ExtHostDiagnosticsShape} from './extHost.protocol';\n", "import {Diagnostic} from './extHostTypes';\n", "\n", "export class DiagnosticCollection implements vscode.DiagnosticCollection {\n", "\n", "\tprivate static _maxDiagnosticsPerFile: number = 250;\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import {DiagnosticSeverity} from './extHostTypes';\n" ], "file_path": "src/vs/workbench/api/node/extHostDiagnostics.ts", "type": "replace", "edit_start_line_idx": 12 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "navigateEditorHistoryByInput": "기록 탐색", "quickNavigateNext": "빠른 열기에서 다음 탐색", "quickNavigatePrevious": "빠른 열기에서 이전 탐색", "quickOpen": "파일로 이동..." }
i18n/kor/src/vs/workbench/browser/actions/triggerQuickOpen.i18n.json
0
https://github.com/microsoft/vscode/commit/fe8bb5b4849061ed88b97dcf76e09ebcce3a6d82
[ 0.00017289488459937274, 0.00017249814118258655, 0.00017210141231771559, 0.00017249814118258655, 3.9673614082857966e-7 ]
{ "id": 1, "code_window": [ "import {IMarkerData} from 'vs/platform/markers/common/markers';\n", "import URI from 'vs/base/common/uri';\n", "import Severity from 'vs/base/common/severity';\n", "import * as vscode from 'vscode';\n", "import {MainContext, MainThreadDiagnosticsShape, ExtHostDiagnosticsShape} from './extHost.protocol';\n", "import {Diagnostic} from './extHostTypes';\n", "\n", "export class DiagnosticCollection implements vscode.DiagnosticCollection {\n", "\n", "\tprivate static _maxDiagnosticsPerFile: number = 250;\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import {DiagnosticSeverity} from './extHostTypes';\n" ], "file_path": "src/vs/workbench/api/node/extHostDiagnostics.ts", "type": "replace", "edit_start_line_idx": 12 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "authFailed": "L'autenticazione non è riuscita su git remote.", "branch": "Branch", "branch2": "Branch", "checkout": "Checkout", "cleanChangesLabel": "&&Pulisci modifiche", "commit": "Commit", "commitAll": "Esegui commit di tutto", "commitAll2": "Esegui commit di tutto", "commitStaged": "Esegui commit delle righe preparate", "commitStaged2": "Esegui commit delle righe preparate", "confirmPublishMessage": "Pubblicare '{0}' in '{1}'?", "confirmPublishMessageButton": "&&Pubblica", "confirmUndo": "Pulire le modifiche in '{0}'?", "confirmUndoAllMultiple": "In {0} file ci sono modifiche non preparate per il commit.\n\nQuesta azione è irreversibile.", "confirmUndoAllOne": "In {0} file ci sono modifiche non preparate per il commit.\n\nQuesta azione è irreversibile.", "confirmUndoMessage": "Pulire tutte le modifiche?", "currentBranch": "Il ramo corrente '{0}' è aggiornato.", "currentBranchPlural": "Il ramo corrente '{0}' è {1} commit indietro e {2} commit avanti rispetto a '{3}'.", "currentBranchPluralSingle": "Il ramo corrente '{0}' è {1} commit indietro e {2} commit avanti rispetto a '{3}'.", "currentBranchSingle": "Il ramo corrente '{0}' è {1} commit indietro e {2} commit avanti rispetto a '{3}'.", "currentBranchSinglePlural": "Il ramo corrente '{0}' è {1} commit indietro e {2} commit avanti rispetto a '{3}'.", "currentlyDetached": "Non è possibile eseguire la sincronizzazione se non si è collegati.", "dirtyChanges": "Eseguire il commit delle modifiche, annullarle o salvarle con il comando stash prima della sincronizzazione.", "dirtyTreeCheckout": "Non è possibile eseguire l'estrazione. Eseguire prima il commit del lavoro o prepararlo per il commit.", "dirtyTreePull": "Non è possibile eseguire il pull. Eseguire prima il commit del lavoro o prepararlo per il commit.", "init": "Init", "irreversible": "Questa azione è irreversibile.", "noUpstream": "Il ramo '{0}' corrente non contiene un ramo a monte configurato.", "openChange": "Apri modifica", "openFile": "Apri file", "publish": "Pubblica", "publishPickMessage": "Selezionare un repository remoto in cui pubblicare il ramo '{0}':", "pull": "Pull", "pullWithRebase": "Esegui pull (Riassegna)", "push": "Push", "refresh": "Aggiorna", "stageAllChanges": "Gestisci tutto temporaneamente", "stageChanges": "Prepara", "sync": "Sincronizza", "synchronizing": "Sincronizzazione...", "undoAllChanges": "Pulisci tutto", "undoChanges": "Pulisci", "undoLastCommit": "Annulla ultimo commit", "unstage": "Annulla preparazione", "unstageAllChanges": "Annulla la gestione temporanea di tutto" }
i18n/ita/src/vs/workbench/parts/git/browser/gitActions.i18n.json
0
https://github.com/microsoft/vscode/commit/fe8bb5b4849061ed88b97dcf76e09ebcce3a6d82
[ 0.00017587901675142348, 0.00017365609528496861, 0.00016810238594189286, 0.0001746453926898539, 0.0000026560769583738875 ]
{ "id": 2, "code_window": [ "\t\t\tlet diagnostics = this._data[uri.toString()];\n", "\t\t\tif (diagnostics) {\n", "\n", "\t\t\t\t// no more than 250 diagnostics per file\n", "\t\t\t\tif (diagnostics.length > DiagnosticCollection._maxDiagnosticsPerFile) {\n", "\t\t\t\t\tconsole.warn('diagnostics for %s will be capped to %d (actually is %d)', uri.toString(), DiagnosticCollection._maxDiagnosticsPerFile, diagnostics.length);\n", "\t\t\t\t\tmarker = [];\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/api/node/extHostDiagnostics.ts", "type": "replace", "edit_start_line_idx": 100 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import {IThreadService} from 'vs/workbench/services/thread/common/threadService'; import {IMarkerData} from 'vs/platform/markers/common/markers'; import URI from 'vs/base/common/uri'; import Severity from 'vs/base/common/severity'; import * as vscode from 'vscode'; import {MainContext, MainThreadDiagnosticsShape, ExtHostDiagnosticsShape} from './extHost.protocol'; import {Diagnostic} from './extHostTypes'; export class DiagnosticCollection implements vscode.DiagnosticCollection { private static _maxDiagnosticsPerFile: number = 250; private _name: string; private _proxy: MainThreadDiagnosticsShape; private _isDisposed = false; private _data: {[uri:string]: vscode.Diagnostic[]} = Object.create(null); constructor(name: string, proxy: MainThreadDiagnosticsShape) { this._name = name; this._proxy = proxy; } dispose(): void { if (!this._isDisposed) { this._proxy.$clear(this.name); this._proxy = undefined; this._data = undefined; this._isDisposed = true; } } get name(): string { this._checkDisposed(); return this._name; } set(uri: vscode.Uri, diagnostics: vscode.Diagnostic[]): void; set(entries: [vscode.Uri, vscode.Diagnostic[]][]): void; set(first: vscode.Uri | [vscode.Uri, vscode.Diagnostic[]][], diagnostics?: vscode.Diagnostic[]) { if (!first) { // this set-call is a clear-call this.clear(); return; } // the actual implementation for #set this._checkDisposed(); let toSync: vscode.Uri[]; if (first instanceof URI) { if (!diagnostics) { // remove this entry this.delete(first); return; } // update single row this._data[first.toString()] = diagnostics; toSync = [first]; } else if (Array.isArray(first)) { // update many rows toSync = []; for (let entry of first) { let [uri, diagnostics] = entry; toSync.push(uri); if (!diagnostics) { // [Uri, undefined] means clear this delete this._data[uri.toString()]; } else { // set or merge diagnostics let existing = this._data[uri.toString()]; if (existing) { existing.push(...diagnostics); } else { this._data[uri.toString()] = diagnostics; } } } } // compute change and send to main side const entries: [URI, IMarkerData[]][] = []; for (let uri of toSync) { let marker: IMarkerData[]; let diagnostics = this._data[uri.toString()]; if (diagnostics) { // no more than 250 diagnostics per file if (diagnostics.length > DiagnosticCollection._maxDiagnosticsPerFile) { console.warn('diagnostics for %s will be capped to %d (actually is %d)', uri.toString(), DiagnosticCollection._maxDiagnosticsPerFile, diagnostics.length); marker = []; const sorted = diagnostics.slice(0).sort(Diagnostic.compare); for (let i = 0; i < DiagnosticCollection._maxDiagnosticsPerFile; i++) { marker.push(DiagnosticCollection._toMarkerData(sorted[i])); } } else { marker = diagnostics.map(DiagnosticCollection._toMarkerData); } } entries.push([<URI> uri, marker]); } this._proxy.$changeMany(this.name, entries); } delete(uri: vscode.Uri): void { this._checkDisposed(); delete this._data[uri.toString()]; this._proxy.$changeMany(this.name, [[<URI> uri, undefined]]); } clear(): void { this._checkDisposed(); this._data = Object.create(null); this._proxy.$clear(this.name); } forEach(callback: (uri: URI, diagnostics: vscode.Diagnostic[], collection: DiagnosticCollection) => any, thisArg?: any): void { this._checkDisposed(); for (let key in this._data) { let uri = URI.parse(key); callback.apply(thisArg, [uri, this.get(uri), this]); } } get(uri: URI): vscode.Diagnostic[] { this._checkDisposed(); let result = this._data[uri.toString()]; if (Array.isArray(result)) { return Object.freeze(result.slice(0)); } } has(uri: URI): boolean { this._checkDisposed(); return Array.isArray(this._data[uri.toString()]); } private _checkDisposed() { if (this._isDisposed) { throw new Error('illegal state - object is disposed'); } } private static _toMarkerData(diagnostic: vscode.Diagnostic): IMarkerData { let range = diagnostic.range; return <IMarkerData>{ startLineNumber: range.start.line + 1, startColumn: range.start.character + 1, endLineNumber: range.end.line + 1, endColumn: range.end.character + 1, message: diagnostic.message, source: diagnostic.source, severity: DiagnosticCollection._convertDiagnosticsSeverity(diagnostic.severity), code: String(diagnostic.code) }; } private static _convertDiagnosticsSeverity(severity: number): Severity { switch (severity) { case 0: return Severity.Error; case 1: return Severity.Warning; case 2: return Severity.Info; case 3: return Severity.Ignore; default: return Severity.Error; } } } export class ExtHostDiagnostics extends ExtHostDiagnosticsShape { private static _idPool: number = 0; private _proxy: MainThreadDiagnosticsShape; private _collections: DiagnosticCollection[]; constructor(threadService: IThreadService) { super(); this._proxy = threadService.get(MainContext.MainThreadDiagnostics); this._collections = []; } createDiagnosticCollection(name: string): vscode.DiagnosticCollection { if (!name) { name = '_generated_diagnostic_collection_name_#' + ExtHostDiagnostics._idPool++; } const {_collections, _proxy} = this; const result = new class extends DiagnosticCollection { constructor() { super(name, _proxy); _collections.push(this); } dispose() { super.dispose(); let idx = _collections.indexOf(this); if (idx !== -1) { _collections.splice(idx, 1); } } }; return result; } forEach(callback: (collection: DiagnosticCollection) => any): void { this._collections.forEach(callback); } }
src/vs/workbench/api/node/extHostDiagnostics.ts
1
https://github.com/microsoft/vscode/commit/fe8bb5b4849061ed88b97dcf76e09ebcce3a6d82
[ 0.9973672032356262, 0.21548059582710266, 0.00016534504538867623, 0.0021353319752961397, 0.4038282632827759 ]
{ "id": 2, "code_window": [ "\t\t\tlet diagnostics = this._data[uri.toString()];\n", "\t\t\tif (diagnostics) {\n", "\n", "\t\t\t\t// no more than 250 diagnostics per file\n", "\t\t\t\tif (diagnostics.length > DiagnosticCollection._maxDiagnosticsPerFile) {\n", "\t\t\t\t\tconsole.warn('diagnostics for %s will be capped to %d (actually is %d)', uri.toString(), DiagnosticCollection._maxDiagnosticsPerFile, diagnostics.length);\n", "\t\t\t\t\tmarker = [];\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/api/node/extHostDiagnostics.ts", "type": "replace", "edit_start_line_idx": 100 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "invalid.injectTo": "`contributes.{0}.injectTo` の値が無効です。言語の範囲名の配列である必要があります。指定された値: {1}", "invalid.language": "`contributes.{0}.language` で不明な言語です。提供された値: {1}", "invalid.path.0": "`contributes.{0}.path` に文字列が必要です。提供された値: {1}", "invalid.path.1": "拡張機能のフォルダー ({2}) の中に `contributes.{0}.path` ({1}) が含まれている必要があります。これにより拡張を移植できなくなる可能性があります。", "invalid.scopeName": "`contributes.{0}.scopeName` には文字列が必要です。提供された値: {1}", "vscode.extension.contributes.grammars": "TextMate トークナイザーを提供します。", "vscode.extension.contributes.grammars.injectTo": "この文法が挿入される言語の範囲名の一覧。", "vscode.extension.contributes.grammars.language": "この構文の提供先の言語識別子です。", "vscode.extension.contributes.grammars.path": "tmLanguage ファイルのパス。拡張機能フォルダーの相対パスであり、通常 './syntaxes/' で始まります。", "vscode.extension.contributes.grammars.scopeName": "tmLanguage ファイルにより使用される TextMate スコープ名。" }
i18n/jpn/src/vs/editor/node/textMate/TMSyntax.i18n.json
0
https://github.com/microsoft/vscode/commit/fe8bb5b4849061ed88b97dcf76e09ebcce3a6d82
[ 0.0001680485438555479, 0.00016695924568921328, 0.00016586994752287865, 0.00016695924568921328, 0.000001089298166334629 ]
{ "id": 2, "code_window": [ "\t\t\tlet diagnostics = this._data[uri.toString()];\n", "\t\t\tif (diagnostics) {\n", "\n", "\t\t\t\t// no more than 250 diagnostics per file\n", "\t\t\t\tif (diagnostics.length > DiagnosticCollection._maxDiagnosticsPerFile) {\n", "\t\t\t\t\tconsole.warn('diagnostics for %s will be capped to %d (actually is %d)', uri.toString(), DiagnosticCollection._maxDiagnosticsPerFile, diagnostics.length);\n", "\t\t\t\t\tmarker = [];\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/api/node/extHostDiagnostics.ts", "type": "replace", "edit_start_line_idx": 100 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "json.nugget.error.access": "Error de la solicitud a {0}: {1}", "json.nugget.error.indexaccess": "Error de la solicitud a {0}: {1}", "json.nugget.error.invalidformat": "{0} no es un documento JSON válido", "json.nugget.error.missingservice": "El documento de índices NuGet no tiene el servicio {0}.", "json.nugget.package.hover": "{0}", "json.nugget.version.hover": "Última versión: {0}", "json.project.default": "Project.json predeterminado" }
i18n/esn/extensions/json/server/out/jsoncontributions/projectJSONContribution.i18n.json
0
https://github.com/microsoft/vscode/commit/fe8bb5b4849061ed88b97dcf76e09ebcce3a6d82
[ 0.00017384755483362824, 0.00017352226132061332, 0.0001731969678075984, 0.00017352226132061332, 3.252935130149126e-7 ]
{ "id": 2, "code_window": [ "\t\t\tlet diagnostics = this._data[uri.toString()];\n", "\t\t\tif (diagnostics) {\n", "\n", "\t\t\t\t// no more than 250 diagnostics per file\n", "\t\t\t\tif (diagnostics.length > DiagnosticCollection._maxDiagnosticsPerFile) {\n", "\t\t\t\t\tconsole.warn('diagnostics for %s will be capped to %d (actually is %d)', uri.toString(), DiagnosticCollection._maxDiagnosticsPerFile, diagnostics.length);\n", "\t\t\t\t\tmarker = [];\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/api/node/extHostDiagnostics.ts", "type": "replace", "edit_start_line_idx": 100 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "_constructor": "생성자({0})", "array": "배열({0})", "boolean": "부울({0})", "cannotRunGotoSymbol": "첫 번째 텍스트 파일을 열어서 기호로 이동합니다.", "cannotRunGotoSymbolInFile": "파일에 대한 기호 정보가 없습니다.", "class": "클래스({0})", "entryAriaLabel": "{0}, 기호", "enum": "열거형({0})", "file": "파일({0})", "function": "함수({0})", "gotoSymbol": "기호 이동...", "gotoSymbolHandlerAriaLabel": "입력하여 현재 활성화된 편집기의 기호를 축소합니다.", "interface": "인터페이스({0})", "key": "키({0})", "method": "메서드({0})", "modules": "모듈({0})", "namespace": "네임스페이스({0})", "noSymbolsFound": "기호를 찾을 수 없음", "noSymbolsMatching": "일치하는 기호 없음", "number": "구성원({0})", "object": "개체({0})", "package": "패키지({0})", "property": "속성({0})", "rule": "규칙({0})", "string": "문자열({0})", "symbols": "기호({0})", "variable": "변수({0})" }
i18n/kor/src/vs/workbench/parts/quickopen/browser/gotoSymbolHandler.i18n.json
0
https://github.com/microsoft/vscode/commit/fe8bb5b4849061ed88b97dcf76e09ebcce3a6d82
[ 0.00017185758042614907, 0.00017025103443302214, 0.00016642648552078754, 0.00017136002134066075, 0.000002240972889921977 ]
{ "id": 3, "code_window": [ "\t\t\t\t\tmarker = [];\n", "\t\t\t\t\tconst sorted = diagnostics.slice(0).sort(Diagnostic.compare);\n", "\t\t\t\t\tfor (let i = 0; i < DiagnosticCollection._maxDiagnosticsPerFile; i++) {\n", "\t\t\t\t\t\tmarker.push(DiagnosticCollection._toMarkerData(sorted[i]));\n", "\t\t\t\t\t}\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\t\t\t\tconst order = [DiagnosticSeverity.Error, DiagnosticSeverity.Warning, DiagnosticSeverity.Information, DiagnosticSeverity.Hint];\n", "\t\t\t\t\torderLoop: for (let i = 0; i < 4; i++) {\n", "\t\t\t\t\t\tfor (const diagnostic of diagnostics) {\n", "\t\t\t\t\t\t\tif (diagnostic.severity === order[i]) {\n", "\t\t\t\t\t\t\t\tconst len = marker.push(DiagnosticCollection._toMarkerData(diagnostic));\n", "\t\t\t\t\t\t\t\tif (len === DiagnosticCollection._maxDiagnosticsPerFile) {\n", "\t\t\t\t\t\t\t\t\tbreak orderLoop;\n", "\t\t\t\t\t\t\t\t}\n", "\t\t\t\t\t\t\t}\n", "\t\t\t\t\t\t}\n" ], "file_path": "src/vs/workbench/api/node/extHostDiagnostics.ts", "type": "replace", "edit_start_line_idx": 102 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import {IThreadService} from 'vs/workbench/services/thread/common/threadService'; import {IMarkerData} from 'vs/platform/markers/common/markers'; import URI from 'vs/base/common/uri'; import Severity from 'vs/base/common/severity'; import * as vscode from 'vscode'; import {MainContext, MainThreadDiagnosticsShape, ExtHostDiagnosticsShape} from './extHost.protocol'; import {Diagnostic} from './extHostTypes'; export class DiagnosticCollection implements vscode.DiagnosticCollection { private static _maxDiagnosticsPerFile: number = 250; private _name: string; private _proxy: MainThreadDiagnosticsShape; private _isDisposed = false; private _data: {[uri:string]: vscode.Diagnostic[]} = Object.create(null); constructor(name: string, proxy: MainThreadDiagnosticsShape) { this._name = name; this._proxy = proxy; } dispose(): void { if (!this._isDisposed) { this._proxy.$clear(this.name); this._proxy = undefined; this._data = undefined; this._isDisposed = true; } } get name(): string { this._checkDisposed(); return this._name; } set(uri: vscode.Uri, diagnostics: vscode.Diagnostic[]): void; set(entries: [vscode.Uri, vscode.Diagnostic[]][]): void; set(first: vscode.Uri | [vscode.Uri, vscode.Diagnostic[]][], diagnostics?: vscode.Diagnostic[]) { if (!first) { // this set-call is a clear-call this.clear(); return; } // the actual implementation for #set this._checkDisposed(); let toSync: vscode.Uri[]; if (first instanceof URI) { if (!diagnostics) { // remove this entry this.delete(first); return; } // update single row this._data[first.toString()] = diagnostics; toSync = [first]; } else if (Array.isArray(first)) { // update many rows toSync = []; for (let entry of first) { let [uri, diagnostics] = entry; toSync.push(uri); if (!diagnostics) { // [Uri, undefined] means clear this delete this._data[uri.toString()]; } else { // set or merge diagnostics let existing = this._data[uri.toString()]; if (existing) { existing.push(...diagnostics); } else { this._data[uri.toString()] = diagnostics; } } } } // compute change and send to main side const entries: [URI, IMarkerData[]][] = []; for (let uri of toSync) { let marker: IMarkerData[]; let diagnostics = this._data[uri.toString()]; if (diagnostics) { // no more than 250 diagnostics per file if (diagnostics.length > DiagnosticCollection._maxDiagnosticsPerFile) { console.warn('diagnostics for %s will be capped to %d (actually is %d)', uri.toString(), DiagnosticCollection._maxDiagnosticsPerFile, diagnostics.length); marker = []; const sorted = diagnostics.slice(0).sort(Diagnostic.compare); for (let i = 0; i < DiagnosticCollection._maxDiagnosticsPerFile; i++) { marker.push(DiagnosticCollection._toMarkerData(sorted[i])); } } else { marker = diagnostics.map(DiagnosticCollection._toMarkerData); } } entries.push([<URI> uri, marker]); } this._proxy.$changeMany(this.name, entries); } delete(uri: vscode.Uri): void { this._checkDisposed(); delete this._data[uri.toString()]; this._proxy.$changeMany(this.name, [[<URI> uri, undefined]]); } clear(): void { this._checkDisposed(); this._data = Object.create(null); this._proxy.$clear(this.name); } forEach(callback: (uri: URI, diagnostics: vscode.Diagnostic[], collection: DiagnosticCollection) => any, thisArg?: any): void { this._checkDisposed(); for (let key in this._data) { let uri = URI.parse(key); callback.apply(thisArg, [uri, this.get(uri), this]); } } get(uri: URI): vscode.Diagnostic[] { this._checkDisposed(); let result = this._data[uri.toString()]; if (Array.isArray(result)) { return Object.freeze(result.slice(0)); } } has(uri: URI): boolean { this._checkDisposed(); return Array.isArray(this._data[uri.toString()]); } private _checkDisposed() { if (this._isDisposed) { throw new Error('illegal state - object is disposed'); } } private static _toMarkerData(diagnostic: vscode.Diagnostic): IMarkerData { let range = diagnostic.range; return <IMarkerData>{ startLineNumber: range.start.line + 1, startColumn: range.start.character + 1, endLineNumber: range.end.line + 1, endColumn: range.end.character + 1, message: diagnostic.message, source: diagnostic.source, severity: DiagnosticCollection._convertDiagnosticsSeverity(diagnostic.severity), code: String(diagnostic.code) }; } private static _convertDiagnosticsSeverity(severity: number): Severity { switch (severity) { case 0: return Severity.Error; case 1: return Severity.Warning; case 2: return Severity.Info; case 3: return Severity.Ignore; default: return Severity.Error; } } } export class ExtHostDiagnostics extends ExtHostDiagnosticsShape { private static _idPool: number = 0; private _proxy: MainThreadDiagnosticsShape; private _collections: DiagnosticCollection[]; constructor(threadService: IThreadService) { super(); this._proxy = threadService.get(MainContext.MainThreadDiagnostics); this._collections = []; } createDiagnosticCollection(name: string): vscode.DiagnosticCollection { if (!name) { name = '_generated_diagnostic_collection_name_#' + ExtHostDiagnostics._idPool++; } const {_collections, _proxy} = this; const result = new class extends DiagnosticCollection { constructor() { super(name, _proxy); _collections.push(this); } dispose() { super.dispose(); let idx = _collections.indexOf(this); if (idx !== -1) { _collections.splice(idx, 1); } } }; return result; } forEach(callback: (collection: DiagnosticCollection) => any): void { this._collections.forEach(callback); } }
src/vs/workbench/api/node/extHostDiagnostics.ts
1
https://github.com/microsoft/vscode/commit/fe8bb5b4849061ed88b97dcf76e09ebcce3a6d82
[ 0.9984022974967957, 0.04947890341281891, 0.00016608960868325084, 0.0004284805618226528, 0.2029590606689453 ]
{ "id": 3, "code_window": [ "\t\t\t\t\tmarker = [];\n", "\t\t\t\t\tconst sorted = diagnostics.slice(0).sort(Diagnostic.compare);\n", "\t\t\t\t\tfor (let i = 0; i < DiagnosticCollection._maxDiagnosticsPerFile; i++) {\n", "\t\t\t\t\t\tmarker.push(DiagnosticCollection._toMarkerData(sorted[i]));\n", "\t\t\t\t\t}\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\t\t\t\tconst order = [DiagnosticSeverity.Error, DiagnosticSeverity.Warning, DiagnosticSeverity.Information, DiagnosticSeverity.Hint];\n", "\t\t\t\t\torderLoop: for (let i = 0; i < 4; i++) {\n", "\t\t\t\t\t\tfor (const diagnostic of diagnostics) {\n", "\t\t\t\t\t\t\tif (diagnostic.severity === order[i]) {\n", "\t\t\t\t\t\t\t\tconst len = marker.push(DiagnosticCollection._toMarkerData(diagnostic));\n", "\t\t\t\t\t\t\t\tif (len === DiagnosticCollection._maxDiagnosticsPerFile) {\n", "\t\t\t\t\t\t\t\t\tbreak orderLoop;\n", "\t\t\t\t\t\t\t\t}\n", "\t\t\t\t\t\t\t}\n", "\t\t\t\t\t\t}\n" ], "file_path": "src/vs/workbench/api/node/extHostDiagnostics.ts", "type": "replace", "edit_start_line_idx": 102 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "alertErrorMessage": "Erreur : {0}", "alertInfoMessage": "Information : {0}", "alertWarningMessage": "Avertissement : {0}" }
i18n/fra/src/vs/base/browser/ui/inputbox/inputBox.i18n.json
0
https://github.com/microsoft/vscode/commit/fe8bb5b4849061ed88b97dcf76e09ebcce3a6d82
[ 0.00017664305050857365, 0.00017657250282354653, 0.0001765019551385194, 0.00017657250282354653, 7.05476850271225e-8 ]