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": 5, "code_window": [ " ]\n", " },\n", " \"ignore\": [\"i18n/schema-validation.*\", \"**/__mocks__\", \"**/__fixtures__\"]\n", " },\n", " \"client/plugins/*\": {\n", " \"entry\": \"gatsby-node.js\"\n", " },\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " }\n", " },\n", " \"client\": {\n", " \"webpack\": \"webpack-workers.js\",\n", " \"ignore\": [\"**/__mocks__\"]\n" ], "file_path": "knip.jsonc", "type": "replace", "edit_start_line_idx": 25 }
--- id: bad87fee1348bd9aedf08827 title: Creare un elenco puntato non ordinato challengeType: 0 videoUrl: 'https://scrimba.com/p/pVMPUv/cDKVPuv' forumTopicId: 16814 dashedName: create-a-bulleted-unordered-list --- # --description-- HTML ha un elemento speciale per la creazione di <dfn>liste non ordinate</dfn>, o elenchi puntati. Le liste non ordinate iniziano con un elemento di apertura `<ul>`, seguito da qualsiasi numero di elementi `<li>`. Infine, le liste non ordinate si chiudono con un `</ul>`. Ad esempio: ```html <ul> <li>milk</li> <li>cheese</li> </ul> ``` creerebbe un elenco puntato contenente `milk` e `cheese`. # --instructions-- Rimuovi gli ultimi due elementi `p` e crea in fondo alla pagina una lista non ordinata di tre cose che i gatti amano. # --hints-- Crea un elemento `ul`. ```js assert($('ul').length > 0); ``` Dovresti avere tre elementi `li` all'interno del tuo elemento `ul`. ```js assert($('ul li').length > 2); ``` Il tuo elemento `ul` dovrebbe avere un tag di chiusura. ```js assert( code.match(/<\/ul>/gi) && code.match(/<ul/gi) && code.match(/<\/ul>/gi).length === code.match(/<ul/gi).length ); ``` Il tuo elemento `li` dovrebbe avere un tag di chiusura. ```js assert( code.match(/<\/li>/gi) && code.match(/<li[\s>]/gi) && code.match(/<\/li>/gi).length === code.match(/<li[\s>]/gi).length ); ``` I tuoi elementi `li` non dovrebbero contenere una stringa vuota o solo spazi bianchi. ```js assert($('ul li').filter((_, item) => !$(item).text().trim()).length === 0); ``` # --seed-- ## --seed-contents-- ```html <h2>CatPhotoApp</h2> <main> <p>Click here to view more <a href="#">cat photos</a>.</p> <a href="#"><img src="https://cdn.freecodecamp.org/curriculum/cat-photo-app/relaxing-cat.jpg" alt="A cute orange cat lying on its back."></a> <p>Kitty ipsum dolor sit amet, shed everywhere shed everywhere stretching attack your ankles chase the red dot, hairball run catnip eat the grass sniff.</p> <p>Purr jump eat the grass rip the couch scratched sunbathe, shed everywhere rip the couch sleep in the sink fluffy fur catnip scratched.</p> </main> ``` # --solutions-- ```html <h2>CatPhotoApp</h2> <main> <p>Click here to view more <a href="#">cat photos</a>.</p> <a href="#"><img src="https://cdn.freecodecamp.org/curriculum/cat-photo-app/relaxing-cat.jpg" alt="A cute orange cat lying on its back."></a> <ul> <li>milk</li> <li>mice</li> <li>catnip</li> </ul> </main> ```
curriculum/challenges/italian/01-responsive-web-design/basic-html-and-html5/create-a-bulleted-unordered-list.md
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/e5715b5948de9aa665f78ce0ad94eaef0a3f5a6d
[ 0.00017355920863337815, 0.0001710228098090738, 0.00016514149319846183, 0.0001718570856610313, 0.0000023914535631774925 ]
{ "id": 5, "code_window": [ " ]\n", " },\n", " \"ignore\": [\"i18n/schema-validation.*\", \"**/__mocks__\", \"**/__fixtures__\"]\n", " },\n", " \"client/plugins/*\": {\n", " \"entry\": \"gatsby-node.js\"\n", " },\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " }\n", " },\n", " \"client\": {\n", " \"webpack\": \"webpack-workers.js\",\n", " \"ignore\": [\"**/__mocks__\"]\n" ], "file_path": "knip.jsonc", "type": "replace", "edit_start_line_idx": 25 }
import { addons } from '@storybook/addons'; import theme from './theme'; addons.setConfig({ theme });
tools/ui-components/.storybook/manager.js
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/e5715b5948de9aa665f78ce0ad94eaef0a3f5a6d
[ 0.0001712324155960232, 0.0001712324155960232, 0.0001712324155960232, 0.0001712324155960232, 0 ]
{ "id": 6, "code_window": [ " },\n", " \"client/plugins/*\": {\n", " \"entry\": \"gatsby-node.js\"\n", " },\n", " // This monospace gives a few unused files, so as not to make the node.js-find-unused workflow fail this is still commented out\n", " // Also try --production to find more unused files.\n", " // \"tools/ui-components\": {\n", " // \"entry\": [\"src/index.ts!\", \"utils/gen-component-script.ts\"],\n", " // \"project\": [\"src/**/*.{ts,tsx}!\", \"utils/*.ts\"]\n", " // },\n", " \"tools/scripts/build\": {\n", " \"entry\": [\"*.ts\"]\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " // \"tools/ui-components\": {},\n" ], "file_path": "knip.jsonc", "type": "replace", "edit_start_line_idx": 31 }
{ "$schema": "https://unpkg.com/knip@next/schema.json", "ignore": "**/*.d.ts", "ignoreBinaries": ["cd", "echo", "sh"], // Only workspaces with a configuration below are analyzed by Knip "workspaces": { ".": { "entry": [], // Configuration options can be overridden individually (necessary here as the default is `cypress/e2e/**/*.cy.{js,jsx,ts,tsx}`). "cypress": ["cypress.config.js", "cypress/e2e/**/*.{js,ts}"] }, "client": { // Files used by Gatsby are handled by Knip's Gatsby plugin (https://github.com/webpro/knip/blob/next/src/plugins/gatsby/README.md) // The rest are `webpack.entry` files. "entry": [], "project": ["**/*.{js,ts,tsx}"], "webpack": { "config": "webpack-workers.js", "entry": [ "src/client/frame-runner.ts", "src/client/workers/sass-compile.ts", "src/client/workers/test-evaluator.ts" ] }, "ignore": ["i18n/schema-validation.*", "**/__mocks__", "**/__fixtures__"] }, "client/plugins/*": { "entry": "gatsby-node.js" }, // This monospace gives a few unused files, so as not to make the node.js-find-unused workflow fail this is still commented out // Also try --production to find more unused files. // "tools/ui-components": { // "entry": ["src/index.ts!", "utils/gen-component-script.ts"], // "project": ["src/**/*.{ts,tsx}!", "utils/*.ts"] // }, "tools/scripts/build": { "entry": ["*.ts"] } } }
knip.jsonc
1
https://github.com/freeCodeCamp/freeCodeCamp/commit/e5715b5948de9aa665f78ce0ad94eaef0a3f5a6d
[ 0.9963473677635193, 0.19958624243736267, 0.00016742317529860884, 0.0005425235722213984, 0.3983806371688843 ]
{ "id": 6, "code_window": [ " },\n", " \"client/plugins/*\": {\n", " \"entry\": \"gatsby-node.js\"\n", " },\n", " // This monospace gives a few unused files, so as not to make the node.js-find-unused workflow fail this is still commented out\n", " // Also try --production to find more unused files.\n", " // \"tools/ui-components\": {\n", " // \"entry\": [\"src/index.ts!\", \"utils/gen-component-script.ts\"],\n", " // \"project\": [\"src/**/*.{ts,tsx}!\", \"utils/*.ts\"]\n", " // },\n", " \"tools/scripts/build\": {\n", " \"entry\": [\"*.ts\"]\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " // \"tools/ui-components\": {},\n" ], "file_path": "knip.jsonc", "type": "replace", "edit_start_line_idx": 31 }
--- id: 5d822fd413a79914d39e9915 title: Schritt 106 challengeType: 0 dashedName: step-106 --- # --description-- You don't need the `background-color` for this building anymore so you can remove that property. # --hints-- Du solltest die `background-color` von `.fb5` entfernen. ```js assert.notMatch(code, /\.fb5\s*\{\s*[^}]*?background-color[^}]*?\}/); ``` # --seed-- ## --seed-contents-- ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>City Skyline</title> <link href="styles.css" rel="stylesheet" /> </head> <body> <div class="background-buildings"> <div></div> <div></div> <div class="bb1 building-wrap"> <div class="bb1a bb1-window"></div> <div class="bb1b bb1-window"></div> <div class="bb1c bb1-window"></div> <div class="bb1d"></div> </div> <div class="bb2"> <div class="bb2a"></div> <div class="bb2b"></div> </div> <div class="bb3"></div> <div></div> <div class="bb4 building-wrap"> <div class="bb4a"></div> <div class="bb4b"></div> <div class="bb4c window-wrap"> <div class="bb4-window"></div> <div class="bb4-window"></div> <div class="bb4-window"></div> <div class="bb4-window"></div> </div> </div> <div></div> <div></div> </div> <div class="foreground-buildings"> <div></div> <div></div> <div class="fb1 building-wrap"> <div class="fb1a"></div> <div class="fb1b"></div> <div class="fb1c"></div> </div> <div class="fb2"> <div class="fb2a"></div> <div class="fb2b window-wrap"> <div class="fb2-window"></div> <div class="fb2-window"></div> <div class="fb2-window"></div> </div> </div> <div></div> <div class="fb3 building-wrap"> <div class="fb3a window-wrap"> <div class="fb3-window"></div> <div class="fb3-window"></div> <div class="fb3-window"></div> </div> <div class="fb3b"></div> <div class="fb3a"></div> <div class="fb3b"></div> </div> <div class="fb4"> <div class="fb4a"></div> <div class="fb4b"> <div class="fb4-window"></div> <div class="fb4-window"></div> <div class="fb4-window"></div> <div class="fb4-window"></div> <div class="fb4-window"></div> <div class="fb4-window"></div> </div> </div> <div class="fb5"></div> <div class="fb6"></div> <div></div> <div></div> </div> </body> </html> ``` ```css :root { --building-color1: #aa80ff; --building-color2: #66cc99; --building-color3: #cc6699; --building-color4: #538cc6; --window-color1: #bb99ff; --window-color2: #8cd9b3; --window-color3: #d98cb3; --window-color4: #8cb3d9; } * { border: 1px solid black; box-sizing: border-box; } body { height: 100vh; margin: 0; overflow: hidden; } .background-buildings, .foreground-buildings { width: 100%; height: 100%; display: flex; align-items: flex-end; justify-content: space-evenly; position: absolute; top: 0; } .building-wrap { display: flex; flex-direction: column; align-items: center; } .window-wrap { display: flex; align-items: center; justify-content: space-evenly; } /* BACKGROUND BUILDINGS - "bb" stands for "background building" */ .bb1 { width: 10%; height: 70%; } .bb1a { width: 70%; } .bb1b { width: 80%; } .bb1c { width: 90%; } .bb1d { width: 100%; height: 70%; background: linear-gradient( var(--building-color1) 50%, var(--window-color1) ); } .bb1-window { height: 10%; background: linear-gradient( var(--building-color1), var(--window-color1) ); } .bb2 { width: 10%; height: 50%; } .bb2a { border-bottom: 5vh solid var(--building-color2); border-left: 5vw solid transparent; border-right: 5vw solid transparent; } .bb2b { width: 100%; height: 100%; background: repeating-linear-gradient( var(--building-color2), var(--building-color2) 6%, var(--window-color2) 6%, var(--window-color2) 9% ); } .bb3 { width: 10%; height: 55%; background: repeating-linear-gradient( 90deg, var(--building-color3), var(--building-color3), var(--window-color3) 15% ); } .bb4 { width: 11%; height: 58%; } .bb4a { width: 3%; height: 10%; background-color: var(--building-color4); } .bb4b { width: 80%; height: 5%; background-color: var(--building-color4); } .bb4c { width: 100%; height: 85%; background-color: var(--building-color4); } .bb4-window { width: 18%; height: 90%; background-color: var(--window-color4); } /* FOREGROUND BUILDINGS - "fb" stands for "foreground building" */ .fb1 { width: 10%; height: 60%; } .fb1a { border-bottom: 7vh solid var(--building-color4); border-left: 2vw solid transparent; border-right: 2vw solid transparent; } .fb1b { width: 60%; height: 10%; background-color: var(--building-color4); } .fb1c { width: 100%; height: 80%; background: repeating-linear-gradient( 90deg, var(--building-color4), var(--building-color4) 10%, transparent 10%, transparent 15% ), repeating-linear-gradient( var(--building-color4), var(--building-color4) 10%, var(--window-color4) 10%, var(--window-color4) 90% ); } .fb2 { width: 10%; height: 40%; } .fb2a { width: 100%; border-bottom: 10vh solid var(--building-color3); border-left: 1vw solid transparent; border-right: 1vw solid transparent; } .fb2b { width: 100%; height: 75%; background-color: var(--building-color3); } .fb2-window { width: 22%; height: 100%; background-color: var(--window-color3); } .fb3 { width: 10%; height: 35%; } .fb3a { width: 80%; height: 15%; background-color: var(--building-color1); } .fb3b { width: 100%; height: 35%; background-color: var(--building-color1); } .fb3-window { width: 25%; height: 80%; background-color: var(--window-color1); } .fb4 { width: 8%; height: 45%; position: relative; left: 10%; } .fb4a { border-top: 5vh solid transparent; border-left: 8vw solid var(--building-color1); } .fb4b { width: 100%; height: 89%; background-color: var(--building-color1); display: flex; flex-wrap: wrap; } .fb4-window { width: 30%; height: 10%; border-radius: 50%; background-color: var(--window-color1); margin: 10%; } --fcc-editable-region-- .fb5 { width: 10%; height: 33%; background-color: var(--building-color2); position: relative; right: 10%; background: repeating-linear-gradient( var(--building-color2), var(--building-color2) 5%, transparent 5%, transparent 10% ), repeating-linear-gradient( 90deg, var(--building-color2), var(--building-color2) 12%, var(--window-color2) 12%, var(--window-color2) 44% ); } --fcc-editable-region-- .fb6 { width: 9%; height: 38%; background-color: var(--building-color3); } ```
curriculum/challenges/german/14-responsive-web-design-22/learn-css-variables-by-building-a-city-skyline/5d822fd413a79914d39e9915.md
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/e5715b5948de9aa665f78ce0ad94eaef0a3f5a6d
[ 0.00017719398601911962, 0.00017188835772685707, 0.00016669425531290472, 0.00017251579265575856, 0.0000022838678432890447 ]
{ "id": 6, "code_window": [ " },\n", " \"client/plugins/*\": {\n", " \"entry\": \"gatsby-node.js\"\n", " },\n", " // This monospace gives a few unused files, so as not to make the node.js-find-unused workflow fail this is still commented out\n", " // Also try --production to find more unused files.\n", " // \"tools/ui-components\": {\n", " // \"entry\": [\"src/index.ts!\", \"utils/gen-component-script.ts\"],\n", " // \"project\": [\"src/**/*.{ts,tsx}!\", \"utils/*.ts\"]\n", " // },\n", " \"tools/scripts/build\": {\n", " \"entry\": [\"*.ts\"]\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " // \"tools/ui-components\": {},\n" ], "file_path": "knip.jsonc", "type": "replace", "edit_start_line_idx": 31 }
--- id: 5d8a4cfbe6b6180ed9a1ca20 title: Step 67 challengeType: 0 dashedName: step-67 --- # --description-- Next, set the `cy` attribute to `d => xScale(d.followers.twitter)`. As a reminder, this will pass each value of your Twitter followers to the `xScale` function where it will determine the y coordinate to use. # --hints-- test-text ```js assert($('svg circle')[0].getAttribute('cy') == '243.232'); ``` # --seed-- ## --before-user-code-- ```html <!DOCTYPE html> <html> <head> <title>D3 Dashboard</title> <style> body { background-color: #ccc; padding: 100px 10px; } .dashboard { width: 980px; height: 500px; background-color: white; box-shadow: 5px 5px 5px 5px #888; margin: auto; display: flex; align-items: center; } </style> </head> <body> <div class="dashboard"></div> </body> </html> ``` ## --seed-contents-- ```html <script> const data = [ { year: 2012, followers: { twitter: 2594, tumblr: 401, instagram: 83 }}, { year: 2013, followers: { twitter: 3049, tumblr: 440, instagram: 192 }}, { year: 2014, followers: { twitter: 3511, tumblr: 415, instagram: 511 }}, { year: 2015, followers: { twitter: 3619, tumblr: 492, instagram: 1014 }}, { year: 2016, followers: { twitter: 4046, tumblr: 543, instagram: 2066 }}, { year: 2017, followers: { twitter: 3991, tumblr: 701, instagram: 3032 }}, { year: 2018, followers: { twitter: 3512, tumblr: 1522, instagram: 4512 }}, { year: 2019, followers: { twitter: 3274, tumblr: 1989, instagram: 4715 }}, { year: 2020, followers: { twitter: 2845, tumblr: 2040, instagram: 4801 }} ]; </script> <script> const svgMargin = 70, svgWidth = 700, svgHeight = 500, twitterColor = '#7cd9d1', tumblrColor = '#f6dd71', instagramColor = '#fd9b98'; const lineGraph = d3.select('.dashboard') .append('svg') .attr('width', svgWidth) .attr('height', svgHeight); const yScale = d3.scaleLinear() .domain([0, 5000]) .range([svgHeight - svgMargin, svgMargin]); const xScale = d3.scaleLinear() .domain([2012, 2020]) .range([svgMargin, svgWidth - svgMargin]); const yAxis = d3.axisLeft(yScale) .ticks(6, '~s'); const xAxis = d3.axisBottom(xScale) .tickFormat(d3.format('')) .tickPadding(10); lineGraph.append('g') .call(yAxis) .attr('transform', `translate(${svgMargin}, 0)`) .style('font', '10px verdana'); lineGraph.append('g') .call(xAxis) .attr('transform', `translate(0, ${svgHeight - svgMargin})`) .selectAll('text') .style('transform', 'translate(-12px, 0) rotate(-50deg)') .style('text-anchor', 'end') .style('cursor', 'pointer') .style('font', '10px verdana') const twitterLine = d3.line() .x(d => xScale(d.year)) .y(d => yScale(d.followers.twitter)); lineGraph.append('path') .attr('d', twitterLine(data)) .attr('stroke', twitterColor) .attr('stroke-width', 3) .attr('fill', 'transparent'); const tumblrLine = d3.line() .x(d => xScale(d.year)) .y(d => yScale(d.followers.tumblr)); lineGraph.append('path') .attr('d', tumblrLine(data)) .attr('stroke', tumblrColor) .attr('stroke-width', 3) .attr('fill', 'transparent'); const instagramLine = d3.line() .x(d => xScale(d.year)) .y(d => yScale(d.followers.instagram)); lineGraph.append('path') .attr('d', instagramLine(data)) .attr('stroke', instagramColor) .attr('stroke-width', 3) .attr('fill', 'transparent'); lineGraph.selectAll('twitter-circles') .data(data) .enter() .append('circle') .attr('cx', d => xScale(d.year)) </script> ``` # --solutions-- ```html <script> const data = [ { year: 2012, followers: { twitter: 2594, tumblr: 401, instagram: 83 }}, { year: 2013, followers: { twitter: 3049, tumblr: 440, instagram: 192 }}, { year: 2014, followers: { twitter: 3511, tumblr: 415, instagram: 511 }}, { year: 2015, followers: { twitter: 3619, tumblr: 492, instagram: 1014 }}, { year: 2016, followers: { twitter: 4046, tumblr: 543, instagram: 2066 }}, { year: 2017, followers: { twitter: 3991, tumblr: 701, instagram: 3032 }}, { year: 2018, followers: { twitter: 3512, tumblr: 1522, instagram: 4512 }}, { year: 2019, followers: { twitter: 3274, tumblr: 1989, instagram: 4715 }}, { year: 2020, followers: { twitter: 2845, tumblr: 2040, instagram: 4801 }} ]; </script> <script> const svgMargin = 70, svgWidth = 700, svgHeight = 500, twitterColor = '#7cd9d1', tumblrColor = '#f6dd71', instagramColor = '#fd9b98'; const lineGraph = d3.select('.dashboard') .append('svg') .attr('width', svgWidth) .attr('height', svgHeight); const yScale = d3.scaleLinear() .domain([0, 5000]) .range([svgHeight - svgMargin, svgMargin]); const xScale = d3.scaleLinear() .domain([2012, 2020]) .range([svgMargin, svgWidth - svgMargin]); const yAxis = d3.axisLeft(yScale) .ticks(6, '~s'); const xAxis = d3.axisBottom(xScale) .tickFormat(d3.format('')) .tickPadding(10); lineGraph.append('g') .call(yAxis) .attr('transform', `translate(${svgMargin}, 0)`) .style('font', '10px verdana'); lineGraph.append('g') .call(xAxis) .attr('transform', `translate(0, ${svgHeight - svgMargin})`) .selectAll('text') .style('transform', 'translate(-12px, 0) rotate(-50deg)') .style('text-anchor', 'end') .style('cursor', 'pointer') .style('font', '10px verdana') const twitterLine = d3.line() .x(d => xScale(d.year)) .y(d => yScale(d.followers.twitter)); lineGraph.append('path') .attr('d', twitterLine(data)) .attr('stroke', twitterColor) .attr('stroke-width', 3) .attr('fill', 'transparent'); const tumblrLine = d3.line() .x(d => xScale(d.year)) .y(d => yScale(d.followers.tumblr)); lineGraph.append('path') .attr('d', tumblrLine(data)) .attr('stroke', tumblrColor) .attr('stroke-width', 3) .attr('fill', 'transparent'); const instagramLine = d3.line() .x(d => xScale(d.year)) .y(d => yScale(d.followers.instagram)); lineGraph.append('path') .attr('d', instagramLine(data)) .attr('stroke', instagramColor) .attr('stroke-width', 3) .attr('fill', 'transparent'); lineGraph.selectAll('twitter-circles') .data(data) .enter() .append('circle') .attr('cx', d => xScale(d.year)) .attr('cy', d => yScale(d.followers.twitter)) </script> ```
curriculum/challenges/espanol/04-data-visualization/d3-dashboard/step-067.md
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/e5715b5948de9aa665f78ce0ad94eaef0a3f5a6d
[ 0.0001774785778252408, 0.0001731050870148465, 0.00016845088975969702, 0.00017322915664408356, 0.000002189298811572371 ]
{ "id": 6, "code_window": [ " },\n", " \"client/plugins/*\": {\n", " \"entry\": \"gatsby-node.js\"\n", " },\n", " // This monospace gives a few unused files, so as not to make the node.js-find-unused workflow fail this is still commented out\n", " // Also try --production to find more unused files.\n", " // \"tools/ui-components\": {\n", " // \"entry\": [\"src/index.ts!\", \"utils/gen-component-script.ts\"],\n", " // \"project\": [\"src/**/*.{ts,tsx}!\", \"utils/*.ts\"]\n", " // },\n", " \"tools/scripts/build\": {\n", " \"entry\": [\"*.ts\"]\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " // \"tools/ui-components\": {},\n" ], "file_path": "knip.jsonc", "type": "replace", "edit_start_line_idx": 31 }
--- id: 615f575b50b91e72af079480 title: Step 35 challengeType: 0 dashedName: step-35 --- # --description-- Crea un nuovo selettore `.left-container p` impostando i margini superiore e inferiore a `-5px` e i margini di sinistra e di destra a `-2px`. Inoltre imposta `font-size` a `2em` e `font-weight` a `700`. # --hints-- Dovresti avere un nuovo selettore `.left-container p`. ```js assert(new __helpers.CSSHelp(document).getStyle('.left-container p')); ``` Il nuovo selettore `.left-container p` dovrebbe avere una proprietà `margin` con il valore `-5px -2px`. ```js assert.equal(new __helpers.CSSHelp(document).getStyle('.left-container p')?.marginTop, '-5px'); assert.equal(new __helpers.CSSHelp(document).getStyle('.left-container p')?.marginBottom, '-5px'); assert.equal(new __helpers.CSSHelp(document).getStyle('.left-container p')?.marginLeft, '-2px'); assert.equal(new __helpers.CSSHelp(document).getStyle('.left-container p')?.marginRight, '-2px'); ``` Il nuovo selettore `.left-container p` dovrebbe avere una proprietà `font-size` con il valore `2em`. ```js assert(new __helpers.CSSHelp(document).getStyle('.left-container p')?.fontSize === '2em'); ``` Il nuovo selettore `.left-container p` dovrebbe avere una proprietà `font-weight` con il valore `700`. ```js assert(new __helpers.CSSHelp(document).getStyle('.left-container p')?.fontWeight === '700'); ``` # --seed-- ## --seed-contents-- ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Nutrition Label</title> <link href="https://fonts.googleapis.com/css?family=Open+Sans:400,700,800" rel="stylesheet"> <link href="./styles.css" rel="stylesheet"> </head> <body> <div class="label"> <header> <h1 class="bold">Nutrition Facts</h1> <div class="divider"></div> <p>8 servings per container</p> <p class="bold">Serving size <span>2/3 cup (55g)</span></p> </header> <div class="divider large"></div> <div class="calories-info"> <div class="left-container"> <h2 class="bold small-text">Amount per serving</h2> <p>Calories</p> </div> <span>230</span> </div> </div> </body> </html> ``` ```css * { box-sizing: border-box; } html { font-size: 16px; } body { font-family: 'Open Sans', sans-serif; } .label { border: 2px solid black; width: 270px; margin: 20px auto; padding: 0 7px; } header h1 { text-align: center; margin: -4px 0; letter-spacing: 0.15px } p { margin: 0; display: flex; justify-content: space-between; } .divider { border-bottom: 1px solid #888989; margin: 2px 0; } .bold { font-weight: 800; } .large { height: 10px; } .large, .medium { background-color: black; border: 0; } .small-text { font-size: 0.85rem; } .calories-info { display: flex; justify-content: space-between; align-items: flex-end; } .calories-info h2 { margin: 0; } --fcc-editable-region-- --fcc-editable-region-- ```
curriculum/challenges/italian/14-responsive-web-design-22/learn-typography-by-building-a-nutrition-label/615f575b50b91e72af079480.md
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/e5715b5948de9aa665f78ce0ad94eaef0a3f5a6d
[ 0.00017515469517093152, 0.00016992553719319403, 0.00016370225057471544, 0.0001702419394860044, 0.000002692214366106782 ]
{ "id": 7, "code_window": [ " \"format:curriculum:prettier\": \"prettier --write ./curriculum\",\n", " \"format:eslint\": \"eslint . --fix\",\n", " \"format:prettier\": \"prettier --write .\",\n", " \"knip\": \"pnpm dlx knip --include files\",\n", " \"knip:all\": \"pnpm dlx knip\",\n", " \"prelint\": \"pnpm run -F=client predevelop\",\n", " \"lint\": \"npm-run-all create:* -p lint:*\",\n", " \"lint:challenges\": \"cd ./curriculum && pnpm run lint\",\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " \"knip\": \"pnpm dlx knip@1 --include files\",\n", " \"knip:all\": \"pnpm dlx knip@1\",\n" ], "file_path": "package.json", "type": "replace", "edit_start_line_idx": 64 }
{ "name": "@freecodecamp/freecodecamp", "version": "0.0.1", "description": "The freeCodeCamp.org open-source codebase and curriculum", "license": "BSD-3-Clause", "private": true, "engines": { "node": ">=16", "pnpm": "7" }, "repository": { "type": "git", "url": "git+https://github.com/freeCodeCamp/freeCodeCamp.git" }, "bugs": { "url": "https://github.com/freeCodeCamp/freeCodeCamp/issues" }, "homepage": "https://github.com/freeCodeCamp/freeCodeCamp#readme", "author": "freeCodeCamp <[email protected]>", "main": "none", "scripts": { "audit-challenges": "pnpm run create:config && ts-node tools/challenge-auditor/index.ts", "analyze-bundle": "webpack-bundle-analyzer", "prebuild": "npm-run-all create:*", "build": "npm-run-all -p build:*", "build-workers": "cd ./client && pnpm run prebuild", "build:client": "cd ./client && pnpm run build", "build:curriculum": "cd ./curriculum && pnpm run build", "build:server": "cd ./api-server && pnpm run build", "challenge-editor": "npm-run-all -p challenge-editor:*", "challenge-editor:client": "cd ./tools/challenge-editor/client && pnpm start", "challenge-editor:server": "cd ./tools/challenge-editor/api && pnpm start", "clean": "npm-run-all -p clean:client clean:server clean:curriculum --serial clean:packages", "clean-and-develop": "pnpm run clean && pnpm install && pnpm run develop", "clean:client": "cd ./client && pnpm run clean", "clean:curriculum": "rm -rf ./config/curriculum.json", "clean:packages": "rm -rf ./node_modules ./**/node_modules", "clean:server": "rm -rf ./api-server/lib", "create:config": "tsc -p config && pnpm run ensure-env && pnpm run download-trending", "create:utils": "tsc -p utils", "precypress": "node ./cypress-install.js", "cypress": "cypress", "cypress:dev:run": "pnpm run cypress run --spec cypress/e2e/default/**/*.{t,j}s", "cypress:dev:watch": "pnpm run cypress open", "cypress:install": "cypress install && echo 'for use with ./cypress-install.js'", "cypress:install-build-tools": "sh ./cypress-install.sh", "predevelop": "npm-run-all create:*", "develop": "npm-run-all build:curriculum -p develop:*", "develop:client": "pnpm run build:curriculum && cd ./client && pnpm run develop", "develop:server": "pnpm run predevelop && cd ./api-server && pnpm run develop", "docs:serve": "docsify serve ./docs -o --port 3400", "e2e": "pnpm run e2e:dev:run", "e2e:dev:run": "start-test develop 'localhost:3000/status/ping|localhost:8000' cypress:dev:run", "e2e:dev:watch": "start-test develop 'localhost:3000/status/ping|localhost:8000' cypress:dev:watch", "e2e:prd:run": "pnpm run build && start-test 'localhost:3000/status/ping|localhost:8000' cypress:dev:run", "e2e:prd:watch": "pnpm run build && start-test 'localhost:3000/status/ping|localhost:8000' cypress:dev:watch", "download-trending": "ts-node ./tools/scripts/build/download-trending.ts", "ensure-env": "cross-env DEBUG=fcc:* ts-node ./tools/scripts/build/ensure-env.ts", "format": "run-s format:eslint format:prettier", "format:curriculum": "run-s format:curriculum:eslint format:curriculum:prettier", "format:curriculum:eslint": "eslint ./curriculum --fix", "format:curriculum:prettier": "prettier --write ./curriculum", "format:eslint": "eslint . --fix", "format:prettier": "prettier --write .", "knip": "pnpm dlx knip --include files", "knip:all": "pnpm dlx knip", "prelint": "pnpm run -F=client predevelop", "lint": "npm-run-all create:* -p lint:*", "lint:challenges": "cd ./curriculum && pnpm run lint", "lint:js": "eslint --max-warnings 0 .", "lint:ts": "tsc && tsc -p config && tsc -p tools/ui-components && tsc -p utils", "lint:prettier": "prettier --list-different .", "reload:server": "pm2 reload api-server/ecosystem.config.js", "seed": "cross-env DEBUG=fcc:* node ./tools/scripts/seed/seed-demo-user", "seed:certified-user": "cross-env DEBUG=fcc:* node ./tools/scripts/seed/seed-demo-user certified-user", "serve:client": "cd ./client && pnpm run serve", "serve:client-ci": "cd ./client && pnpm run serve-ci", "start": "npm-run-all create:* -p develop:server serve:client", "start-ci": "npm-run-all create:* -p start:server serve:client-ci", "start:server": "pm2 start api-server/ecosystem.config.js", "storybook": "cd ./tools/ui-components && pnpm run storybook", "test": "run-s create:* build:curriculum build-workers test:*", "test:source": "jest", "test:curriculum": "cd ./curriculum && pnpm test", "test-api": "cd api && jest", "test-curriculum-full-output": "cd ./curriculum && pnpm run test:full-output", "test-client": "jest client", "test-config": "jest config", "test-curriculum-js": "jest curriculum", "test-server": "jest api-server", "test-tools": "jest tools", "test-utils": "jest utils", "test-ui-components": "jest tools/ui-components", "postinstall": "cypress cache prune", "prepare": "husky install" }, "dependencies": { "dotenv": "16.0.3", "invariant": "2.2.4", "pm2": "^5.2.2" }, "devDependencies": { "@babel/eslint-parser": "7.21.3", "@babel/plugin-proposal-function-bind": "7.18.9", "@babel/preset-env": "7.20.2", "@babel/preset-react": "7.18.6", "@babel/preset-typescript": "7.21.0", "@testing-library/cypress": "8.0.7", "@testing-library/dom": "8.20.0", "@testing-library/jest-dom": "5.16.5", "@testing-library/user-event": "13.5.0", "@types/jest": "27.5.2", "@types/lodash": "4.14.191", "@types/node": "18.15.3", "@types/store": "2.0.2", "babel-jest": "29.5.0", "babel-plugin-transform-imports": "2.0.0", "cross-env": "7.0.3", "cypress": "10.11.0", "cypress-plugin-stripe-elements": "1.0.2", "cypress-plugin-tab": "1.0.5", "docsify-cli": "4.4.4", "eslint": "7.32.0", "eslint-config-prettier": "8.7.0", "eslint-plugin-filenames-simple": "0.8.0", "eslint-plugin-import": "2.27.5", "eslint-plugin-jest-dom": "3.9.4", "eslint-plugin-jsx-a11y": "6.7.1", "eslint-plugin-no-only-tests": "2.6.0", "eslint-plugin-prefer-object-spread": "1.2.1", "eslint-plugin-react": "7.32.2", "eslint-plugin-react-hooks": "4.6.0", "eslint-plugin-testing-library": "4.12.4", "execa": "5.1.1", "husky": "8.0.3", "jest": "27.5.1", "js-yaml": "3.14.1", "lint-staged": "^13.1.0", "lodash": "4.17.21", "markdownlint": "0.27.0", "mock-fs": "5.2.0", "npm-run-all": "4.1.5", "prettier": "^2.8.0", "prismjs": "1.29.0", "process": "0.11.10", "start-server-and-test": "1.15.5", "store": "2.0.12", "ts-node": "10.9.1", "typescript": "4.9.5", "webpack-bundle-analyzer": "4.8.0", "yargs": "17.7.1" } }
package.json
1
https://github.com/freeCodeCamp/freeCodeCamp/commit/e5715b5948de9aa665f78ce0ad94eaef0a3f5a6d
[ 0.9924226403236389, 0.06244075670838356, 0.00016340703587047756, 0.00017256499268114567, 0.24012114107608795 ]
{ "id": 7, "code_window": [ " \"format:curriculum:prettier\": \"prettier --write ./curriculum\",\n", " \"format:eslint\": \"eslint . --fix\",\n", " \"format:prettier\": \"prettier --write .\",\n", " \"knip\": \"pnpm dlx knip --include files\",\n", " \"knip:all\": \"pnpm dlx knip\",\n", " \"prelint\": \"pnpm run -F=client predevelop\",\n", " \"lint\": \"npm-run-all create:* -p lint:*\",\n", " \"lint:challenges\": \"cd ./curriculum && pnpm run lint\",\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " \"knip\": \"pnpm dlx knip@1 --include files\",\n", " \"knip:all\": \"pnpm dlx knip@1\",\n" ], "file_path": "package.json", "type": "replace", "edit_start_line_idx": 64 }
--- id: 5900f40d1000cf542c50ff20 title: 'Problem 161: Triominoes' challengeType: 1 forumTopicId: 301795 dashedName: problem-161-triominoes --- # --description-- A triomino is a shape consisting of three squares joined via the edges. There are two basic forms: <img class="img-responsive center-block" alt="two basic triominoes forms" src="https://cdn.freecodecamp.org/curriculum/project-euler/triominoes-1.gif" style="background-color: white; padding: 10px;" /> If all possible orientations are taken into account there are six: <img class="img-responsive center-block" alt="triominoes forms including orientation" src="https://cdn.freecodecamp.org/curriculum/project-euler/triominoes-2.gif" style="background-color: white; padding: 10px;" /> Any n by m grid for which nxm is divisible by 3 can be tiled with triominoes. If we consider tilings that can be obtained by reflection or rotation from another tiling as different there are 41 ways a 2 by 9 grid can be tiled with triominoes: <img class="img-responsive center-block" alt="animation showing 41 ways of filling 2x9 grid with triominoes" src="https://cdn.freecodecamp.org/curriculum/project-euler/triominoes-3.gif" style="background-color: white; padding: 10px;" /> In how many ways can a 9 by 12 grid be tiled in this way by triominoes? # --hints-- `triominoes()` should return `20574308184277972`. ```js assert.strictEqual(triominoes(), 20574308184277972); ``` # --seed-- ## --seed-contents-- ```js function triominoes() { return true; } triominoes(); ``` # --solutions-- ```js // solution required ```
curriculum/challenges/chinese-traditional/10-coding-interview-prep/project-euler/problem-161-triominoes.md
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/e5715b5948de9aa665f78ce0ad94eaef0a3f5a6d
[ 0.00017438844952266663, 0.0001680497662164271, 0.00016280300042126328, 0.0001671994396019727, 0.000004333825472713215 ]
{ "id": 7, "code_window": [ " \"format:curriculum:prettier\": \"prettier --write ./curriculum\",\n", " \"format:eslint\": \"eslint . --fix\",\n", " \"format:prettier\": \"prettier --write .\",\n", " \"knip\": \"pnpm dlx knip --include files\",\n", " \"knip:all\": \"pnpm dlx knip\",\n", " \"prelint\": \"pnpm run -F=client predevelop\",\n", " \"lint\": \"npm-run-all create:* -p lint:*\",\n", " \"lint:challenges\": \"cd ./curriculum && pnpm run lint\",\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " \"knip\": \"pnpm dlx knip@1 --include files\",\n", " \"knip:all\": \"pnpm dlx knip@1\",\n" ], "file_path": "package.json", "type": "replace", "edit_start_line_idx": 64 }
--- id: 567af2437cbaa8c51670a16c title: Objekte auf Eigenschaften prüfen challengeType: 1 forumTopicId: 18324 dashedName: testing-objects-for-properties --- # --description-- Manchmal ist es nützlich zu prüfen, ob die Eigenschaft eines bestimmten Objekts existiert oder nicht. Wir können die Methode `.hasOwnProperty(propname)` von Objekten verwenden, um festzustellen, ob das Objekt den angegebenen Eigenschaftsnamen enthält. `.hasOwnProperty()` gibt `true` oder `false` zurück, wenn die Eigenschaft gefunden wird oder nicht. **Beispiel** ```js const myObj = { top: "hat", bottom: "pants" }; myObj.hasOwnProperty("top"); myObj.hasOwnProperty("middle"); ``` Die erste `hasOwnProperty` gibt `true` zurück, während die zweite `false` zurückgibt. # --instructions-- Ändere die Funktion `checkObj` so, dass sie prüft, ob ein an die Funktion übergebenes Objekt (`obj`) eine bestimmte Eigenschaft enthält (`checkProp`). Wenn die Eigenschaft gefunden wird, wird der Wert der Eigenschaft zurückgegeben. Wenn nicht, wird `"Not Found"` zurückgegeben. # --hints-- `checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "gift")` sollte den String `pony` zurückgeben. ```js assert( checkObj({ gift: 'pony', pet: 'kitten', bed: 'sleigh' }, 'gift') === 'pony' ); ``` `checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "pet")` sollte den String `kitten` zurückgeben. ```js assert( checkObj({ gift: 'pony', pet: 'kitten', bed: 'sleigh' }, 'pet') === 'kitten' ); ``` `checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "house")` sollte den String `Not Found` zurückgeben. ```js assert( checkObj({ gift: 'pony', pet: 'kitten', bed: 'sleigh' }, 'house') === 'Not Found' ); ``` `checkObj({city: "Seattle"}, "city")` sollte den String `Seattle` zurückgeben. ```js assert(checkObj({ city: 'Seattle' }, 'city') === 'Seattle'); ``` `checkObj({city: "Seattle"}, "district")` sollte den String `Not Found` zurückgeben. ```js assert(checkObj({ city: 'Seattle' }, 'district') === 'Not Found'); ``` `checkObj({pet: "kitten", bed: "sleigh"}, "gift")` sollte den String `Not Found` zurückgeben. ```js assert(checkObj({ pet: 'kitten', bed: 'sleigh' }, 'gift') === 'Not Found'); ``` # --seed-- ## --seed-contents-- ```js function checkObj(obj, checkProp) { // Only change code below this line return "Change Me!"; // Only change code above this line } ``` # --solutions-- ```js function checkObj(obj, checkProp) { if(obj.hasOwnProperty(checkProp)) { return obj[checkProp]; } else { return "Not Found"; } } ```
curriculum/challenges/german/02-javascript-algorithms-and-data-structures/basic-javascript/testing-objects-for-properties.md
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/e5715b5948de9aa665f78ce0ad94eaef0a3f5a6d
[ 0.00017710834799800068, 0.00017318014579359442, 0.00016836257418617606, 0.0001735375844873488, 0.0000026706109110818943 ]
{ "id": 7, "code_window": [ " \"format:curriculum:prettier\": \"prettier --write ./curriculum\",\n", " \"format:eslint\": \"eslint . --fix\",\n", " \"format:prettier\": \"prettier --write .\",\n", " \"knip\": \"pnpm dlx knip --include files\",\n", " \"knip:all\": \"pnpm dlx knip\",\n", " \"prelint\": \"pnpm run -F=client predevelop\",\n", " \"lint\": \"npm-run-all create:* -p lint:*\",\n", " \"lint:challenges\": \"cd ./curriculum && pnpm run lint\",\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " \"knip\": \"pnpm dlx knip@1 --include files\",\n", " \"knip:all\": \"pnpm dlx knip@1\",\n" ], "file_path": "package.json", "type": "replace", "edit_start_line_idx": 64 }
--- id: 5900f4021000cf542c50ff14 title: 'Problem 148: Exploring Pascal''s triangle' challengeType: 1 forumTopicId: 301777 dashedName: problem-148-exploring-pascals-triangle --- # --description-- We can easily verify that none of the entries in the first seven rows of Pascal's triangle are divisible by 7: ```markup 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 ``` However, if we check the first one hundred rows, we will find that only 2361 of the 5050 entries are not divisible by 7. # --instructions-- Find the number of entries which are not divisible by 7 in the first one billion (${10}^9$) rows of Pascal's triangle. # --hints-- `entriesOfPascalsTriangle()` should return `2129970655314432`. ```js assert.strictEqual(entriesOfPascalsTriangle(), 2129970655314432); ``` # --seed-- ## --seed-contents-- ```js function entriesOfPascalsTriangle() { return true; } entriesOfPascalsTriangle(); ``` # --solutions-- ```js // solution required ```
curriculum/challenges/german/10-coding-interview-prep/project-euler/problem-148-exploring-pascals-triangle.md
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/e5715b5948de9aa665f78ce0ad94eaef0a3f5a6d
[ 0.00026801429339684546, 0.00018555614224169403, 0.0001640600967220962, 0.0001700773136690259, 0.00003697038846439682 ]
{ "id": 0, "code_window": [ "\tuse std::os::unix::fs::MetadataExt;\n", "\n", "\tlet metadata = from.metadata()?;\n", "\tfs::set_permissions(&to, metadata.permissions())?;\n", "\n", "\t// based on coreutils' chown https://github.com/uutils/coreutils/blob/72b4629916abe0852ad27286f4e307fbca546b6e/src/chown/chown.rs#L266-L281\n", "\tlet s = std::ffi::CString::new(to.as_os_str().as_bytes()).unwrap();\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tfs::set_permissions(to, metadata.permissions())?;\n" ], "file_path": "cli/src/self_update.rs", "type": "replace", "edit_start_line_idx": 152 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ use std::{fs, path::Path, process::Command}; use tempfile::tempdir; use crate::{ constants::{VSCODE_CLI_COMMIT, VSCODE_CLI_QUALITY}, options::Quality, update_service::{unzip_downloaded_release, Platform, Release, TargetKind, UpdateService}, util::{ errors::{wrap, AnyError, CorruptDownload, UpdatesNotConfigured}, http, io::{ReportCopyProgress, SilentCopyProgress}, }, }; pub struct SelfUpdate<'a> { commit: &'static str, quality: Quality, platform: Platform, update_service: &'a UpdateService, } impl<'a> SelfUpdate<'a> { pub fn new(update_service: &'a UpdateService) -> Result<Self, AnyError> { let commit = VSCODE_CLI_COMMIT .ok_or_else(|| UpdatesNotConfigured("unknown build commit".to_string()))?; let quality = VSCODE_CLI_QUALITY .ok_or_else(|| UpdatesNotConfigured("no configured quality".to_string())) .and_then(|q| Quality::try_from(q).map_err(UpdatesNotConfigured))?; let platform = Platform::env_default().ok_or_else(|| { UpdatesNotConfigured("Unknown platform, please report this error".to_string()) })?; Ok(Self { commit, quality, platform, update_service, }) } /// Gets the current release pub async fn get_current_release(&self) -> Result<Release, AnyError> { self.update_service .get_latest_commit(self.platform, TargetKind::Cli, self.quality) .await } /// Gets whether the given release is what this CLI is built against pub fn is_up_to_date_with(&self, release: &Release) -> bool { release.commit == self.commit } /// Updates the CLI to the given release. pub async fn do_update( &self, release: &Release, progress: impl ReportCopyProgress, ) -> Result<(), AnyError> { // 1. Download the archive into a temporary directory let tempdir = tempdir().map_err(|e| wrap(e, "Failed to create temp dir"))?; let archive_path = tempdir.path().join("archive"); let stream = self.update_service.get_download_stream(release).await?; http::download_into_file(&archive_path, progress, stream).await?; // 2. Unzip the archive and get the binary let target_path = std::env::current_exe().map_err(|e| wrap(e, "could not get current exe"))?; let staging_path = target_path.with_extension(".update"); let archive_contents_path = tempdir.path().join("content"); // unzipping the single binary is pretty small and fast--don't bother with passing progress unzip_downloaded_release(&archive_path, &archive_contents_path, SilentCopyProgress())?; copy_updated_cli_to_path(&archive_contents_path, &staging_path)?; // 3. Copy file metadata, make sure the new binary is executable\ copy_file_metadata(&target_path, &staging_path) .map_err(|e| wrap(e, "failed to set file permissions"))?; validate_cli_is_good(&staging_path)?; // Try to rename the old CLI to the tempdir, where it can get cleaned up by the // OS later. However, this can fail if the tempdir is on a different drive // than the installation dir. In this case just rename it to ".old". if fs::rename(&target_path, &tempdir.path().join("old-code-cli")).is_err() { fs::rename(&target_path, &target_path.with_extension(".old")) .map_err(|e| wrap(e, "failed to rename old CLI"))?; } fs::rename(&staging_path, &target_path) .map_err(|e| wrap(e, "failed to rename newly installed CLI"))?; Ok(()) } } fn validate_cli_is_good(exe_path: &Path) -> Result<(), AnyError> { let o = Command::new(exe_path) .args(["--version"]) .output() .map_err(|e| CorruptDownload(format!("could not execute new binary, aborting: {}", e)))?; if !o.status.success() { let msg = format!( "could not execute new binary, aborting. Stdout:\r\n\r\n{}\r\n\r\nStderr:\r\n\r\n{}", String::from_utf8_lossy(&o.stdout), String::from_utf8_lossy(&o.stderr), ); return Err(CorruptDownload(msg).into()); } Ok(()) } fn copy_updated_cli_to_path(unzipped_content: &Path, staging_path: &Path) -> Result<(), AnyError> { let unzipped_files = fs::read_dir(unzipped_content) .map_err(|e| wrap(e, "could not read update contents"))? .collect::<Vec<_>>(); if unzipped_files.len() != 1 { let msg = format!( "expected exactly one file in update, got {}", unzipped_files.len() ); return Err(CorruptDownload(msg).into()); } let archive_file = unzipped_files[0] .as_ref() .map_err(|e| wrap(e, "error listing update files"))?; fs::copy(&archive_file.path(), staging_path) .map_err(|e| wrap(e, "error copying to staging file"))?; Ok(()) } #[cfg(target_os = "windows")] fn copy_file_metadata(from: &Path, to: &Path) -> Result<(), std::io::Error> { let permissions = from.metadata()?.permissions(); fs::set_permissions(&to, permissions)?; Ok(()) } #[cfg(not(target_os = "windows"))] fn copy_file_metadata(from: &Path, to: &Path) -> Result<(), std::io::Error> { use std::os::unix::ffi::OsStrExt; use std::os::unix::fs::MetadataExt; let metadata = from.metadata()?; fs::set_permissions(&to, metadata.permissions())?; // based on coreutils' chown https://github.com/uutils/coreutils/blob/72b4629916abe0852ad27286f4e307fbca546b6e/src/chown/chown.rs#L266-L281 let s = std::ffi::CString::new(to.as_os_str().as_bytes()).unwrap(); let ret = unsafe { libc::chown(s.as_ptr(), metadata.uid(), metadata.gid()) }; if ret != 0 { return Err(std::io::Error::last_os_error()); } Ok(()) }
cli/src/self_update.rs
1
https://github.com/microsoft/vscode/commit/fe5f564db16038785936282be7f6b871f34b8bd1
[ 0.9983710646629333, 0.11593978852033615, 0.00016398081788793206, 0.00016880655311979353, 0.31690460443496704 ]
{ "id": 0, "code_window": [ "\tuse std::os::unix::fs::MetadataExt;\n", "\n", "\tlet metadata = from.metadata()?;\n", "\tfs::set_permissions(&to, metadata.permissions())?;\n", "\n", "\t// based on coreutils' chown https://github.com/uutils/coreutils/blob/72b4629916abe0852ad27286f4e307fbca546b6e/src/chown/chown.rs#L266-L281\n", "\tlet s = std::ffi::CString::new(to.as_os_str().as_bytes()).unwrap();\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tfs::set_permissions(to, metadata.permissions())?;\n" ], "file_path": "cli/src/self_update.rs", "type": "replace", "edit_start_line_idx": 152 }
{ "registrations": [ { "component": { "type": "git", "git": { "name": "jeff-hykin/better-cpp-syntax", "repositoryUrl": "https://github.com/jeff-hykin/better-cpp-syntax", "commitHash": "1866de22c09781cbceacc2c98063f7bf77b1ca62" } }, "license": "MIT", "version": "1.16.1", "description": "The original JSON grammars were derived from https://github.com/atom/language-c which was originally converted from the C TextMate bundle https://github.com/textmate/c.tmbundle." }, { "component": { "type": "git", "git": { "name": "jeff-hykin/better-c-syntax", "repositoryUrl": "https://github.com/jeff-hykin/better-c-syntax", "commitHash": "34712a6106a4ffb0a04d2fa836fd28ff6c5849a4" } }, "license": "MIT", "version": "1.13.2", "description": "The original JSON grammars were derived from https://github.com/atom/language-c which was originally converted from the C TextMate bundle https://github.com/textmate/c.tmbundle." }, { "component": { "type": "git", "git": { "name": "textmate/c.tmbundle", "repositoryUrl": "https://github.com/textmate/c.tmbundle", "commitHash": "60daf83b9d45329524f7847a75e9298b3aae5805" } }, "licenseDetail": [ "Copyright (c) textmate-c.tmbundle authors", "", "If not otherwise specified (see below), files in this repository fall under the following license:", "", "Permission to copy, use, modify, sell and distribute this", "software is granted. This software is provided \"as is\" without", "express or implied warranty, and with no claim as to its", "suitability for any purpose.", "", "An exception is made for files in readable text which contain their own license information,", "or files where an accompanying file exists (in the same directory) with a \"-license\" suffix added", "to the base-name name of the original file, and an extension of txt, html, or similar. For example", "\"tidy\" is accompanied by \"tidy-license.txt\"." ], "license": "TextMate Bundle License", "version": "0.0.0" }, { "component": { "type": "git", "git": { "name": "NVIDIA/cuda-cpp-grammar", "repositoryUrl": "https://github.com/NVIDIA/cuda-cpp-grammar", "commitHash": "81e88eaec5170aa8585736c63627c73e3589998c" } }, "license": "MIT", "version": "0.0.0", "description": "The file syntaxes/cuda-cpp.tmLanguage.json was derived from https://github.com/jeff-hykin/cpp-textmate-grammar, which was derived from https://github.com/atom/language-c, which was originally converted from the C TextMate bundle https://github.com/textmate/c.tmbundle." } ], "version": 1 }
extensions/cpp/cgmanifest.json
0
https://github.com/microsoft/vscode/commit/fe5f564db16038785936282be7f6b871f34b8bd1
[ 0.00017273190314881504, 0.0001697127299848944, 0.00016450765542685986, 0.00017072263290174305, 0.0000027575724743655883 ]
{ "id": 0, "code_window": [ "\tuse std::os::unix::fs::MetadataExt;\n", "\n", "\tlet metadata = from.metadata()?;\n", "\tfs::set_permissions(&to, metadata.permissions())?;\n", "\n", "\t// based on coreutils' chown https://github.com/uutils/coreutils/blob/72b4629916abe0852ad27286f4e307fbca546b6e/src/chown/chown.rs#L266-L281\n", "\tlet s = std::ffi::CString::new(to.as_os_str().as_bytes()).unwrap();\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tfs::set_permissions(to, metadata.permissions())?;\n" ], "file_path": "cli/src/self_update.rs", "type": "replace", "edit_start_line_idx": 152 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Emitter } from 'vs/base/common/event'; import { combinedDisposable, Disposable, IDisposable } from 'vs/base/common/lifecycle'; import { ResourceMap } from 'vs/base/common/map'; import { isEqual } from 'vs/base/common/resources'; import { withNullAsUndefined } from 'vs/base/common/types'; import { URI } from 'vs/base/common/uri'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { ILogService } from 'vs/platform/log/common/log'; import { NotebookTextModel } from 'vs/workbench/contrib/notebook/common/model/notebookTextModel'; import { CellEditType, CellUri, ICellEditOperation, NotebookCellExecutionState, NotebookCellInternalMetadata, NotebookTextModelWillAddRemoveEvent } from 'vs/workbench/contrib/notebook/common/notebookCommon'; import { CellExecutionUpdateType, INotebookExecutionService } from 'vs/workbench/contrib/notebook/common/notebookExecutionService'; import { ICellExecuteUpdate, ICellExecutionComplete, ICellExecutionStateChangedEvent, ICellExecutionStateUpdate, IFailedCellInfo, INotebookCellExecution, INotebookExecutionStateService, INotebookFailStateChangedEvent } from 'vs/workbench/contrib/notebook/common/notebookExecutionStateService'; import { INotebookKernelService } from 'vs/workbench/contrib/notebook/common/notebookKernelService'; import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService'; export class NotebookExecutionStateService extends Disposable implements INotebookExecutionStateService { declare _serviceBrand: undefined; private readonly _executions = new ResourceMap<Map<number, CellExecution>>(); private readonly _notebookListeners = new ResourceMap<NotebookExecutionListeners>(); private readonly _cellListeners = new ResourceMap<IDisposable>(); private readonly _lastFailedCells = new ResourceMap<IFailedCellInfo>(); private readonly _onDidChangeCellExecution = this._register(new Emitter<ICellExecutionStateChangedEvent>()); onDidChangeCellExecution = this._onDidChangeCellExecution.event; private readonly _onDidChangeLastRunFailState = this._register(new Emitter<INotebookFailStateChangedEvent>()); onDidChangeLastRunFailState = this._onDidChangeLastRunFailState.event; constructor( @IInstantiationService private readonly _instantiationService: IInstantiationService, @ILogService private readonly _logService: ILogService, @INotebookService private readonly _notebookService: INotebookService, ) { super(); } getLastFailedCellForNotebook(notebook: URI): number | undefined { const failedCell = this._lastFailedCells.get(notebook); return failedCell?.visible ? failedCell.cellHandle : undefined; } forceCancelNotebookExecutions(notebookUri: URI): void { const notebookExecutions = this._executions.get(notebookUri); if (!notebookExecutions) { return; } for (const exe of notebookExecutions.values()) { this._onCellExecutionDidComplete(notebookUri, exe.cellHandle, exe); } } getCellExecution(cellUri: URI): INotebookCellExecution | undefined { const parsed = CellUri.parse(cellUri); if (!parsed) { throw new Error(`Not a cell URI: ${cellUri}`); } const exeMap = this._executions.get(parsed.notebook); if (exeMap) { return exeMap.get(parsed.handle); } return undefined; } getCellExecutionsForNotebook(notebook: URI): INotebookCellExecution[] { const exeMap = this._executions.get(notebook); return exeMap ? Array.from(exeMap.values()) : []; } getCellExecutionsByHandleForNotebook(notebook: URI): Map<number, INotebookCellExecution> | undefined { const exeMap = this._executions.get(notebook); return withNullAsUndefined(exeMap); } private _onCellExecutionDidChange(notebookUri: URI, cellHandle: number, exe: CellExecution): void { this._onDidChangeCellExecution.fire(new NotebookExecutionEvent(notebookUri, cellHandle, exe)); } private _onCellExecutionDidComplete(notebookUri: URI, cellHandle: number, exe: CellExecution, lastRunSuccess?: boolean): void { const notebookExecutions = this._executions.get(notebookUri); if (!notebookExecutions) { this._logService.debug(`NotebookExecutionStateService#_onCellExecutionDidComplete - unknown notebook ${notebookUri.toString()}`); return; } exe.dispose(); const cellUri = CellUri.generate(notebookUri, cellHandle); this._cellListeners.get(cellUri)?.dispose(); this._cellListeners.delete(cellUri); notebookExecutions.delete(cellHandle); if (notebookExecutions.size === 0) { this._executions.delete(notebookUri); this._notebookListeners.get(notebookUri)?.dispose(); this._notebookListeners.delete(notebookUri); } if (lastRunSuccess !== undefined) { if (lastRunSuccess) { this._clearLastFailedCell(notebookUri); } else { this._setLastFailedCell(notebookUri, cellHandle); } } this._onDidChangeCellExecution.fire(new NotebookExecutionEvent(notebookUri, cellHandle)); } createCellExecution(notebookUri: URI, cellHandle: number): INotebookCellExecution { const notebook = this._notebookService.getNotebookTextModel(notebookUri); if (!notebook) { throw new Error(`Notebook not found: ${notebookUri.toString()}`); } let notebookExecutionMap = this._executions.get(notebookUri); if (!notebookExecutionMap) { const listeners = this._instantiationService.createInstance(NotebookExecutionListeners, notebookUri); this._notebookListeners.set(notebookUri, listeners); notebookExecutionMap = new Map<number, CellExecution>(); this._executions.set(notebookUri, notebookExecutionMap); } let exe = notebookExecutionMap.get(cellHandle); if (!exe) { exe = this._createNotebookCellExecution(notebook, cellHandle); notebookExecutionMap.set(cellHandle, exe); exe.initialize(); this._onDidChangeCellExecution.fire(new NotebookExecutionEvent(notebookUri, cellHandle, exe)); } return exe; } private _createNotebookCellExecution(notebook: NotebookTextModel, cellHandle: number): CellExecution { const notebookUri = notebook.uri; const exe: CellExecution = this._instantiationService.createInstance(CellExecution, cellHandle, notebook); const disposable = combinedDisposable( exe.onDidUpdate(() => this._onCellExecutionDidChange(notebookUri, cellHandle, exe)), exe.onDidComplete(lastRunSuccess => this._onCellExecutionDidComplete(notebookUri, cellHandle, exe, lastRunSuccess))); this._cellListeners.set(CellUri.generate(notebookUri, cellHandle), disposable); return exe; } private _setLastFailedCell(notebookURI: URI, cellHandle: number): void { const prevLastFailedCellInfo = this._lastFailedCells.get(notebookURI); const notebook = this._notebookService.getNotebookTextModel(notebookURI); if (!notebook) { return; } const newLastFailedCellInfo: IFailedCellInfo = { cellHandle: cellHandle, disposable: prevLastFailedCellInfo ? prevLastFailedCellInfo.disposable : this._getFailedCellListener(notebook), visible: true }; this._lastFailedCells.set(notebookURI, newLastFailedCellInfo); this._onDidChangeLastRunFailState.fire({ visible: true, notebook: notebookURI }); } private _setLastFailedCellVisibility(notebookURI: URI, visible: boolean): void { const lastFailedCellInfo = this._lastFailedCells.get(notebookURI); if (lastFailedCellInfo) { this._lastFailedCells.set(notebookURI, { cellHandle: lastFailedCellInfo.cellHandle, disposable: lastFailedCellInfo.disposable, visible: visible, }); } this._onDidChangeLastRunFailState.fire({ visible: visible, notebook: notebookURI }); } private _clearLastFailedCell(notebookURI: URI): void { const lastFailedCellInfo = this._lastFailedCells.get(notebookURI); if (lastFailedCellInfo) { lastFailedCellInfo.disposable?.dispose(); this._lastFailedCells.delete(notebookURI); } this._onDidChangeLastRunFailState.fire({ visible: false, notebook: notebookURI }); } private _getFailedCellListener(notebook: NotebookTextModel): IDisposable { return notebook.onWillAddRemoveCells((e: NotebookTextModelWillAddRemoveEvent) => { const lastFailedCell = this._lastFailedCells.get(notebook.uri)?.cellHandle; if (lastFailedCell !== undefined) { const lastFailedCellPos = notebook.cells.findIndex(c => c.handle === lastFailedCell); e.rawEvent.changes.forEach(([start, deleteCount, addedCells]) => { if (deleteCount) { if (lastFailedCellPos >= start && lastFailedCellPos < start + deleteCount) { this._setLastFailedCellVisibility(notebook.uri, false); } } if (addedCells.some(cell => cell.handle === lastFailedCell)) { this._setLastFailedCellVisibility(notebook.uri, true); } }); } }); } override dispose(): void { super.dispose(); this._executions.forEach(executionMap => { executionMap.forEach(execution => execution.dispose()); executionMap.clear(); }); this._executions.clear(); this._cellListeners.forEach(disposable => disposable.dispose()); this._notebookListeners.forEach(disposable => disposable.dispose()); this._lastFailedCells.forEach(elem => elem.disposable.dispose()); } } class NotebookExecutionEvent implements ICellExecutionStateChangedEvent { constructor( readonly notebook: URI, readonly cellHandle: number, readonly changed?: CellExecution ) { } affectsCell(cell: URI): boolean { const parsedUri = CellUri.parse(cell); return !!parsedUri && isEqual(this.notebook, parsedUri.notebook) && this.cellHandle === parsedUri.handle; } affectsNotebook(notebook: URI): boolean { return isEqual(this.notebook, notebook); } } class NotebookExecutionListeners extends Disposable { private readonly _notebookModel: NotebookTextModel; constructor( notebook: URI, @INotebookService private readonly _notebookService: INotebookService, @INotebookKernelService private readonly _notebookKernelService: INotebookKernelService, @INotebookExecutionService private readonly _notebookExecutionService: INotebookExecutionService, @INotebookExecutionStateService private readonly _notebookExecutionStateService: INotebookExecutionStateService, @ILogService private readonly _logService: ILogService, ) { super(); this._logService.debug(`NotebookExecution#ctor ${notebook.toString()}`); const notebookModel = this._notebookService.getNotebookTextModel(notebook); if (!notebookModel) { throw new Error('Notebook not found: ' + notebook); } this._notebookModel = notebookModel; this._register(this._notebookModel.onWillAddRemoveCells(e => this.onWillAddRemoveCells(e))); this._register(this._notebookModel.onWillDispose(() => this.onWillDisposeDocument())); } private cancelAll(): void { this._logService.debug(`NotebookExecutionListeners#cancelAll`); const exes = this._notebookExecutionStateService.getCellExecutionsForNotebook(this._notebookModel.uri); this._notebookExecutionService.cancelNotebookCellHandles(this._notebookModel, exes.map(exe => exe.cellHandle)); } private onWillDisposeDocument(): void { this._logService.debug(`NotebookExecution#onWillDisposeDocument`); this.cancelAll(); } private onWillAddRemoveCells(e: NotebookTextModelWillAddRemoveEvent): void { const notebookExes = this._notebookExecutionStateService.getCellExecutionsByHandleForNotebook(this._notebookModel.uri); const executingDeletedHandles = new Set<number>(); const pendingDeletedHandles = new Set<number>(); if (notebookExes) { e.rawEvent.changes.forEach(([start, deleteCount]) => { if (deleteCount) { const deletedHandles = this._notebookModel.cells.slice(start, start + deleteCount).map(c => c.handle); deletedHandles.forEach(h => { const exe = notebookExes.get(h); if (exe?.state === NotebookCellExecutionState.Executing) { executingDeletedHandles.add(h); } else if (exe) { pendingDeletedHandles.add(h); } }); } }); } if (executingDeletedHandles.size || pendingDeletedHandles.size) { const kernel = this._notebookKernelService.getSelectedOrSuggestedKernel(this._notebookModel); if (kernel) { const implementsInterrupt = kernel.implementsInterrupt; const handlesToCancel = implementsInterrupt ? [...executingDeletedHandles] : [...executingDeletedHandles, ...pendingDeletedHandles]; this._logService.debug(`NotebookExecution#onWillAddRemoveCells, ${JSON.stringify([...handlesToCancel])}`); if (handlesToCancel.length) { kernel.cancelNotebookCellExecution(this._notebookModel.uri, handlesToCancel); } } } } } function updateToEdit(update: ICellExecuteUpdate, cellHandle: number): ICellEditOperation { if (update.editType === CellExecutionUpdateType.Output) { return { editType: CellEditType.Output, handle: update.cellHandle, append: update.append, outputs: update.outputs, }; } else if (update.editType === CellExecutionUpdateType.OutputItems) { return { editType: CellEditType.OutputItems, items: update.items, append: update.append, outputId: update.outputId }; } else if (update.editType === CellExecutionUpdateType.ExecutionState) { const newInternalMetadata: Partial<NotebookCellInternalMetadata> = {}; if (typeof update.executionOrder !== 'undefined') { newInternalMetadata.executionOrder = update.executionOrder; } if (typeof update.runStartTime !== 'undefined') { newInternalMetadata.runStartTime = update.runStartTime; } return { editType: CellEditType.PartialInternalMetadata, handle: cellHandle, internalMetadata: newInternalMetadata }; } throw new Error('Unknown cell update type'); } class CellExecution extends Disposable implements INotebookCellExecution { private readonly _onDidUpdate = this._register(new Emitter<void>()); readonly onDidUpdate = this._onDidUpdate.event; private readonly _onDidComplete = this._register(new Emitter<boolean | undefined>()); readonly onDidComplete = this._onDidComplete.event; private _state: NotebookCellExecutionState = NotebookCellExecutionState.Unconfirmed; get state() { return this._state; } get notebook(): URI { return this._notebookModel.uri; } private _didPause = false; get didPause() { return this._didPause; } private _isPaused = false; get isPaused() { return this._isPaused; } constructor( readonly cellHandle: number, private readonly _notebookModel: NotebookTextModel, @ILogService private readonly _logService: ILogService, ) { super(); this._logService.debug(`CellExecution#ctor ${this.getCellLog()}`); } initialize() { const startExecuteEdit: ICellEditOperation = { editType: CellEditType.PartialInternalMetadata, handle: this.cellHandle, internalMetadata: { runStartTime: null, runEndTime: null, lastRunSuccess: null, executionOrder: null, } }; this._applyExecutionEdits([startExecuteEdit]); } private getCellLog(): string { return `${this._notebookModel.uri.toString()}, ${this.cellHandle}`; } private logUpdates(updates: ICellExecuteUpdate[]): void { const updateTypes = updates.map(u => CellExecutionUpdateType[u.editType]).join(', '); this._logService.debug(`CellExecution#updateExecution ${this.getCellLog()}, [${updateTypes}]`); } confirm() { this._logService.debug(`CellExecution#confirm ${this.getCellLog()}`); this._state = NotebookCellExecutionState.Pending; this._onDidUpdate.fire(); } update(updates: ICellExecuteUpdate[]): void { this.logUpdates(updates); if (updates.some(u => u.editType === CellExecutionUpdateType.ExecutionState)) { this._state = NotebookCellExecutionState.Executing; } if (!this._didPause && updates.some(u => u.editType === CellExecutionUpdateType.ExecutionState && u.didPause)) { this._didPause = true; } const lastIsPausedUpdate = [...updates].reverse().find(u => u.editType === CellExecutionUpdateType.ExecutionState && typeof u.isPaused === 'boolean'); if (lastIsPausedUpdate) { this._isPaused = (lastIsPausedUpdate as ICellExecutionStateUpdate).isPaused!; } const cellModel = this._notebookModel.cells.find(c => c.handle === this.cellHandle); if (!cellModel) { this._logService.debug(`CellExecution#update, updating cell not in notebook: ${this._notebookModel.uri.toString()}, ${this.cellHandle}`); } else { const edits = updates.map(update => updateToEdit(update, this.cellHandle)); this._applyExecutionEdits(edits); } if (updates.some(u => u.editType === CellExecutionUpdateType.ExecutionState)) { this._onDidUpdate.fire(); } } complete(completionData: ICellExecutionComplete): void { const cellModel = this._notebookModel.cells.find(c => c.handle === this.cellHandle); if (!cellModel) { this._logService.debug(`CellExecution#complete, completing cell not in notebook: ${this._notebookModel.uri.toString()}, ${this.cellHandle}`); } else { const edit: ICellEditOperation = { editType: CellEditType.PartialInternalMetadata, handle: this.cellHandle, internalMetadata: { lastRunSuccess: completionData.lastRunSuccess, runStartTime: this._didPause ? null : cellModel.internalMetadata.runStartTime, runEndTime: this._didPause ? null : completionData.runEndTime, } }; this._applyExecutionEdits([edit]); } this._onDidComplete.fire(completionData.lastRunSuccess); } private _applyExecutionEdits(edits: ICellEditOperation[]): void { this._notebookModel.applyEdits(edits, true, undefined, () => undefined, undefined, false); } }
src/vs/workbench/contrib/notebook/browser/services/notebookExecutionStateServiceImpl.ts
0
https://github.com/microsoft/vscode/commit/fe5f564db16038785936282be7f6b871f34b8bd1
[ 0.00017702071636449546, 0.00017222980386577547, 0.00016631861217319965, 0.00017229566583409905, 0.0000021198791273491224 ]
{ "id": 0, "code_window": [ "\tuse std::os::unix::fs::MetadataExt;\n", "\n", "\tlet metadata = from.metadata()?;\n", "\tfs::set_permissions(&to, metadata.permissions())?;\n", "\n", "\t// based on coreutils' chown https://github.com/uutils/coreutils/blob/72b4629916abe0852ad27286f4e307fbca546b6e/src/chown/chown.rs#L266-L281\n", "\tlet s = std::ffi::CString::new(to.as_os_str().as_bytes()).unwrap();\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tfs::set_permissions(to, metadata.permissions())?;\n" ], "file_path": "cli/src/self_update.rs", "type": "replace", "edit_start_line_idx": 152 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { extensions } from 'vscode'; import { API as GitBaseAPI, GitBaseExtension } from './api/git-base'; export class GitBaseApi { private static _gitBaseApi: GitBaseAPI | undefined; static getAPI(): GitBaseAPI { if (!this._gitBaseApi) { const gitBaseExtension = extensions.getExtension<GitBaseExtension>('vscode.git-base')!.exports; const onDidChangeGitBaseExtensionEnablement = (enabled: boolean) => { this._gitBaseApi = enabled ? gitBaseExtension.getAPI(1) : undefined; }; gitBaseExtension.onDidChangeEnablement(onDidChangeGitBaseExtensionEnablement); onDidChangeGitBaseExtensionEnablement(gitBaseExtension.enabled); if (!this._gitBaseApi) { throw new Error('vscode.git-base extension is not enabled.'); } } return this._gitBaseApi; } }
extensions/git/src/git-base.ts
0
https://github.com/microsoft/vscode/commit/fe5f564db16038785936282be7f6b871f34b8bd1
[ 0.0001729855575831607, 0.00016949258861131966, 0.0001659408153500408, 0.0001695219543762505, 0.0000025735605504451087 ]
{ "id": 1, "code_window": [ ") -> Result<(), AnyError> {\n", "\tinfo!(log, \"Setting up server...\");\n", "\n", "\tunzip_downloaded_release(compressed_file, &paths.server_dir, SilentCopyProgress())?;\n", "\n", "\tmatch fs::remove_file(&compressed_file) {\n", "\t\tOk(()) => {}\n", "\t\tErr(e) => {\n", "\t\t\tif e.kind() != ErrorKind::NotFound {\n", "\t\t\t\treturn Err(AnyError::from(wrap(e, \"error removing downloaded file\")));\n", "\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tmatch fs::remove_file(compressed_file) {\n" ], "file_path": "cli/src/tunnels/code_server.rs", "type": "replace", "edit_start_line_idx": 354 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ use std::{fs, path::Path, process::Command}; use tempfile::tempdir; use crate::{ constants::{VSCODE_CLI_COMMIT, VSCODE_CLI_QUALITY}, options::Quality, update_service::{unzip_downloaded_release, Platform, Release, TargetKind, UpdateService}, util::{ errors::{wrap, AnyError, CorruptDownload, UpdatesNotConfigured}, http, io::{ReportCopyProgress, SilentCopyProgress}, }, }; pub struct SelfUpdate<'a> { commit: &'static str, quality: Quality, platform: Platform, update_service: &'a UpdateService, } impl<'a> SelfUpdate<'a> { pub fn new(update_service: &'a UpdateService) -> Result<Self, AnyError> { let commit = VSCODE_CLI_COMMIT .ok_or_else(|| UpdatesNotConfigured("unknown build commit".to_string()))?; let quality = VSCODE_CLI_QUALITY .ok_or_else(|| UpdatesNotConfigured("no configured quality".to_string())) .and_then(|q| Quality::try_from(q).map_err(UpdatesNotConfigured))?; let platform = Platform::env_default().ok_or_else(|| { UpdatesNotConfigured("Unknown platform, please report this error".to_string()) })?; Ok(Self { commit, quality, platform, update_service, }) } /// Gets the current release pub async fn get_current_release(&self) -> Result<Release, AnyError> { self.update_service .get_latest_commit(self.platform, TargetKind::Cli, self.quality) .await } /// Gets whether the given release is what this CLI is built against pub fn is_up_to_date_with(&self, release: &Release) -> bool { release.commit == self.commit } /// Updates the CLI to the given release. pub async fn do_update( &self, release: &Release, progress: impl ReportCopyProgress, ) -> Result<(), AnyError> { // 1. Download the archive into a temporary directory let tempdir = tempdir().map_err(|e| wrap(e, "Failed to create temp dir"))?; let archive_path = tempdir.path().join("archive"); let stream = self.update_service.get_download_stream(release).await?; http::download_into_file(&archive_path, progress, stream).await?; // 2. Unzip the archive and get the binary let target_path = std::env::current_exe().map_err(|e| wrap(e, "could not get current exe"))?; let staging_path = target_path.with_extension(".update"); let archive_contents_path = tempdir.path().join("content"); // unzipping the single binary is pretty small and fast--don't bother with passing progress unzip_downloaded_release(&archive_path, &archive_contents_path, SilentCopyProgress())?; copy_updated_cli_to_path(&archive_contents_path, &staging_path)?; // 3. Copy file metadata, make sure the new binary is executable\ copy_file_metadata(&target_path, &staging_path) .map_err(|e| wrap(e, "failed to set file permissions"))?; validate_cli_is_good(&staging_path)?; // Try to rename the old CLI to the tempdir, where it can get cleaned up by the // OS later. However, this can fail if the tempdir is on a different drive // than the installation dir. In this case just rename it to ".old". if fs::rename(&target_path, &tempdir.path().join("old-code-cli")).is_err() { fs::rename(&target_path, &target_path.with_extension(".old")) .map_err(|e| wrap(e, "failed to rename old CLI"))?; } fs::rename(&staging_path, &target_path) .map_err(|e| wrap(e, "failed to rename newly installed CLI"))?; Ok(()) } } fn validate_cli_is_good(exe_path: &Path) -> Result<(), AnyError> { let o = Command::new(exe_path) .args(["--version"]) .output() .map_err(|e| CorruptDownload(format!("could not execute new binary, aborting: {}", e)))?; if !o.status.success() { let msg = format!( "could not execute new binary, aborting. Stdout:\r\n\r\n{}\r\n\r\nStderr:\r\n\r\n{}", String::from_utf8_lossy(&o.stdout), String::from_utf8_lossy(&o.stderr), ); return Err(CorruptDownload(msg).into()); } Ok(()) } fn copy_updated_cli_to_path(unzipped_content: &Path, staging_path: &Path) -> Result<(), AnyError> { let unzipped_files = fs::read_dir(unzipped_content) .map_err(|e| wrap(e, "could not read update contents"))? .collect::<Vec<_>>(); if unzipped_files.len() != 1 { let msg = format!( "expected exactly one file in update, got {}", unzipped_files.len() ); return Err(CorruptDownload(msg).into()); } let archive_file = unzipped_files[0] .as_ref() .map_err(|e| wrap(e, "error listing update files"))?; fs::copy(&archive_file.path(), staging_path) .map_err(|e| wrap(e, "error copying to staging file"))?; Ok(()) } #[cfg(target_os = "windows")] fn copy_file_metadata(from: &Path, to: &Path) -> Result<(), std::io::Error> { let permissions = from.metadata()?.permissions(); fs::set_permissions(&to, permissions)?; Ok(()) } #[cfg(not(target_os = "windows"))] fn copy_file_metadata(from: &Path, to: &Path) -> Result<(), std::io::Error> { use std::os::unix::ffi::OsStrExt; use std::os::unix::fs::MetadataExt; let metadata = from.metadata()?; fs::set_permissions(&to, metadata.permissions())?; // based on coreutils' chown https://github.com/uutils/coreutils/blob/72b4629916abe0852ad27286f4e307fbca546b6e/src/chown/chown.rs#L266-L281 let s = std::ffi::CString::new(to.as_os_str().as_bytes()).unwrap(); let ret = unsafe { libc::chown(s.as_ptr(), metadata.uid(), metadata.gid()) }; if ret != 0 { return Err(std::io::Error::last_os_error()); } Ok(()) }
cli/src/self_update.rs
1
https://github.com/microsoft/vscode/commit/fe5f564db16038785936282be7f6b871f34b8bd1
[ 0.0005563836893998086, 0.00024251092690974474, 0.0001667774049565196, 0.00017740887415129691, 0.00011155800893902779 ]
{ "id": 1, "code_window": [ ") -> Result<(), AnyError> {\n", "\tinfo!(log, \"Setting up server...\");\n", "\n", "\tunzip_downloaded_release(compressed_file, &paths.server_dir, SilentCopyProgress())?;\n", "\n", "\tmatch fs::remove_file(&compressed_file) {\n", "\t\tOk(()) => {}\n", "\t\tErr(e) => {\n", "\t\t\tif e.kind() != ErrorKind::NotFound {\n", "\t\t\t\treturn Err(AnyError::from(wrap(e, \"error removing downloaded file\")));\n", "\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tmatch fs::remove_file(compressed_file) {\n" ], "file_path": "cli/src/tunnels/code_server.rs", "type": "replace", "edit_start_line_idx": 354 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./media/notificationsCenter'; import 'vs/css!./media/notificationsActions'; import { NOTIFICATIONS_BORDER, NOTIFICATIONS_CENTER_HEADER_FOREGROUND, NOTIFICATIONS_CENTER_HEADER_BACKGROUND, NOTIFICATIONS_CENTER_BORDER } from 'vs/workbench/common/theme'; import { IThemeService, registerThemingParticipant, Themable } from 'vs/platform/theme/common/themeService'; import { INotificationsModel, INotificationChangeEvent, NotificationChangeType, NotificationViewItemContentChangeKind } from 'vs/workbench/common/notifications'; import { IWorkbenchLayoutService, Parts } from 'vs/workbench/services/layout/browser/layoutService'; import { Emitter } from 'vs/base/common/event'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { INotificationsCenterController } from 'vs/workbench/browser/parts/notifications/notificationsCommands'; import { NotificationsList } from 'vs/workbench/browser/parts/notifications/notificationsList'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { isAncestor, Dimension } from 'vs/base/browser/dom'; import { widgetShadow } from 'vs/platform/theme/common/colorRegistry'; import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService'; import { localize } from 'vs/nls'; import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar'; import { ClearAllNotificationsAction, HideNotificationsCenterAction, NotificationActionRunner, ToggleDoNotDisturbAction } from 'vs/workbench/browser/parts/notifications/notificationsActions'; import { IAction } from 'vs/base/common/actions'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { assertAllDefined, assertIsDefined } from 'vs/base/common/types'; import { NotificationsCenterVisibleContext } from 'vs/workbench/common/contextkeys'; import { INotificationService } from 'vs/platform/notification/common/notification'; export class NotificationsCenter extends Themable implements INotificationsCenterController { private static readonly MAX_DIMENSIONS = new Dimension(450, 400); private readonly _onDidChangeVisibility = this._register(new Emitter<void>()); readonly onDidChangeVisibility = this._onDidChangeVisibility.event; private notificationsCenterContainer: HTMLElement | undefined; private notificationsCenterHeader: HTMLElement | undefined; private notificationsCenterTitle: HTMLSpanElement | undefined; private notificationsList: NotificationsList | undefined; private _isVisible: boolean | undefined; private workbenchDimensions: Dimension | undefined; private readonly notificationsCenterVisibleContextKey = NotificationsCenterVisibleContext.bindTo(this.contextKeyService); private clearAllAction: ClearAllNotificationsAction | undefined; private toggleDoNotDisturbAction: ToggleDoNotDisturbAction | undefined; constructor( private readonly container: HTMLElement, private readonly model: INotificationsModel, @IThemeService themeService: IThemeService, @IInstantiationService private readonly instantiationService: IInstantiationService, @IWorkbenchLayoutService private readonly layoutService: IWorkbenchLayoutService, @IContextKeyService private readonly contextKeyService: IContextKeyService, @IEditorGroupsService private readonly editorGroupService: IEditorGroupsService, @IKeybindingService private readonly keybindingService: IKeybindingService, @INotificationService private readonly notificationService: INotificationService, ) { super(themeService); this.notificationsCenterVisibleContextKey = NotificationsCenterVisibleContext.bindTo(contextKeyService); this.registerListeners(); } private registerListeners(): void { this._register(this.model.onDidChangeNotification(e => this.onDidChangeNotification(e))); this._register(this.layoutService.onDidLayout(dimension => this.layout(Dimension.lift(dimension)))); this._register(this.notificationService.onDidChangeDoNotDisturbMode(() => this.onDidChangeDoNotDisturbMode())); } private onDidChangeDoNotDisturbMode(): void { this.hide(); // hide the notification center when do not disturb is toggled } get isVisible(): boolean { return !!this._isVisible; } show(): void { if (this._isVisible) { const notificationsList = assertIsDefined(this.notificationsList); notificationsList.show(true /* focus */); return; // already visible } // Lazily create if showing for the first time if (!this.notificationsCenterContainer) { this.create(); } // Title this.updateTitle(); // Make visible const [notificationsList, notificationsCenterContainer] = assertAllDefined(this.notificationsList, this.notificationsCenterContainer); this._isVisible = true; notificationsCenterContainer.classList.add('visible'); notificationsList.show(); // Layout this.layout(this.workbenchDimensions); // Show all notifications that are present now notificationsList.updateNotificationsList(0, 0, this.model.notifications); // Focus first notificationsList.focusFirst(); // Theming this.updateStyles(); // Mark as visible this.model.notifications.forEach(notification => notification.updateVisibility(true)); // Context Key this.notificationsCenterVisibleContextKey.set(true); // Event this._onDidChangeVisibility.fire(); } private updateTitle(): void { const [notificationsCenterTitle, clearAllAction] = assertAllDefined(this.notificationsCenterTitle, this.clearAllAction); if (this.model.notifications.length === 0) { notificationsCenterTitle.textContent = localize('notificationsEmpty', "No new notifications"); clearAllAction.enabled = false; } else { notificationsCenterTitle.textContent = localize('notifications', "Notifications"); clearAllAction.enabled = this.model.notifications.some(notification => !notification.hasProgress); } } private create(): void { // Container this.notificationsCenterContainer = document.createElement('div'); this.notificationsCenterContainer.classList.add('notifications-center'); // Header this.notificationsCenterHeader = document.createElement('div'); this.notificationsCenterHeader.classList.add('notifications-center-header'); this.notificationsCenterContainer.appendChild(this.notificationsCenterHeader); // Header Title this.notificationsCenterTitle = document.createElement('span'); this.notificationsCenterTitle.classList.add('notifications-center-header-title'); this.notificationsCenterHeader.appendChild(this.notificationsCenterTitle); // Header Toolbar const toolbarContainer = document.createElement('div'); toolbarContainer.classList.add('notifications-center-header-toolbar'); this.notificationsCenterHeader.appendChild(toolbarContainer); const actionRunner = this._register(this.instantiationService.createInstance(NotificationActionRunner)); const notificationsToolBar = this._register(new ActionBar(toolbarContainer, { ariaLabel: localize('notificationsToolbar', "Notification Center Actions"), actionRunner })); this.clearAllAction = this._register(this.instantiationService.createInstance(ClearAllNotificationsAction, ClearAllNotificationsAction.ID, ClearAllNotificationsAction.LABEL)); notificationsToolBar.push(this.clearAllAction, { icon: true, label: false, keybinding: this.getKeybindingLabel(this.clearAllAction) }); this.toggleDoNotDisturbAction = this._register(this.instantiationService.createInstance(ToggleDoNotDisturbAction, ToggleDoNotDisturbAction.ID, ToggleDoNotDisturbAction.LABEL)); notificationsToolBar.push(this.toggleDoNotDisturbAction, { icon: true, label: false, keybinding: this.getKeybindingLabel(this.toggleDoNotDisturbAction) }); const hideAllAction = this._register(this.instantiationService.createInstance(HideNotificationsCenterAction, HideNotificationsCenterAction.ID, HideNotificationsCenterAction.LABEL)); notificationsToolBar.push(hideAllAction, { icon: true, label: false, keybinding: this.getKeybindingLabel(hideAllAction) }); // Notifications List this.notificationsList = this.instantiationService.createInstance(NotificationsList, this.notificationsCenterContainer, { widgetAriaLabel: localize('notificationsCenterWidgetAriaLabel', "Notifications Center") }); this.container.appendChild(this.notificationsCenterContainer); } private getKeybindingLabel(action: IAction): string | null { const keybinding = this.keybindingService.lookupKeybinding(action.id); return keybinding ? keybinding.getLabel() : null; } private onDidChangeNotification(e: INotificationChangeEvent): void { if (!this._isVisible) { return; // only if visible } let focusEditor = false; // Update notifications list based on event kind const [notificationsList, notificationsCenterContainer] = assertAllDefined(this.notificationsList, this.notificationsCenterContainer); switch (e.kind) { case NotificationChangeType.ADD: notificationsList.updateNotificationsList(e.index, 0, [e.item]); e.item.updateVisibility(true); break; case NotificationChangeType.CHANGE: // Handle content changes // - actions: re-draw to properly show them // - message: update notification height unless collapsed switch (e.detail) { case NotificationViewItemContentChangeKind.ACTIONS: notificationsList.updateNotificationsList(e.index, 1, [e.item]); break; case NotificationViewItemContentChangeKind.MESSAGE: if (e.item.expanded) { notificationsList.updateNotificationHeight(e.item); } break; } break; case NotificationChangeType.EXPAND_COLLAPSE: // Re-draw entire item when expansion changes to reveal or hide details notificationsList.updateNotificationsList(e.index, 1, [e.item]); break; case NotificationChangeType.REMOVE: focusEditor = isAncestor(document.activeElement, notificationsCenterContainer); notificationsList.updateNotificationsList(e.index, 1); e.item.updateVisibility(false); break; } // Update title this.updateTitle(); // Hide if no more notifications to show if (this.model.notifications.length === 0) { this.hide(); // Restore focus to editor group if we had focus if (focusEditor) { this.editorGroupService.activeGroup.focus(); } } } hide(): void { if (!this._isVisible || !this.notificationsCenterContainer || !this.notificationsList) { return; // already hidden } const focusEditor = isAncestor(document.activeElement, this.notificationsCenterContainer); // Hide this._isVisible = false; this.notificationsCenterContainer.classList.remove('visible'); this.notificationsList.hide(); // Mark as hidden this.model.notifications.forEach(notification => notification.updateVisibility(false)); // Context Key this.notificationsCenterVisibleContextKey.set(false); // Event this._onDidChangeVisibility.fire(); // Restore focus to editor group if we had focus if (focusEditor) { this.editorGroupService.activeGroup.focus(); } } protected override updateStyles(): void { if (this.notificationsCenterContainer && this.notificationsCenterHeader) { const widgetShadowColor = this.getColor(widgetShadow); this.notificationsCenterContainer.style.boxShadow = widgetShadowColor ? `0 0 8px 2px ${widgetShadowColor}` : ''; const borderColor = this.getColor(NOTIFICATIONS_CENTER_BORDER); this.notificationsCenterContainer.style.border = borderColor ? `1px solid ${borderColor}` : ''; const headerForeground = this.getColor(NOTIFICATIONS_CENTER_HEADER_FOREGROUND); this.notificationsCenterHeader.style.color = headerForeground ? headerForeground.toString() : ''; const headerBackground = this.getColor(NOTIFICATIONS_CENTER_HEADER_BACKGROUND); this.notificationsCenterHeader.style.background = headerBackground ? headerBackground.toString() : ''; } } layout(dimension: Dimension | undefined): void { this.workbenchDimensions = dimension; if (this._isVisible && this.notificationsCenterContainer) { const maxWidth = NotificationsCenter.MAX_DIMENSIONS.width; const maxHeight = NotificationsCenter.MAX_DIMENSIONS.height; let availableWidth = maxWidth; let availableHeight = maxHeight; if (this.workbenchDimensions) { // Make sure notifications are not exceding available width availableWidth = this.workbenchDimensions.width; availableWidth -= (2 * 8); // adjust for paddings left and right // Make sure notifications are not exceeding available height availableHeight = this.workbenchDimensions.height - 35 /* header */; if (this.layoutService.isVisible(Parts.STATUSBAR_PART)) { availableHeight -= 22; // adjust for status bar } if (this.layoutService.isVisible(Parts.TITLEBAR_PART)) { availableHeight -= 22; // adjust for title bar } availableHeight -= (2 * 12); // adjust for paddings top and bottom } // Apply to list const notificationsList = assertIsDefined(this.notificationsList); notificationsList.layout(Math.min(maxWidth, availableWidth), Math.min(maxHeight, availableHeight)); } } clearAll(): void { // Hide notifications center first this.hide(); // Close all for (const notification of [...this.model.notifications] /* copy array since we modify it from closing */) { if (!notification.hasProgress) { notification.close(); } } } } registerThemingParticipant((theme, collector) => { const notificationBorderColor = theme.getColor(NOTIFICATIONS_BORDER); if (notificationBorderColor) { collector.addRule(`.monaco-workbench > .notifications-center .notifications-list-container .monaco-list-row[data-last-element="false"] > .notification-list-item { border-bottom: 1px solid ${notificationBorderColor}; }`); } });
src/vs/workbench/browser/parts/notifications/notificationsCenter.ts
0
https://github.com/microsoft/vscode/commit/fe5f564db16038785936282be7f6b871f34b8bd1
[ 0.00017751462291926146, 0.00017376554023940116, 0.00016826690989546478, 0.00017399812350049615, 0.000002039358378169709 ]
{ "id": 1, "code_window": [ ") -> Result<(), AnyError> {\n", "\tinfo!(log, \"Setting up server...\");\n", "\n", "\tunzip_downloaded_release(compressed_file, &paths.server_dir, SilentCopyProgress())?;\n", "\n", "\tmatch fs::remove_file(&compressed_file) {\n", "\t\tOk(()) => {}\n", "\t\tErr(e) => {\n", "\t\t\tif e.kind() != ErrorKind::NotFound {\n", "\t\t\t\treturn Err(AnyError::from(wrap(e, \"error removing downloaded file\")));\n", "\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tmatch fs::remove_file(compressed_file) {\n" ], "file_path": "cli/src/tunnels/code_server.rs", "type": "replace", "edit_start_line_idx": 354 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { CancelablePromise, createCancelablePromise } from 'vs/base/common/async'; import { VSBuffer } from 'vs/base/common/buffer'; import { CancellationToken, CancellationTokenSource } from 'vs/base/common/cancellation'; import { isCancellationError, onUnexpectedError } from 'vs/base/common/errors'; import { Emitter } from 'vs/base/common/event'; import { Disposable, DisposableStore, IDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { generateUuid } from 'vs/base/common/uuid'; import { IIPCLogger } from 'vs/base/parts/ipc/common/ipc'; import { Client, ISocket, PersistentProtocol, SocketCloseEventType } from 'vs/base/parts/ipc/common/ipc.net'; import { ILogService } from 'vs/platform/log/common/log'; import { RemoteAgentConnectionContext } from 'vs/platform/remote/common/remoteAgentEnvironment'; import { RemoteAuthorityResolverError } from 'vs/platform/remote/common/remoteAuthorityResolver'; import { getRemoteServerRootPath } from 'vs/platform/remote/common/remoteHosts'; import { ISignService } from 'vs/platform/sign/common/sign'; const RECONNECT_TIMEOUT = 30 * 1000 /* 30s */; export const enum ConnectionType { Management = 1, ExtensionHost = 2, Tunnel = 3, } function connectionTypeToString(connectionType: ConnectionType): string { switch (connectionType) { case ConnectionType.Management: return 'Management'; case ConnectionType.ExtensionHost: return 'ExtensionHost'; case ConnectionType.Tunnel: return 'Tunnel'; } } export interface AuthRequest { type: 'auth'; auth: string; data: string; } export interface SignRequest { type: 'sign'; data: string; signedData: string; } export interface ConnectionTypeRequest { type: 'connectionType'; commit?: string; signedData: string; desiredConnectionType?: ConnectionType; args?: any; } export interface ErrorMessage { type: 'error'; reason: string; } export interface OKMessage { type: 'ok'; } export type HandshakeMessage = AuthRequest | SignRequest | ConnectionTypeRequest | ErrorMessage | OKMessage; interface ISimpleConnectionOptions { commit: string | undefined; quality: string | undefined; host: string; port: number; connectionToken: string | undefined; reconnectionToken: string; reconnectionProtocol: PersistentProtocol | null; socketFactory: ISocketFactory; signService: ISignService; logService: ILogService; } export interface IConnectCallback { (err: any | undefined, socket: ISocket | undefined): void; } export interface ISocketFactory { connect(host: string, port: number, path: string, query: string, debugLabel: string, callback: IConnectCallback): void; } function createTimeoutCancellation(millis: number): CancellationToken { const source = new CancellationTokenSource(); setTimeout(() => source.cancel(), millis); return source.token; } function combineTimeoutCancellation(a: CancellationToken, b: CancellationToken): CancellationToken { if (a.isCancellationRequested || b.isCancellationRequested) { return CancellationToken.Cancelled; } const source = new CancellationTokenSource(); a.onCancellationRequested(() => source.cancel()); b.onCancellationRequested(() => source.cancel()); return source.token; } class PromiseWithTimeout<T> { private _state: 'pending' | 'resolved' | 'rejected' | 'timedout'; private readonly _disposables: DisposableStore; public readonly promise: Promise<T>; private _resolvePromise!: (value: T) => void; private _rejectPromise!: (err: any) => void; public get didTimeout(): boolean { return (this._state === 'timedout'); } constructor(timeoutCancellationToken: CancellationToken) { this._state = 'pending'; this._disposables = new DisposableStore(); this.promise = new Promise<T>((resolve, reject) => { this._resolvePromise = resolve; this._rejectPromise = reject; }); if (timeoutCancellationToken.isCancellationRequested) { this._timeout(); } else { this._disposables.add(timeoutCancellationToken.onCancellationRequested(() => this._timeout())); } } public registerDisposable(disposable: IDisposable): void { if (this._state === 'pending') { this._disposables.add(disposable); } else { disposable.dispose(); } } private _timeout(): void { if (this._state !== 'pending') { return; } this._disposables.dispose(); this._state = 'timedout'; this._rejectPromise(this._createTimeoutError()); } private _createTimeoutError(): Error { const err: any = new Error('Time limit reached'); err.code = 'ETIMEDOUT'; err.syscall = 'connect'; return err; } public resolve(value: T): void { if (this._state !== 'pending') { return; } this._disposables.dispose(); this._state = 'resolved'; this._resolvePromise(value); } public reject(err: any): void { if (this._state !== 'pending') { return; } this._disposables.dispose(); this._state = 'rejected'; this._rejectPromise(err); } } function readOneControlMessage<T>(protocol: PersistentProtocol, timeoutCancellationToken: CancellationToken): Promise<T> { const result = new PromiseWithTimeout<T>(timeoutCancellationToken); result.registerDisposable(protocol.onControlMessage(raw => { const msg: T = JSON.parse(raw.toString()); const error = getErrorFromMessage(msg); if (error) { result.reject(error); } else { result.resolve(msg); } })); return result.promise; } function createSocket(logService: ILogService, socketFactory: ISocketFactory, host: string, port: number, path: string, query: string, debugLabel: string, timeoutCancellationToken: CancellationToken): Promise<ISocket> { const result = new PromiseWithTimeout<ISocket>(timeoutCancellationToken); socketFactory.connect(host, port, path, query, debugLabel, (err: any, socket: ISocket | undefined) => { if (result.didTimeout) { if (err) { logService.error(err); } socket?.dispose(); } else { if (err || !socket) { result.reject(err); } else { result.resolve(socket); } } }); return result.promise; } function raceWithTimeoutCancellation<T>(promise: Promise<T>, timeoutCancellationToken: CancellationToken): Promise<T> { const result = new PromiseWithTimeout<T>(timeoutCancellationToken); promise.then( (res) => { if (!result.didTimeout) { result.resolve(res); } }, (err) => { if (!result.didTimeout) { result.reject(err); } } ); return result.promise; } async function connectToRemoteExtensionHostAgent(options: ISimpleConnectionOptions, connectionType: ConnectionType, args: any | undefined, timeoutCancellationToken: CancellationToken): Promise<{ protocol: PersistentProtocol; ownsProtocol: boolean }> { const logPrefix = connectLogPrefix(options, connectionType); options.logService.trace(`${logPrefix} 1/6. invoking socketFactory.connect().`); let socket: ISocket; try { socket = await createSocket(options.logService, options.socketFactory, options.host, options.port, getRemoteServerRootPath(options), `reconnectionToken=${options.reconnectionToken}&reconnection=${options.reconnectionProtocol ? 'true' : 'false'}`, `renderer-${connectionTypeToString(connectionType)}-${options.reconnectionToken}`, timeoutCancellationToken); } catch (error) { options.logService.error(`${logPrefix} socketFactory.connect() failed or timed out. Error:`); options.logService.error(error); throw error; } options.logService.trace(`${logPrefix} 2/6. socketFactory.connect() was successful.`); let protocol: PersistentProtocol; let ownsProtocol: boolean; if (options.reconnectionProtocol) { options.reconnectionProtocol.beginAcceptReconnection(socket, null); protocol = options.reconnectionProtocol; ownsProtocol = false; } else { protocol = new PersistentProtocol(socket, null); ownsProtocol = true; } options.logService.trace(`${logPrefix} 3/6. sending AuthRequest control message.`); const message = await raceWithTimeoutCancellation(options.signService.createNewMessage(generateUuid()), timeoutCancellationToken); const authRequest: AuthRequest = { type: 'auth', auth: options.connectionToken || '00000000000000000000', data: message.data }; protocol.sendControl(VSBuffer.fromString(JSON.stringify(authRequest))); try { const msg = await readOneControlMessage<HandshakeMessage>(protocol, combineTimeoutCancellation(timeoutCancellationToken, createTimeoutCancellation(10000))); if (msg.type !== 'sign' || typeof msg.data !== 'string') { const error: any = new Error('Unexpected handshake message'); error.code = 'VSCODE_CONNECTION_ERROR'; throw error; } options.logService.trace(`${logPrefix} 4/6. received SignRequest control message.`); const isValid = await raceWithTimeoutCancellation(options.signService.validate(message, msg.signedData), timeoutCancellationToken); if (!isValid) { const error: any = new Error('Refused to connect to unsupported server'); error.code = 'VSCODE_CONNECTION_ERROR'; throw error; } const signed = await raceWithTimeoutCancellation(options.signService.sign(msg.data), timeoutCancellationToken); const connTypeRequest: ConnectionTypeRequest = { type: 'connectionType', commit: options.commit, signedData: signed, desiredConnectionType: connectionType }; if (args) { connTypeRequest.args = args; } options.logService.trace(`${logPrefix} 5/6. sending ConnectionTypeRequest control message.`); protocol.sendControl(VSBuffer.fromString(JSON.stringify(connTypeRequest))); return { protocol, ownsProtocol }; } catch (error) { if (error && error.code === 'ETIMEDOUT') { options.logService.error(`${logPrefix} the handshake timed out. Error:`); options.logService.error(error); } if (error && error.code === 'VSCODE_CONNECTION_ERROR') { options.logService.error(`${logPrefix} received error control message when negotiating connection. Error:`); options.logService.error(error); } if (ownsProtocol) { safeDisposeProtocolAndSocket(protocol); } throw error; } } interface IManagementConnectionResult { protocol: PersistentProtocol; } async function connectToRemoteExtensionHostAgentAndReadOneMessage<T>(options: ISimpleConnectionOptions, connectionType: ConnectionType, args: any | undefined, timeoutCancellationToken: CancellationToken): Promise<{ protocol: PersistentProtocol; firstMessage: T }> { const startTime = Date.now(); const logPrefix = connectLogPrefix(options, connectionType); const { protocol, ownsProtocol } = await connectToRemoteExtensionHostAgent(options, connectionType, args, timeoutCancellationToken); const result = new PromiseWithTimeout<{ protocol: PersistentProtocol; firstMessage: T }>(timeoutCancellationToken); result.registerDisposable(protocol.onControlMessage(raw => { const msg: T = JSON.parse(raw.toString()); const error = getErrorFromMessage(msg); if (error) { options.logService.error(`${logPrefix} received error control message when negotiating connection. Error:`); options.logService.error(error); if (ownsProtocol) { safeDisposeProtocolAndSocket(protocol); } result.reject(error); } else { options.reconnectionProtocol?.endAcceptReconnection(); options.logService.trace(`${logPrefix} 6/6. handshake finished, connection is up and running after ${logElapsed(startTime)}!`); result.resolve({ protocol, firstMessage: msg }); } })); return result.promise; } async function doConnectRemoteAgentManagement(options: ISimpleConnectionOptions, timeoutCancellationToken: CancellationToken): Promise<IManagementConnectionResult> { const { protocol } = await connectToRemoteExtensionHostAgentAndReadOneMessage(options, ConnectionType.Management, undefined, timeoutCancellationToken); return { protocol }; } export interface IRemoteExtensionHostStartParams { language: string; debugId?: string; break?: boolean; port?: number | null; env?: { [key: string]: string | null }; } interface IExtensionHostConnectionResult { protocol: PersistentProtocol; debugPort?: number; } async function doConnectRemoteAgentExtensionHost(options: ISimpleConnectionOptions, startArguments: IRemoteExtensionHostStartParams, timeoutCancellationToken: CancellationToken): Promise<IExtensionHostConnectionResult> { const { protocol, firstMessage } = await connectToRemoteExtensionHostAgentAndReadOneMessage<{ debugPort?: number }>(options, ConnectionType.ExtensionHost, startArguments, timeoutCancellationToken); const debugPort = firstMessage && firstMessage.debugPort; return { protocol, debugPort }; } export interface ITunnelConnectionStartParams { host: string; port: number; } async function doConnectRemoteAgentTunnel(options: ISimpleConnectionOptions, startParams: ITunnelConnectionStartParams, timeoutCancellationToken: CancellationToken): Promise<PersistentProtocol> { const startTime = Date.now(); const logPrefix = connectLogPrefix(options, ConnectionType.Tunnel); const { protocol } = await connectToRemoteExtensionHostAgent(options, ConnectionType.Tunnel, startParams, timeoutCancellationToken); options.logService.trace(`${logPrefix} 6/6. handshake finished, connection is up and running after ${logElapsed(startTime)}!`); return protocol; } export interface IConnectionOptions { commit: string | undefined; quality: string | undefined; socketFactory: ISocketFactory; addressProvider: IAddressProvider; signService: ISignService; logService: ILogService; ipcLogger: IIPCLogger | null; } async function resolveConnectionOptions(options: IConnectionOptions, reconnectionToken: string, reconnectionProtocol: PersistentProtocol | null): Promise<ISimpleConnectionOptions> { const { host, port, connectionToken } = await options.addressProvider.getAddress(); return { commit: options.commit, quality: options.quality, host: host, port: port, connectionToken: connectionToken, reconnectionToken: reconnectionToken, reconnectionProtocol: reconnectionProtocol, socketFactory: options.socketFactory, signService: options.signService, logService: options.logService }; } export interface IAddress { host: string; port: number; connectionToken: string | undefined; } export interface IAddressProvider { getAddress(): Promise<IAddress>; } export async function connectRemoteAgentManagement(options: IConnectionOptions, remoteAuthority: string, clientId: string): Promise<ManagementPersistentConnection> { return createInitialConnection( options, async (simpleOptions) => { const { protocol } = await doConnectRemoteAgentManagement(simpleOptions, CancellationToken.None); return new ManagementPersistentConnection(options, remoteAuthority, clientId, simpleOptions.reconnectionToken, protocol); } ); } export async function connectRemoteAgentExtensionHost(options: IConnectionOptions, startArguments: IRemoteExtensionHostStartParams): Promise<ExtensionHostPersistentConnection> { return createInitialConnection( options, async (simpleOptions) => { const { protocol, debugPort } = await doConnectRemoteAgentExtensionHost(simpleOptions, startArguments, CancellationToken.None); return new ExtensionHostPersistentConnection(options, startArguments, simpleOptions.reconnectionToken, protocol, debugPort); } ); } /** * Will attempt to connect 5 times. If it fails 5 consecutive times, it will give up. */ async function createInitialConnection<T extends PersistentConnection>(options: IConnectionOptions, connectionFactory: (simpleOptions: ISimpleConnectionOptions) => Promise<T>): Promise<T> { const MAX_ATTEMPTS = 5; for (let attempt = 1; ; attempt++) { try { const reconnectionToken = generateUuid(); const simpleOptions = await resolveConnectionOptions(options, reconnectionToken, null); const result = await connectionFactory(simpleOptions); return result; } catch (err) { if (attempt < MAX_ATTEMPTS) { options.logService.error(`[remote-connection][attempt ${attempt}] An error occurred in initial connection! Will retry... Error:`); options.logService.error(err); } else { options.logService.error(`[remote-connection][attempt ${attempt}] An error occurred in initial connection! It will be treated as a permanent error. Error:`); options.logService.error(err); PersistentConnection.triggerPermanentFailure(0, 0, RemoteAuthorityResolverError.isHandled(err)); throw err; } } } } export async function connectRemoteAgentTunnel(options: IConnectionOptions, tunnelRemoteHost: string, tunnelRemotePort: number): Promise<PersistentProtocol> { const simpleOptions = await resolveConnectionOptions(options, generateUuid(), null); const protocol = await doConnectRemoteAgentTunnel(simpleOptions, { host: tunnelRemoteHost, port: tunnelRemotePort }, CancellationToken.None); return protocol; } function sleep(seconds: number): CancelablePromise<void> { return createCancelablePromise(token => { return new Promise((resolve, reject) => { const timeout = setTimeout(resolve, seconds * 1000); token.onCancellationRequested(() => { clearTimeout(timeout); resolve(); }); }); }); } export const enum PersistentConnectionEventType { ConnectionLost, ReconnectionWait, ReconnectionRunning, ReconnectionPermanentFailure, ConnectionGain } export class ConnectionLostEvent { public readonly type = PersistentConnectionEventType.ConnectionLost; constructor( public readonly reconnectionToken: string, public readonly millisSinceLastIncomingData: number ) { } } export class ReconnectionWaitEvent { public readonly type = PersistentConnectionEventType.ReconnectionWait; constructor( public readonly reconnectionToken: string, public readonly millisSinceLastIncomingData: number, public readonly durationSeconds: number, private readonly cancellableTimer: CancelablePromise<void> ) { } public skipWait(): void { this.cancellableTimer.cancel(); } } export class ReconnectionRunningEvent { public readonly type = PersistentConnectionEventType.ReconnectionRunning; constructor( public readonly reconnectionToken: string, public readonly millisSinceLastIncomingData: number, public readonly attempt: number ) { } } export class ConnectionGainEvent { public readonly type = PersistentConnectionEventType.ConnectionGain; constructor( public readonly reconnectionToken: string, public readonly millisSinceLastIncomingData: number, public readonly attempt: number ) { } } export class ReconnectionPermanentFailureEvent { public readonly type = PersistentConnectionEventType.ReconnectionPermanentFailure; constructor( public readonly reconnectionToken: string, public readonly millisSinceLastIncomingData: number, public readonly attempt: number, public readonly handled: boolean ) { } } export type PersistentConnectionEvent = ConnectionGainEvent | ConnectionLostEvent | ReconnectionWaitEvent | ReconnectionRunningEvent | ReconnectionPermanentFailureEvent; export abstract class PersistentConnection extends Disposable { public static triggerPermanentFailure(millisSinceLastIncomingData: number, attempt: number, handled: boolean): void { this._permanentFailure = true; this._permanentFailureMillisSinceLastIncomingData = millisSinceLastIncomingData; this._permanentFailureAttempt = attempt; this._permanentFailureHandled = handled; this._instances.forEach(instance => instance._gotoPermanentFailure(this._permanentFailureMillisSinceLastIncomingData, this._permanentFailureAttempt, this._permanentFailureHandled)); } public static debugTriggerReconnection() { this._instances.forEach(instance => instance._beginReconnecting()); } public static debugPauseSocketWriting() { this._instances.forEach(instance => instance._pauseSocketWriting()); } private static _permanentFailure: boolean = false; private static _permanentFailureMillisSinceLastIncomingData: number = 0; private static _permanentFailureAttempt: number = 0; private static _permanentFailureHandled: boolean = false; private static _instances: PersistentConnection[] = []; private readonly _onDidStateChange = this._register(new Emitter<PersistentConnectionEvent>()); public readonly onDidStateChange = this._onDidStateChange.event; private _permanentFailure: boolean = false; private get _isPermanentFailure(): boolean { return this._permanentFailure || PersistentConnection._permanentFailure; } private _isReconnecting: boolean; constructor( private readonly _connectionType: ConnectionType, protected readonly _options: IConnectionOptions, public readonly reconnectionToken: string, public readonly protocol: PersistentProtocol, private readonly _reconnectionFailureIsFatal: boolean ) { super(); this._isReconnecting = false; this._onDidStateChange.fire(new ConnectionGainEvent(this.reconnectionToken, 0, 0)); this._register(protocol.onSocketClose((e) => { const logPrefix = commonLogPrefix(this._connectionType, this.reconnectionToken, true); if (!e) { this._options.logService.info(`${logPrefix} received socket close event.`); } else if (e.type === SocketCloseEventType.NodeSocketCloseEvent) { this._options.logService.info(`${logPrefix} received socket close event (hadError: ${e.hadError}).`); if (e.error) { this._options.logService.error(e.error); } } else { this._options.logService.info(`${logPrefix} received socket close event (wasClean: ${e.wasClean}, code: ${e.code}, reason: ${e.reason}).`); if (e.event) { this._options.logService.error(e.event); } } this._beginReconnecting(); })); this._register(protocol.onSocketTimeout((e) => { const logPrefix = commonLogPrefix(this._connectionType, this.reconnectionToken, true); this._options.logService.info(`${logPrefix} received socket timeout event (unacknowledgedMsgCount: ${e.unacknowledgedMsgCount}, timeSinceOldestUnacknowledgedMsg: ${e.timeSinceOldestUnacknowledgedMsg}, timeSinceLastReceivedSomeData: ${e.timeSinceLastReceivedSomeData}).`); this._beginReconnecting(); })); PersistentConnection._instances.push(this); this._register(toDisposable(() => { const myIndex = PersistentConnection._instances.indexOf(this); if (myIndex >= 0) { PersistentConnection._instances.splice(myIndex, 1); } })); if (this._isPermanentFailure) { this._gotoPermanentFailure(PersistentConnection._permanentFailureMillisSinceLastIncomingData, PersistentConnection._permanentFailureAttempt, PersistentConnection._permanentFailureHandled); } } private async _beginReconnecting(): Promise<void> { // Only have one reconnection loop active at a time. if (this._isReconnecting) { return; } try { this._isReconnecting = true; await this._runReconnectingLoop(); } finally { this._isReconnecting = false; } } private async _runReconnectingLoop(): Promise<void> { if (this._isPermanentFailure) { // no more attempts! return; } const logPrefix = commonLogPrefix(this._connectionType, this.reconnectionToken, true); this._options.logService.info(`${logPrefix} starting reconnecting loop. You can get more information with the trace log level.`); this._onDidStateChange.fire(new ConnectionLostEvent(this.reconnectionToken, this.protocol.getMillisSinceLastIncomingData())); const TIMES = [0, 5, 5, 10, 10, 10, 10, 10, 30]; let attempt = -1; do { attempt++; const waitTime = (attempt < TIMES.length ? TIMES[attempt] : TIMES[TIMES.length - 1]); try { if (waitTime > 0) { const sleepPromise = sleep(waitTime); this._onDidStateChange.fire(new ReconnectionWaitEvent(this.reconnectionToken, this.protocol.getMillisSinceLastIncomingData(), waitTime, sleepPromise)); this._options.logService.info(`${logPrefix} waiting for ${waitTime} seconds before reconnecting...`); try { await sleepPromise; } catch { } // User canceled timer } if (this._isPermanentFailure) { this._options.logService.error(`${logPrefix} permanent failure occurred while running the reconnecting loop.`); break; } // connection was lost, let's try to re-establish it this._onDidStateChange.fire(new ReconnectionRunningEvent(this.reconnectionToken, this.protocol.getMillisSinceLastIncomingData(), attempt + 1)); this._options.logService.info(`${logPrefix} resolving connection...`); const simpleOptions = await resolveConnectionOptions(this._options, this.reconnectionToken, this.protocol); this._options.logService.info(`${logPrefix} connecting to ${simpleOptions.host}:${simpleOptions.port}...`); await this._reconnect(simpleOptions, createTimeoutCancellation(RECONNECT_TIMEOUT)); this._options.logService.info(`${logPrefix} reconnected!`); this._onDidStateChange.fire(new ConnectionGainEvent(this.reconnectionToken, this.protocol.getMillisSinceLastIncomingData(), attempt + 1)); break; } catch (err) { if (err.code === 'VSCODE_CONNECTION_ERROR') { this._options.logService.error(`${logPrefix} A permanent error occurred in the reconnecting loop! Will give up now! Error:`); this._options.logService.error(err); this._onReconnectionPermanentFailure(this.protocol.getMillisSinceLastIncomingData(), attempt + 1, false); break; } if (attempt > 360) { // ReconnectionGraceTime is 3hrs, with 30s between attempts that yields a maximum of 360 attempts this._options.logService.error(`${logPrefix} An error occurred while reconnecting, but it will be treated as a permanent error because the reconnection grace time has expired! Will give up now! Error:`); this._options.logService.error(err); this._onReconnectionPermanentFailure(this.protocol.getMillisSinceLastIncomingData(), attempt + 1, false); break; } if (RemoteAuthorityResolverError.isTemporarilyNotAvailable(err)) { this._options.logService.info(`${logPrefix} A temporarily not available error occurred while trying to reconnect, will try again...`); this._options.logService.trace(err); // try again! continue; } if ((err.code === 'ETIMEDOUT' || err.code === 'ENETUNREACH' || err.code === 'ECONNREFUSED' || err.code === 'ECONNRESET') && err.syscall === 'connect') { this._options.logService.info(`${logPrefix} A network error occurred while trying to reconnect, will try again...`); this._options.logService.trace(err); // try again! continue; } if (isCancellationError(err)) { this._options.logService.info(`${logPrefix} A promise cancelation error occurred while trying to reconnect, will try again...`); this._options.logService.trace(err); // try again! continue; } if (err instanceof RemoteAuthorityResolverError) { this._options.logService.error(`${logPrefix} A RemoteAuthorityResolverError occurred while trying to reconnect. Will give up now! Error:`); this._options.logService.error(err); this._onReconnectionPermanentFailure(this.protocol.getMillisSinceLastIncomingData(), attempt + 1, RemoteAuthorityResolverError.isHandled(err)); break; } this._options.logService.error(`${logPrefix} An unknown error occurred while trying to reconnect, since this is an unknown case, it will be treated as a permanent error! Will give up now! Error:`); this._options.logService.error(err); this._onReconnectionPermanentFailure(this.protocol.getMillisSinceLastIncomingData(), attempt + 1, false); break; } } while (!this._isPermanentFailure); } private _onReconnectionPermanentFailure(millisSinceLastIncomingData: number, attempt: number, handled: boolean): void { if (this._reconnectionFailureIsFatal) { PersistentConnection.triggerPermanentFailure(millisSinceLastIncomingData, attempt, handled); } else { this._gotoPermanentFailure(millisSinceLastIncomingData, attempt, handled); } } private _gotoPermanentFailure(millisSinceLastIncomingData: number, attempt: number, handled: boolean): void { this._onDidStateChange.fire(new ReconnectionPermanentFailureEvent(this.reconnectionToken, millisSinceLastIncomingData, attempt, handled)); safeDisposeProtocolAndSocket(this.protocol); } private _pauseSocketWriting(): void { this.protocol.pauseSocketWriting(); } protected abstract _reconnect(options: ISimpleConnectionOptions, timeoutCancellationToken: CancellationToken): Promise<void>; } export class ManagementPersistentConnection extends PersistentConnection { public readonly client: Client<RemoteAgentConnectionContext>; constructor(options: IConnectionOptions, remoteAuthority: string, clientId: string, reconnectionToken: string, protocol: PersistentProtocol) { super(ConnectionType.Management, options, reconnectionToken, protocol, /*reconnectionFailureIsFatal*/true); this.client = this._register(new Client<RemoteAgentConnectionContext>(protocol, { remoteAuthority: remoteAuthority, clientId: clientId }, options.ipcLogger)); } protected async _reconnect(options: ISimpleConnectionOptions, timeoutCancellationToken: CancellationToken): Promise<void> { await doConnectRemoteAgentManagement(options, timeoutCancellationToken); } } export class ExtensionHostPersistentConnection extends PersistentConnection { private readonly _startArguments: IRemoteExtensionHostStartParams; public readonly debugPort: number | undefined; constructor(options: IConnectionOptions, startArguments: IRemoteExtensionHostStartParams, reconnectionToken: string, protocol: PersistentProtocol, debugPort: number | undefined) { super(ConnectionType.ExtensionHost, options, reconnectionToken, protocol, /*reconnectionFailureIsFatal*/false); this._startArguments = startArguments; this.debugPort = debugPort; } protected async _reconnect(options: ISimpleConnectionOptions, timeoutCancellationToken: CancellationToken): Promise<void> { await doConnectRemoteAgentExtensionHost(options, this._startArguments, timeoutCancellationToken); } } function safeDisposeProtocolAndSocket(protocol: PersistentProtocol): void { try { protocol.acceptDisconnect(); const socket = protocol.getSocket(); protocol.dispose(); socket.dispose(); } catch (err) { onUnexpectedError(err); } } function getErrorFromMessage(msg: any): Error | null { if (msg && msg.type === 'error') { const error = new Error(`Connection error: ${msg.reason}`); (<any>error).code = 'VSCODE_CONNECTION_ERROR'; return error; } return null; } function stringRightPad(str: string, len: number): string { while (str.length < len) { str += ' '; } return str; } function commonLogPrefix(connectionType: ConnectionType, reconnectionToken: string, isReconnect: boolean): string { return `[remote-connection][${stringRightPad(connectionTypeToString(connectionType), 13)}][${reconnectionToken.substr(0, 5)}…][${isReconnect ? 'reconnect' : 'initial'}]`; } function connectLogPrefix(options: ISimpleConnectionOptions, connectionType: ConnectionType): string { return `${commonLogPrefix(connectionType, options.reconnectionToken, !!options.reconnectionProtocol)}[${options.host}:${options.port}]`; } function logElapsed(startTime: number): string { return `${Date.now() - startTime} ms`; }
src/vs/platform/remote/common/remoteAgentConnection.ts
0
https://github.com/microsoft/vscode/commit/fe5f564db16038785936282be7f6b871f34b8bd1
[ 0.0015017499681562185, 0.0002011307660723105, 0.0001633866340853274, 0.0001710819487925619, 0.0001824468345148489 ]
{ "id": 1, "code_window": [ ") -> Result<(), AnyError> {\n", "\tinfo!(log, \"Setting up server...\");\n", "\n", "\tunzip_downloaded_release(compressed_file, &paths.server_dir, SilentCopyProgress())?;\n", "\n", "\tmatch fs::remove_file(&compressed_file) {\n", "\t\tOk(()) => {}\n", "\t\tErr(e) => {\n", "\t\t\tif e.kind() != ErrorKind::NotFound {\n", "\t\t\t\treturn Err(AnyError::from(wrap(e, \"error removing downloaded file\")));\n", "\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tmatch fs::remove_file(compressed_file) {\n" ], "file_path": "cli/src/tunnels/code_server.rs", "type": "replace", "edit_start_line_idx": 354 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as vscode from 'vscode'; import { Disposable } from './util/dispose'; export abstract class PreviewStatusBarEntry extends Disposable { private _showOwner: unknown | undefined; protected readonly entry: vscode.StatusBarItem; constructor(id: string, name: string, alignment: vscode.StatusBarAlignment, priority: number) { super(); this.entry = this._register(vscode.window.createStatusBarItem(id, alignment, priority)); this.entry.name = name; } protected showItem(owner: unknown, text: string) { this._showOwner = owner; this.entry.text = text; this.entry.show(); } public hide(owner: unknown) { if (owner === this._showOwner) { this.entry.hide(); this._showOwner = undefined; } } }
extensions/media-preview/src/ownedStatusBarEntry.ts
0
https://github.com/microsoft/vscode/commit/fe5f564db16038785936282be7f6b871f34b8bd1
[ 0.0001773576223058626, 0.00017303202184848487, 0.00016940945351962, 0.0001726805348880589, 0.0000028321578611212317 ]
{ "id": 2, "code_window": [ "\t\t\t} else {\n", "\t\t\t\tentry_path.into_owned()\n", "\t\t\t});\n", "\n", "\t\t\tif let Some(p) = path.parent() {\n", "\t\t\t\tfs::create_dir_all(&p)\n", "\t\t\t\t\t.map_err(|e| wrap(e, format!(\"could not create dir for {}\", p.display())))?;\n", "\t\t\t}\n", "\n", "\t\t\tentry\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tfs::create_dir_all(p)\n" ], "file_path": "cli/src/util/tar.rs", "type": "replace", "edit_start_line_idx": 89 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ use super::paths::{InstalledServer, LastUsedServers, ServerPaths}; use crate::options::{Quality, TelemetryLevel}; use crate::state::LauncherPaths; use crate::update_service::{ unzip_downloaded_release, Platform, Release, TargetKind, UpdateService, }; use crate::util::command::{capture_command, kill_tree}; use crate::util::errors::{ wrap, AnyError, ExtensionInstallFailed, MissingEntrypointError, WrappedError, }; use crate::util::http; use crate::util::io::SilentCopyProgress; use crate::util::machine::process_exists; use crate::{debug, info, log, span, spanf, trace, warning}; use lazy_static::lazy_static; use opentelemetry::KeyValue; use regex::Regex; use serde::Deserialize; use std::fs; use std::fs::File; use std::io::{ErrorKind, Write}; use std::path::{Path, PathBuf}; use std::time::Duration; use tokio::fs::remove_file; use tokio::io::{AsyncBufReadExt, BufReader}; use tokio::process::{Child, Command}; use tokio::sync::oneshot::Receiver; use tokio::time::{interval, timeout}; use uuid::Uuid; lazy_static! { static ref LISTENING_PORT_RE: Regex = Regex::new(r"Extension host agent listening on (.+)").unwrap(); static ref WEB_UI_RE: Regex = Regex::new(r"Web UI available at (.+)").unwrap(); } const MAX_RETAINED_SERVERS: usize = 5; #[derive(Clone, Debug, Default)] pub struct CodeServerArgs { pub host: Option<String>, pub port: Option<u16>, pub socket_path: Option<String>, // common argument pub telemetry_level: Option<TelemetryLevel>, pub log: Option<log::Level>, pub accept_server_license_terms: bool, pub verbose: bool, // extension management pub install_extensions: Vec<String>, pub uninstall_extensions: Vec<String>, pub list_extensions: bool, pub show_versions: bool, pub category: Option<String>, pub pre_release: bool, pub force: bool, pub start_server: bool, // connection tokens pub connection_token: Option<String>, pub connection_token_file: Option<String>, pub without_connection_token: bool, } impl CodeServerArgs { pub fn log_level(&self) -> log::Level { if self.verbose { log::Level::Trace } else { self.log.unwrap_or(log::Level::Info) } } pub fn telemetry_disabled(&self) -> bool { self.telemetry_level == Some(TelemetryLevel::Off) } pub fn command_arguments(&self) -> Vec<String> { let mut args = Vec::new(); if let Some(i) = &self.socket_path { args.push(format!("--socket-path={}", i)); } else { if let Some(i) = &self.host { args.push(format!("--host={}", i)); } if let Some(i) = &self.port { args.push(format!("--port={}", i)); } } if let Some(i) = &self.connection_token { args.push(format!("--connection-token={}", i)); } if let Some(i) = &self.connection_token_file { args.push(format!("--connection-token-file={}", i)); } if self.without_connection_token { args.push(String::from("--without-connection-token")); } if self.accept_server_license_terms { args.push(String::from("--accept-server-license-terms")); } if let Some(i) = self.telemetry_level { args.push(format!("--telemetry-level={}", i)); } if let Some(i) = self.log { args.push(format!("--log={}", i)); } for extension in &self.install_extensions { args.push(format!("--install-extension={}", extension)); } if !&self.install_extensions.is_empty() { if self.pre_release { args.push(String::from("--pre-release")); } if self.force { args.push(String::from("--force")); } } for extension in &self.uninstall_extensions { args.push(format!("--uninstall-extension={}", extension)); } if self.list_extensions { args.push(String::from("--list-extensions")); if self.show_versions { args.push(String::from("--show-versions")); } if let Some(i) = &self.category { args.push(format!("--category={}", i)); } } if self.start_server { args.push(String::from("--start-server")); } args } } /// Base server params that can be `resolve()`d to a `ResolvedServerParams`. /// Doing so fetches additional information like a commit ID if previously /// unspecified. pub struct ServerParamsRaw { pub commit_id: Option<String>, pub quality: Quality, pub code_server_args: CodeServerArgs, pub headless: bool, pub platform: Platform, } /// Server params that can be used to start a VS Code server. pub struct ResolvedServerParams { pub release: Release, pub code_server_args: CodeServerArgs, } impl ResolvedServerParams { fn as_installed_server(&self) -> InstalledServer { InstalledServer { commit: self.release.commit.clone(), quality: self.release.quality, headless: self.release.target == TargetKind::Server, } } } impl ServerParamsRaw { pub async fn resolve(self, log: &log::Logger) -> Result<ResolvedServerParams, AnyError> { Ok(ResolvedServerParams { release: self.get_or_fetch_commit_id(log).await?, code_server_args: self.code_server_args, }) } async fn get_or_fetch_commit_id(&self, log: &log::Logger) -> Result<Release, AnyError> { let target = match self.headless { true => TargetKind::Server, false => TargetKind::Web, }; if let Some(c) = &self.commit_id { return Ok(Release { commit: c.clone(), quality: self.quality, target, name: String::new(), platform: self.platform, }); } UpdateService::new(log.clone(), reqwest::Client::new()) .get_latest_commit(self.platform, target, self.quality) .await } } #[derive(Deserialize)] #[serde(rename_all = "camelCase")] #[allow(dead_code)] struct UpdateServerVersion { pub name: String, pub version: String, pub product_version: String, pub timestamp: i64, } /// Code server listening on a port address. pub struct SocketCodeServer { pub commit_id: String, pub socket: PathBuf, pub origin: CodeServerOrigin, } /// Code server listening on a socket address. pub struct PortCodeServer { pub commit_id: String, pub port: u16, pub origin: CodeServerOrigin, } /// A server listening on any address/location. pub enum AnyCodeServer { Socket(SocketCodeServer), Port(PortCodeServer), } // impl AnyCodeServer { // pub fn origin(&mut self) -> &mut CodeServerOrigin { // match self { // AnyCodeServer::Socket(p) => &mut p.origin, // AnyCodeServer::Port(p) => &mut p.origin, // } // } // } pub enum CodeServerOrigin { /// A new code server, that opens the barrier when it exits. New(Box<Child>), /// An existing code server with a PID. Existing(u32), } impl CodeServerOrigin { pub async fn wait_for_exit(&mut self) { match self { CodeServerOrigin::New(child) => { child.wait().await.ok(); } CodeServerOrigin::Existing(pid) => { let mut interval = interval(Duration::from_secs(30)); while process_exists(*pid) { interval.tick().await; } } } } pub async fn kill(&mut self) { match self { CodeServerOrigin::New(child) => { child.kill().await.ok(); } CodeServerOrigin::Existing(pid) => { kill_tree(*pid).await.ok(); } } } } async fn check_and_create_dir(path: &Path) -> Result<(), WrappedError> { tokio::fs::create_dir_all(path) .await .map_err(|e| wrap(e, "error creating server directory"))?; Ok(()) } async fn install_server_if_needed( log: &log::Logger, paths: &ServerPaths, release: &Release, ) -> Result<(), AnyError> { if paths.executable.exists() { info!( log, "Found existing installation at {}", paths.server_dir.display() ); return Ok(()); } let tar_file_path = spanf!( log, log.span("server.download"), download_server(&paths.server_dir, release, log) )?; span!( log, log.span("server.extract"), install_server(&tar_file_path, paths, log) )?; Ok(()) } async fn download_server( path: &Path, release: &Release, log: &log::Logger, ) -> Result<PathBuf, AnyError> { let response = UpdateService::new(log.clone(), reqwest::Client::new()) .get_download_stream(release) .await?; let mut save_path = path.to_owned(); let fname = response .url() .path_segments() .and_then(|segments| segments.last()) .and_then(|name| if name.is_empty() { None } else { Some(name) }) .unwrap_or("tmp.zip"); info!( log, "Downloading VS Code server {} -> {}", response.url(), save_path.display() ); save_path.push(fname); http::download_into_file( &save_path, log.get_download_logger("server download progress:"), response, ) .await?; Ok(save_path) } fn install_server( compressed_file: &Path, paths: &ServerPaths, log: &log::Logger, ) -> Result<(), AnyError> { info!(log, "Setting up server..."); unzip_downloaded_release(compressed_file, &paths.server_dir, SilentCopyProgress())?; match fs::remove_file(&compressed_file) { Ok(()) => {} Err(e) => { if e.kind() != ErrorKind::NotFound { return Err(AnyError::from(wrap(e, "error removing downloaded file"))); } } } if !paths.executable.exists() { return Err(AnyError::from(MissingEntrypointError())); } Ok(()) } /// Ensures the given list of extensions are installed on the running server. async fn do_extension_install_on_running_server( start_script_path: &Path, extensions: &[String], log: &log::Logger, ) -> Result<(), AnyError> { if extensions.is_empty() { return Ok(()); } debug!(log, "Installing extensions..."); let command = format!( "{} {}", start_script_path.display(), extensions .iter() .map(|s| get_extensions_flag(s)) .collect::<Vec<String>>() .join(" ") ); let result = capture_command("bash", &["-c", &command]).await?; if !result.status.success() { Err(AnyError::from(ExtensionInstallFailed( String::from_utf8_lossy(&result.stderr).to_string(), ))) } else { Ok(()) } } pub struct ServerBuilder<'a> { logger: &'a log::Logger, server_params: &'a ResolvedServerParams, last_used: LastUsedServers<'a>, server_paths: ServerPaths, } impl<'a> ServerBuilder<'a> { pub fn new( logger: &'a log::Logger, server_params: &'a ResolvedServerParams, launcher_paths: &'a LauncherPaths, ) -> Self { Self { logger, server_params, last_used: LastUsedServers::new(launcher_paths), server_paths: server_params .as_installed_server() .server_paths(launcher_paths), } } /// Gets any already-running server from this directory. pub async fn get_running(&self) -> Result<Option<AnyCodeServer>, AnyError> { info!( self.logger, "Checking {} and {} for a running server...", self.server_paths.logfile.display(), self.server_paths.pidfile.display() ); let pid = match self.server_paths.get_running_pid() { Some(pid) => pid, None => return Ok(None), }; info!(self.logger, "Found running server (pid={})", pid); if !Path::new(&self.server_paths.logfile).exists() { warning!(self.logger, "VS Code Server is running but its logfile is missing. Don't delete the VS Code Server manually, run the command 'code-server prune'."); return Ok(None); } do_extension_install_on_running_server( &self.server_paths.executable, &self.server_params.code_server_args.install_extensions, self.logger, ) .await?; let origin = CodeServerOrigin::Existing(pid); let contents = fs::read_to_string(&self.server_paths.logfile) .expect("Something went wrong reading log file"); if let Some(port) = parse_port_from(&contents) { Ok(Some(AnyCodeServer::Port(PortCodeServer { commit_id: self.server_params.release.commit.to_owned(), port, origin, }))) } else if let Some(socket) = parse_socket_from(&contents) { Ok(Some(AnyCodeServer::Socket(SocketCodeServer { commit_id: self.server_params.release.commit.to_owned(), socket, origin, }))) } else { Ok(None) } } /// Ensures the server is set up in the configured directory. pub async fn setup(&self) -> Result<(), AnyError> { debug!(self.logger, "Installing and setting up VS Code Server..."); check_and_create_dir(&self.server_paths.server_dir).await?; install_server_if_needed(self.logger, &self.server_paths, &self.server_params.release) .await?; debug!(self.logger, "Server setup complete"); match self.last_used.add(self.server_params.as_installed_server()) { Err(e) => warning!(self.logger, "Error adding server to last used: {}", e), Ok(count) if count > MAX_RETAINED_SERVERS => { if let Err(e) = self.last_used.trim(self.logger, MAX_RETAINED_SERVERS) { warning!(self.logger, "Error trimming old servers: {}", e); } } Ok(_) => {} } Ok(()) } pub async fn listen_on_default_socket(&self) -> Result<SocketCodeServer, AnyError> { let requested_file = if cfg!(target_os = "windows") { PathBuf::from(format!(r"\\.\pipe\vscode-server-{}", Uuid::new_v4())) } else { std::env::temp_dir().join(format!("vscode-server-{}", Uuid::new_v4())) }; self.listen_on_socket(&requested_file).await } pub async fn listen_on_socket(&self, socket: &Path) -> Result<SocketCodeServer, AnyError> { Ok(spanf!( self.logger, self.logger.span("server.start").with_attributes(vec! { KeyValue::new("commit_id", self.server_params.release.commit.to_string()), KeyValue::new("quality", format!("{}", self.server_params.release.quality)), }), self._listen_on_socket(socket) )?) } async fn _listen_on_socket(&self, socket: &Path) -> Result<SocketCodeServer, AnyError> { remove_file(&socket).await.ok(); // ignore any error if it doesn't exist let mut cmd = self.get_base_command(); cmd.arg("--start-server") .arg("--without-connection-token") .arg("--enable-remote-auto-shutdown") .arg(format!("--socket-path={}", socket.display())); let child = self.spawn_server_process(cmd)?; let log_file = self.get_logfile()?; let plog = self.logger.prefixed(&log::new_code_server_prefix()); let (mut origin, listen_rx) = monitor_server::<SocketMatcher, PathBuf>(child, Some(log_file), plog, false); let socket = match timeout(Duration::from_secs(8), listen_rx).await { Err(e) => { origin.kill().await; Err(wrap(e, "timed out looking for socket")) } Ok(Err(e)) => { origin.kill().await; Err(wrap(e, "server exited without writing socket")) } Ok(Ok(socket)) => Ok(socket), }?; info!(self.logger, "Server started"); Ok(SocketCodeServer { commit_id: self.server_params.release.commit.to_owned(), socket, origin, }) } /// Starts with a given opaque set of args. Does not set up any port or /// socket, but does return one if present, in the form of a channel. pub async fn start_opaque_with_args<M, R>( &self, args: &[String], ) -> Result<(CodeServerOrigin, Receiver<R>), AnyError> where M: ServerOutputMatcher<R>, R: 'static + Send + std::fmt::Debug, { let mut cmd = self.get_base_command(); cmd.args(args); let child = self.spawn_server_process(cmd)?; let plog = self.logger.prefixed(&log::new_code_server_prefix()); Ok(monitor_server::<M, R>(child, None, plog, true)) } fn spawn_server_process(&self, mut cmd: Command) -> Result<Child, AnyError> { info!(self.logger, "Starting server..."); debug!(self.logger, "Starting server with command... {:?}", cmd); let child = cmd .stderr(std::process::Stdio::piped()) .stdout(std::process::Stdio::piped()) .spawn() .map_err(|e| wrap(e, "error spawning server"))?; self.server_paths .write_pid(child.id().expect("expected server to have pid"))?; Ok(child) } fn get_logfile(&self) -> Result<File, WrappedError> { File::create(&self.server_paths.logfile).map_err(|e| { wrap( e, format!( "error creating log file {}", self.server_paths.logfile.display() ), ) }) } fn get_base_command(&self) -> Command { let mut cmd = Command::new(&self.server_paths.executable); cmd.stdin(std::process::Stdio::null()) .args(self.server_params.code_server_args.command_arguments()); cmd } } fn monitor_server<M, R>( mut child: Child, log_file: Option<File>, plog: log::Logger, write_directly: bool, ) -> (CodeServerOrigin, Receiver<R>) where M: ServerOutputMatcher<R>, R: 'static + Send + std::fmt::Debug, { let stdout = child .stdout .take() .expect("child did not have a handle to stdout"); let stderr = child .stderr .take() .expect("child did not have a handle to stdout"); let (listen_tx, listen_rx) = tokio::sync::oneshot::channel(); // Handle stderr and stdout in a separate task. Initially scan lines looking // for the listening port. Afterwards, just scan and write out to the file. tokio::spawn(async move { let mut stdout_reader = BufReader::new(stdout).lines(); let mut stderr_reader = BufReader::new(stderr).lines(); let write_line = |line: &str| -> std::io::Result<()> { if let Some(mut f) = log_file.as_ref() { f.write_all(line.as_bytes())?; f.write_all(&[b'\n'])?; } if write_directly { println!("{}", line); } else { trace!(plog, line); } Ok(()) }; loop { let line = tokio::select! { l = stderr_reader.next_line() => l, l = stdout_reader.next_line() => l, }; match line { Err(e) => { trace!(plog, "error reading from stdout/stderr: {}", e); return; } Ok(None) => break, Ok(Some(l)) => { write_line(&l).ok(); if let Some(listen_on) = M::match_line(&l) { trace!(plog, "parsed location: {:?}", listen_on); listen_tx.send(listen_on).ok(); break; } } } } loop { let line = tokio::select! { l = stderr_reader.next_line() => l, l = stdout_reader.next_line() => l, }; match line { Err(e) => { trace!(plog, "error reading from stdout/stderr: {}", e); break; } Ok(None) => break, Ok(Some(l)) => { write_line(&l).ok(); } } } }); let origin = CodeServerOrigin::New(Box::new(child)); (origin, listen_rx) } fn get_extensions_flag(extension_id: &str) -> String { format!("--install-extension={}", extension_id) } /// A type that can be used to scan stdout from the VS Code server. Returns /// some other type that, in turn, is returned from starting the server. pub trait ServerOutputMatcher<R> where R: Send, { fn match_line(line: &str) -> Option<R>; } /// Parses a line like "Extension host agent listening on /tmp/foo.sock" struct SocketMatcher(); impl ServerOutputMatcher<PathBuf> for SocketMatcher { fn match_line(line: &str) -> Option<PathBuf> { parse_socket_from(line) } } /// Parses a line like "Extension host agent listening on 9000" pub struct PortMatcher(); impl ServerOutputMatcher<u16> for PortMatcher { fn match_line(line: &str) -> Option<u16> { parse_port_from(line) } } /// Parses a line like "Web UI available at http://localhost:9000/?tkn=..." pub struct WebUiMatcher(); impl ServerOutputMatcher<reqwest::Url> for WebUiMatcher { fn match_line(line: &str) -> Option<reqwest::Url> { WEB_UI_RE.captures(line).and_then(|cap| { cap.get(1) .and_then(|uri| reqwest::Url::parse(uri.as_str()).ok()) }) } } /// Does not do any parsing and just immediately returns an empty result. pub struct NoOpMatcher(); impl ServerOutputMatcher<()> for NoOpMatcher { fn match_line(_: &str) -> Option<()> { Some(()) } } fn parse_socket_from(text: &str) -> Option<PathBuf> { LISTENING_PORT_RE .captures(text) .and_then(|cap| cap.get(1).map(|path| PathBuf::from(path.as_str()))) } fn parse_port_from(text: &str) -> Option<u16> { LISTENING_PORT_RE.captures(text).and_then(|cap| { cap.get(1) .and_then(|path| path.as_str().parse::<u16>().ok()) }) }
cli/src/tunnels/code_server.rs
1
https://github.com/microsoft/vscode/commit/fe5f564db16038785936282be7f6b871f34b8bd1
[ 0.8670964241027832, 0.012010075151920319, 0.000160697745741345, 0.00017290402320213616, 0.0987439826130867 ]
{ "id": 2, "code_window": [ "\t\t\t} else {\n", "\t\t\t\tentry_path.into_owned()\n", "\t\t\t});\n", "\n", "\t\t\tif let Some(p) = path.parent() {\n", "\t\t\t\tfs::create_dir_all(&p)\n", "\t\t\t\t\t.map_err(|e| wrap(e, format!(\"could not create dir for {}\", p.display())))?;\n", "\t\t\t}\n", "\n", "\t\t\tentry\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tfs::create_dir_all(p)\n" ], "file_path": "cli/src/util/tar.rs", "type": "replace", "edit_start_line_idx": 89 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/editor/common/languages/languageConfigurationRegistry'; import 'vs/editor/standalone/browser/standaloneCodeEditorService'; import 'vs/editor/standalone/browser/standaloneLayoutService'; import 'vs/platform/undoRedo/common/undoRedoService'; import 'vs/editor/common/services/languageFeatureDebounce'; import * as strings from 'vs/base/common/strings'; import * as dom from 'vs/base/browser/dom'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { Emitter, Event } from 'vs/base/common/event'; import { Keybinding, ResolvedKeybinding, SimpleKeybinding, createKeybinding } from 'vs/base/common/keybindings'; import { IDisposable, IReference, ImmortalReference, toDisposable, DisposableStore, Disposable, combinedDisposable } from 'vs/base/common/lifecycle'; import { OS, isLinux, isMacintosh } from 'vs/base/common/platform'; import Severity from 'vs/base/common/severity'; import { URI } from 'vs/base/common/uri'; import { IBulkEditOptions, IBulkEditResult, IBulkEditService, ResourceEdit, ResourceTextEdit } from 'vs/editor/browser/services/bulkEditService'; import { isDiffEditorConfigurationKey, isEditorConfigurationKey } from 'vs/editor/common/config/editorConfigurationSchema'; import { EditOperation, ISingleEditOperation } from 'vs/editor/common/core/editOperation'; import { IPosition, Position as Pos } from 'vs/editor/common/core/position'; import { Range } from 'vs/editor/common/core/range'; import { ITextModel, ITextSnapshot } from 'vs/editor/common/model'; import { IModelService } from 'vs/editor/common/services/model'; import { IResolvedTextEditorModel, ITextModelContentProvider, ITextModelService } from 'vs/editor/common/services/resolverService'; import { ITextResourceConfigurationService, ITextResourcePropertiesService, ITextResourceConfigurationChangeEvent } from 'vs/editor/common/services/textResourceConfiguration'; import { CommandsRegistry, ICommandEvent, ICommandHandler, ICommandService } from 'vs/platform/commands/common/commands'; import { IConfigurationChangeEvent, IConfigurationData, IConfigurationOverrides, IConfigurationService, IConfigurationModel, IConfigurationValue, ConfigurationTarget } from 'vs/platform/configuration/common/configuration'; import { Configuration, ConfigurationModel, ConfigurationChangeEvent } from 'vs/platform/configuration/common/configurationModels'; import { IContextKeyService, ContextKeyExpression } from 'vs/platform/contextkey/common/contextkey'; import { IConfirmation, IConfirmationResult, IDialogOptions, IDialogService, IInputResult, IShowResult } from 'vs/platform/dialogs/common/dialogs'; import { createDecorator, IInstantiationService, ServiceIdentifier } from 'vs/platform/instantiation/common/instantiation'; import { AbstractKeybindingService } from 'vs/platform/keybinding/common/abstractKeybindingService'; import { IKeybindingService, IKeyboardEvent, KeybindingsSchemaContribution } from 'vs/platform/keybinding/common/keybinding'; import { KeybindingResolver } from 'vs/platform/keybinding/common/keybindingResolver'; import { IKeybindingItem, KeybindingsRegistry } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { ResolvedKeybindingItem } from 'vs/platform/keybinding/common/resolvedKeybindingItem'; import { USLayoutResolvedKeybinding } from 'vs/platform/keybinding/common/usLayoutResolvedKeybinding'; import { ILabelService, ResourceLabelFormatter, IFormatterChangeEvent } from 'vs/platform/label/common/label'; import { INotification, INotificationHandle, INotificationService, IPromptChoice, IPromptOptions, NoOpNotification, IStatusMessageOptions } from 'vs/platform/notification/common/notification'; import { IProgressRunner, IEditorProgressService, IProgressService, IProgress, IProgressCompositeOptions, IProgressDialogOptions, IProgressNotificationOptions, IProgressOptions, IProgressStep, IProgressWindowOptions } from 'vs/platform/progress/common/progress'; import { ITelemetryInfo, ITelemetryService, TelemetryLevel } from 'vs/platform/telemetry/common/telemetry'; import { ISingleFolderWorkspaceIdentifier, IWorkspaceIdentifier, IWorkspace, IWorkspaceContextService, IWorkspaceFolder, IWorkspaceFoldersChangeEvent, IWorkspaceFoldersWillChangeEvent, WorkbenchState, WorkspaceFolder } from 'vs/platform/workspace/common/workspace'; import { ILayoutService } from 'vs/platform/layout/browser/layoutService'; import { StandaloneServicesNLS } from 'vs/editor/common/standaloneStrings'; import { ClassifiedEvent, StrictPropertyCheck, OmitMetadata, IGDPRProperty } from 'vs/platform/telemetry/common/gdprTypings'; import { basename } from 'vs/base/common/resources'; import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService'; import { ConsoleLogger, ILogService, LogService } from 'vs/platform/log/common/log'; import { IWorkspaceTrustManagementService, IWorkspaceTrustTransitionParticipant, IWorkspaceTrustUriInfo } from 'vs/platform/workspace/common/workspaceTrust'; import { EditorOption } from 'vs/editor/common/config/editorOptions'; import { ICodeEditor, IDiffEditor } from 'vs/editor/browser/editorBrowser'; import { IContextMenuService, IContextViewDelegate, IContextViewService } from 'vs/platform/contextview/browser/contextView'; import { ContextViewService } from 'vs/platform/contextview/browser/contextViewService'; import { LanguageService } from 'vs/editor/common/services/languageService'; import { ContextMenuService } from 'vs/platform/contextview/browser/contextMenuService'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { getSingletonServiceDescriptors, InstantiationType, registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { OpenerService } from 'vs/editor/browser/services/openerService'; import { IEditorWorkerService } from 'vs/editor/common/services/editorWorker'; import { EditorWorkerService } from 'vs/editor/browser/services/editorWorkerService'; import { ILanguageService } from 'vs/editor/common/languages/language'; import { MarkerDecorationsService } from 'vs/editor/common/services/markerDecorationsService'; import { IMarkerDecorationsService } from 'vs/editor/common/services/markerDecorations'; import { ModelService } from 'vs/editor/common/services/modelService'; import { StandaloneQuickInputService } from 'vs/editor/standalone/browser/quickInput/standaloneQuickInputService'; import { StandaloneThemeService } from 'vs/editor/standalone/browser/standaloneThemeService'; import { IStandaloneThemeService } from 'vs/editor/standalone/common/standaloneTheme'; import { AccessibilityService } from 'vs/platform/accessibility/browser/accessibilityService'; import { IAccessibilityService } from 'vs/platform/accessibility/common/accessibility'; import { IMenuService } from 'vs/platform/actions/common/actions'; import { MenuService } from 'vs/platform/actions/common/menuService'; import { BrowserClipboardService } from 'vs/platform/clipboard/browser/clipboardService'; import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService'; import { ContextKeyService } from 'vs/platform/contextkey/browser/contextKeyService'; import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors'; import { InstantiationService } from 'vs/platform/instantiation/common/instantiationService'; import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection'; import { IListService, ListService } from 'vs/platform/list/browser/listService'; import { IMarkerService } from 'vs/platform/markers/common/markers'; import { MarkerService } from 'vs/platform/markers/common/markerService'; import { IOpenerService } from 'vs/platform/opener/common/opener'; import { IQuickInputService } from 'vs/platform/quickinput/common/quickInput'; import { IStorageService, InMemoryStorageService } from 'vs/platform/storage/common/storage'; import { staticObservableValue } from 'vs/base/common/observableValue'; import 'vs/editor/common/services/languageFeaturesService'; import { DefaultConfigurationModel } from 'vs/platform/configuration/common/configurations'; import { WorkspaceEdit } from 'vs/editor/common/languages'; class SimpleModel implements IResolvedTextEditorModel { private readonly model: ITextModel; private readonly _onWillDispose: Emitter<void>; constructor(model: ITextModel) { this.model = model; this._onWillDispose = new Emitter<void>(); } public get onWillDispose(): Event<void> { return this._onWillDispose.event; } public resolve(): Promise<void> { return Promise.resolve(); } public get textEditorModel(): ITextModel { return this.model; } public createSnapshot(): ITextSnapshot { return this.model.createSnapshot(); } public isReadonly(): boolean { return false; } private disposed = false; public dispose(): void { this.disposed = true; this._onWillDispose.fire(); } public isDisposed(): boolean { return this.disposed; } public isResolved(): boolean { return true; } public getLanguageId(): string | undefined { return this.model.getLanguageId(); } } class StandaloneTextModelService implements ITextModelService { public _serviceBrand: undefined; constructor( @IModelService private readonly modelService: IModelService ) { } public createModelReference(resource: URI): Promise<IReference<IResolvedTextEditorModel>> { const model = this.modelService.getModel(resource); if (!model) { return Promise.reject(new Error(`Model not found`)); } return Promise.resolve(new ImmortalReference(new SimpleModel(model))); } public registerTextModelContentProvider(scheme: string, provider: ITextModelContentProvider): IDisposable { return { dispose: function () { /* no op */ } }; } public canHandleResource(resource: URI): boolean { return false; } } class StandaloneEditorProgressService implements IEditorProgressService { declare readonly _serviceBrand: undefined; private static NULL_PROGRESS_RUNNER: IProgressRunner = { done: () => { }, total: () => { }, worked: () => { } }; show(infinite: true, delay?: number): IProgressRunner; show(total: number, delay?: number): IProgressRunner; show(): IProgressRunner { return StandaloneEditorProgressService.NULL_PROGRESS_RUNNER; } async showWhile(promise: Promise<any>, delay?: number): Promise<void> { await promise; } } class StandaloneProgressService implements IProgressService { declare readonly _serviceBrand: undefined; withProgress<R>(_options: IProgressOptions | IProgressDialogOptions | IProgressNotificationOptions | IProgressWindowOptions | IProgressCompositeOptions, task: (progress: IProgress<IProgressStep>) => Promise<R>, onDidCancel?: ((choice?: number | undefined) => void) | undefined): Promise<R> { return task({ report: () => { }, }); } } class StandaloneDialogService implements IDialogService { public _serviceBrand: undefined; readonly onWillShowDialog = Event.None; readonly onDidShowDialog = Event.None; public confirm(confirmation: IConfirmation): Promise<IConfirmationResult> { return this.doConfirm(confirmation).then(confirmed => { return { confirmed, checkboxChecked: false // unsupported } as IConfirmationResult; }); } private doConfirm(confirmation: IConfirmation): Promise<boolean> { let messageText = confirmation.message; if (confirmation.detail) { messageText = messageText + '\n\n' + confirmation.detail; } return Promise.resolve(window.confirm(messageText)); } public show(severity: Severity, message: string, buttons: string[], options?: IDialogOptions): Promise<IShowResult> { return Promise.resolve({ choice: 0 }); } public input(): Promise<IInputResult> { return Promise.resolve({ choice: 0 }); // unsupported } public about(): Promise<void> { return Promise.resolve(undefined); } } export class StandaloneNotificationService implements INotificationService { readonly onDidAddNotification: Event<INotification> = Event.None; readonly onDidRemoveNotification: Event<INotification> = Event.None; readonly onDidChangeDoNotDisturbMode: Event<void> = Event.None; public _serviceBrand: undefined; public doNotDisturbMode: boolean = false; private static readonly NO_OP: INotificationHandle = new NoOpNotification(); public info(message: string): INotificationHandle { return this.notify({ severity: Severity.Info, message }); } public warn(message: string): INotificationHandle { return this.notify({ severity: Severity.Warning, message }); } public error(error: string | Error): INotificationHandle { return this.notify({ severity: Severity.Error, message: error }); } public notify(notification: INotification): INotificationHandle { switch (notification.severity) { case Severity.Error: console.error(notification.message); break; case Severity.Warning: console.warn(notification.message); break; default: console.log(notification.message); break; } return StandaloneNotificationService.NO_OP; } public prompt(severity: Severity, message: string, choices: IPromptChoice[], options?: IPromptOptions): INotificationHandle { return StandaloneNotificationService.NO_OP; } public status(message: string | Error, options?: IStatusMessageOptions): IDisposable { return Disposable.None; } } export class StandaloneCommandService implements ICommandService { declare readonly _serviceBrand: undefined; private readonly _instantiationService: IInstantiationService; private readonly _onWillExecuteCommand = new Emitter<ICommandEvent>(); private readonly _onDidExecuteCommand = new Emitter<ICommandEvent>(); public readonly onWillExecuteCommand: Event<ICommandEvent> = this._onWillExecuteCommand.event; public readonly onDidExecuteCommand: Event<ICommandEvent> = this._onDidExecuteCommand.event; constructor( @IInstantiationService instantiationService: IInstantiationService ) { this._instantiationService = instantiationService; } public executeCommand<T>(id: string, ...args: any[]): Promise<T> { const command = CommandsRegistry.getCommand(id); if (!command) { return Promise.reject(new Error(`command '${id}' not found`)); } try { this._onWillExecuteCommand.fire({ commandId: id, args }); const result = this._instantiationService.invokeFunction.apply(this._instantiationService, [command.handler, ...args]) as T; this._onDidExecuteCommand.fire({ commandId: id, args }); return Promise.resolve(result); } catch (err) { return Promise.reject(err); } } } export interface IKeybindingRule { keybinding: number; command?: string | null; commandArgs?: any; when?: ContextKeyExpression | null; } export class StandaloneKeybindingService extends AbstractKeybindingService { private _cachedResolver: KeybindingResolver | null; private _dynamicKeybindings: IKeybindingItem[]; private readonly _domNodeListeners: DomNodeListeners[]; constructor( @IContextKeyService contextKeyService: IContextKeyService, @ICommandService commandService: ICommandService, @ITelemetryService telemetryService: ITelemetryService, @INotificationService notificationService: INotificationService, @ILogService logService: ILogService, @ICodeEditorService codeEditorService: ICodeEditorService ) { super(contextKeyService, commandService, telemetryService, notificationService, logService); this._cachedResolver = null; this._dynamicKeybindings = []; this._domNodeListeners = []; const addContainer = (domNode: HTMLElement) => { const disposables = new DisposableStore(); // for standard keybindings disposables.add(dom.addDisposableListener(domNode, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => { const keyEvent = new StandardKeyboardEvent(e); const shouldPreventDefault = this._dispatch(keyEvent, keyEvent.target); if (shouldPreventDefault) { keyEvent.preventDefault(); keyEvent.stopPropagation(); } })); // for single modifier chord keybindings (e.g. shift shift) disposables.add(dom.addDisposableListener(domNode, dom.EventType.KEY_UP, (e: KeyboardEvent) => { const keyEvent = new StandardKeyboardEvent(e); const shouldPreventDefault = this._singleModifierDispatch(keyEvent, keyEvent.target); if (shouldPreventDefault) { keyEvent.preventDefault(); } })); this._domNodeListeners.push(new DomNodeListeners(domNode, disposables)); }; const removeContainer = (domNode: HTMLElement) => { for (let i = 0; i < this._domNodeListeners.length; i++) { const domNodeListeners = this._domNodeListeners[i]; if (domNodeListeners.domNode === domNode) { this._domNodeListeners.splice(i, 1); domNodeListeners.dispose(); } } }; const addCodeEditor = (codeEditor: ICodeEditor) => { if (codeEditor.getOption(EditorOption.inDiffEditor)) { return; } addContainer(codeEditor.getContainerDomNode()); }; const removeCodeEditor = (codeEditor: ICodeEditor) => { if (codeEditor.getOption(EditorOption.inDiffEditor)) { return; } removeContainer(codeEditor.getContainerDomNode()); }; this._register(codeEditorService.onCodeEditorAdd(addCodeEditor)); this._register(codeEditorService.onCodeEditorRemove(removeCodeEditor)); codeEditorService.listCodeEditors().forEach(addCodeEditor); const addDiffEditor = (diffEditor: IDiffEditor) => { addContainer(diffEditor.getContainerDomNode()); }; const removeDiffEditor = (diffEditor: IDiffEditor) => { removeContainer(diffEditor.getContainerDomNode()); }; this._register(codeEditorService.onDiffEditorAdd(addDiffEditor)); this._register(codeEditorService.onDiffEditorRemove(removeDiffEditor)); codeEditorService.listDiffEditors().forEach(addDiffEditor); } public addDynamicKeybinding(command: string, keybinding: number, handler: ICommandHandler, when: ContextKeyExpression | undefined): IDisposable { return combinedDisposable( CommandsRegistry.registerCommand(command, handler), this.addDynamicKeybindings([{ keybinding, command, when }]) ); } public addDynamicKeybindings(rules: IKeybindingRule[]): IDisposable { const entries: IKeybindingItem[] = rules.map((rule) => { const keybinding = createKeybinding(rule.keybinding, OS); return { keybinding: keybinding?.parts ?? null, command: rule.command ?? null, commandArgs: rule.commandArgs, when: rule.when, weight1: 1000, weight2: 0, extensionId: null, isBuiltinExtension: false }; }); this._dynamicKeybindings = this._dynamicKeybindings.concat(entries); this.updateResolver(); return toDisposable(() => { // Search the first entry and remove them all since they will be contiguous for (let i = 0; i < this._dynamicKeybindings.length; i++) { if (this._dynamicKeybindings[i] === entries[0]) { this._dynamicKeybindings.splice(i, entries.length); this.updateResolver(); return; } } }); } private updateResolver(): void { this._cachedResolver = null; this._onDidUpdateKeybindings.fire(); } protected _getResolver(): KeybindingResolver { if (!this._cachedResolver) { const defaults = this._toNormalizedKeybindingItems(KeybindingsRegistry.getDefaultKeybindings(), true); const overrides = this._toNormalizedKeybindingItems(this._dynamicKeybindings, false); this._cachedResolver = new KeybindingResolver(defaults, overrides, (str) => this._log(str)); } return this._cachedResolver; } protected _documentHasFocus(): boolean { return document.hasFocus(); } private _toNormalizedKeybindingItems(items: IKeybindingItem[], isDefault: boolean): ResolvedKeybindingItem[] { const result: ResolvedKeybindingItem[] = []; let resultLen = 0; for (const item of items) { const when = item.when || undefined; const keybinding = item.keybinding; if (!keybinding) { // This might be a removal keybinding item in user settings => accept it result[resultLen++] = new ResolvedKeybindingItem(undefined, item.command, item.commandArgs, when, isDefault, null, false); } else { const resolvedKeybindings = USLayoutResolvedKeybinding.resolveUserBinding(keybinding, OS); for (const resolvedKeybinding of resolvedKeybindings) { result[resultLen++] = new ResolvedKeybindingItem(resolvedKeybinding, item.command, item.commandArgs, when, isDefault, null, false); } } } return result; } public resolveKeybinding(keybinding: Keybinding): ResolvedKeybinding[] { return [new USLayoutResolvedKeybinding(keybinding, OS)]; } public resolveKeyboardEvent(keyboardEvent: IKeyboardEvent): ResolvedKeybinding { const keybinding = new SimpleKeybinding( keyboardEvent.ctrlKey, keyboardEvent.shiftKey, keyboardEvent.altKey, keyboardEvent.metaKey, keyboardEvent.keyCode ).toChord(); return new USLayoutResolvedKeybinding(keybinding, OS); } public resolveUserBinding(userBinding: string): ResolvedKeybinding[] { return []; } public _dumpDebugInfo(): string { return ''; } public _dumpDebugInfoJSON(): string { return ''; } public registerSchemaContribution(contribution: KeybindingsSchemaContribution): void { // noop } } class DomNodeListeners extends Disposable { constructor( public readonly domNode: HTMLElement, disposables: DisposableStore ) { super(); this._register(disposables); } } function isConfigurationOverrides(thing: any): thing is IConfigurationOverrides { return thing && typeof thing === 'object' && (!thing.overrideIdentifier || typeof thing.overrideIdentifier === 'string') && (!thing.resource || thing.resource instanceof URI); } export class StandaloneConfigurationService implements IConfigurationService { declare readonly _serviceBrand: undefined; private readonly _onDidChangeConfiguration = new Emitter<IConfigurationChangeEvent>(); public readonly onDidChangeConfiguration: Event<IConfigurationChangeEvent> = this._onDidChangeConfiguration.event; private readonly _configuration: Configuration; constructor() { this._configuration = new Configuration(new DefaultConfigurationModel(), new ConfigurationModel(), new ConfigurationModel(), new ConfigurationModel()); } getValue<T>(): T; getValue<T>(section: string): T; getValue<T>(overrides: IConfigurationOverrides): T; getValue<T>(section: string, overrides: IConfigurationOverrides): T; getValue(arg1?: any, arg2?: any): any { const section = typeof arg1 === 'string' ? arg1 : undefined; const overrides = isConfigurationOverrides(arg1) ? arg1 : isConfigurationOverrides(arg2) ? arg2 : {}; return this._configuration.getValue(section, overrides, undefined); } public updateValues(values: [string, any][]): Promise<void> { const previous = { data: this._configuration.toData() }; const changedKeys: string[] = []; for (const entry of values) { const [key, value] = entry; if (this.getValue(key) === value) { continue; } this._configuration.updateValue(key, value); changedKeys.push(key); } if (changedKeys.length > 0) { const configurationChangeEvent = new ConfigurationChangeEvent({ keys: changedKeys, overrides: [] }, previous, this._configuration); configurationChangeEvent.source = ConfigurationTarget.MEMORY; configurationChangeEvent.sourceConfig = null; this._onDidChangeConfiguration.fire(configurationChangeEvent); } return Promise.resolve(); } public updateValue(key: string, value: any, arg3?: any, arg4?: any): Promise<void> { return this.updateValues([[key, value]]); } public inspect<C>(key: string, options: IConfigurationOverrides = {}): IConfigurationValue<C> { return this._configuration.inspect<C>(key, options, undefined); } public keys() { return this._configuration.keys(undefined); } public reloadConfiguration(): Promise<void> { return Promise.resolve(undefined); } public getConfigurationData(): IConfigurationData | null { const emptyModel: IConfigurationModel = { contents: {}, keys: [], overrides: [] }; return { defaults: emptyModel, policy: emptyModel, application: emptyModel, user: emptyModel, workspace: emptyModel, folders: [] }; } } class StandaloneResourceConfigurationService implements ITextResourceConfigurationService { declare readonly _serviceBrand: undefined; private readonly _onDidChangeConfiguration = new Emitter<ITextResourceConfigurationChangeEvent>(); public readonly onDidChangeConfiguration = this._onDidChangeConfiguration.event; constructor( @IConfigurationService private readonly configurationService: StandaloneConfigurationService ) { this.configurationService.onDidChangeConfiguration((e) => { this._onDidChangeConfiguration.fire({ affectedKeys: e.affectedKeys, affectsConfiguration: (resource: URI, configuration: string) => e.affectsConfiguration(configuration) }); }); } getValue<T>(resource: URI, section?: string): T; getValue<T>(resource: URI, position?: IPosition, section?: string): T; getValue<T>(resource: any, arg2?: any, arg3?: any) { const position: IPosition | null = Pos.isIPosition(arg2) ? arg2 : null; const section: string | undefined = position ? (typeof arg3 === 'string' ? arg3 : undefined) : (typeof arg2 === 'string' ? arg2 : undefined); if (typeof section === 'undefined') { return this.configurationService.getValue<T>(); } return this.configurationService.getValue<T>(section); } updateValue(resource: URI, key: string, value: any, configurationTarget?: ConfigurationTarget): Promise<void> { return this.configurationService.updateValue(key, value, { resource }, configurationTarget); } } class StandaloneResourcePropertiesService implements ITextResourcePropertiesService { declare readonly _serviceBrand: undefined; constructor( @IConfigurationService private readonly configurationService: IConfigurationService, ) { } getEOL(resource: URI, language?: string): string { const eol = this.configurationService.getValue('files.eol', { overrideIdentifier: language, resource }); if (eol && typeof eol === 'string' && eol !== 'auto') { return eol; } return (isLinux || isMacintosh) ? '\n' : '\r\n'; } } class StandaloneTelemetryService implements ITelemetryService { declare readonly _serviceBrand: undefined; public telemetryLevel = staticObservableValue(TelemetryLevel.NONE); public sendErrorTelemetry = false; public setEnabled(value: boolean): void { } public setExperimentProperty(name: string, value: string): void { } public publicLog(eventName: string, data?: any): Promise<void> { return Promise.resolve(undefined); } publicLog2<E extends ClassifiedEvent<OmitMetadata<T>> = never, T extends IGDPRProperty = never>(eventName: string, data?: StrictPropertyCheck<T, E>) { return this.publicLog(eventName, data as any); } public publicLogError(eventName: string, data?: any): Promise<void> { return Promise.resolve(undefined); } publicLogError2<E extends ClassifiedEvent<OmitMetadata<T>> = never, T extends IGDPRProperty = never>(eventName: string, data?: StrictPropertyCheck<T, E>) { return this.publicLogError(eventName, data as any); } public getTelemetryInfo(): Promise<ITelemetryInfo> { throw new Error(`Not available`); } } class StandaloneWorkspaceContextService implements IWorkspaceContextService { public _serviceBrand: undefined; private static readonly SCHEME = 'inmemory'; private readonly _onDidChangeWorkspaceName = new Emitter<void>(); public readonly onDidChangeWorkspaceName: Event<void> = this._onDidChangeWorkspaceName.event; private readonly _onWillChangeWorkspaceFolders = new Emitter<IWorkspaceFoldersWillChangeEvent>(); public readonly onWillChangeWorkspaceFolders: Event<IWorkspaceFoldersWillChangeEvent> = this._onWillChangeWorkspaceFolders.event; private readonly _onDidChangeWorkspaceFolders = new Emitter<IWorkspaceFoldersChangeEvent>(); public readonly onDidChangeWorkspaceFolders: Event<IWorkspaceFoldersChangeEvent> = this._onDidChangeWorkspaceFolders.event; private readonly _onDidChangeWorkbenchState = new Emitter<WorkbenchState>(); public readonly onDidChangeWorkbenchState: Event<WorkbenchState> = this._onDidChangeWorkbenchState.event; private readonly workspace: IWorkspace; constructor() { const resource = URI.from({ scheme: StandaloneWorkspaceContextService.SCHEME, authority: 'model', path: '/' }); this.workspace = { id: '4064f6ec-cb38-4ad0-af64-ee6467e63c82', folders: [new WorkspaceFolder({ uri: resource, name: '', index: 0 })] }; } getCompleteWorkspace(): Promise<IWorkspace> { return Promise.resolve(this.getWorkspace()); } public getWorkspace(): IWorkspace { return this.workspace; } public getWorkbenchState(): WorkbenchState { if (this.workspace) { if (this.workspace.configuration) { return WorkbenchState.WORKSPACE; } return WorkbenchState.FOLDER; } return WorkbenchState.EMPTY; } public getWorkspaceFolder(resource: URI): IWorkspaceFolder | null { return resource && resource.scheme === StandaloneWorkspaceContextService.SCHEME ? this.workspace.folders[0] : null; } public isInsideWorkspace(resource: URI): boolean { return resource && resource.scheme === StandaloneWorkspaceContextService.SCHEME; } public isCurrentWorkspace(workspaceIdOrFolder: IWorkspaceIdentifier | ISingleFolderWorkspaceIdentifier | URI): boolean { return true; } } export function updateConfigurationService(configurationService: IConfigurationService, source: any, isDiffEditor: boolean): void { if (!source) { return; } if (!(configurationService instanceof StandaloneConfigurationService)) { return; } const toUpdate: [string, any][] = []; Object.keys(source).forEach((key) => { if (isEditorConfigurationKey(key)) { toUpdate.push([`editor.${key}`, source[key]]); } if (isDiffEditor && isDiffEditorConfigurationKey(key)) { toUpdate.push([`diffEditor.${key}`, source[key]]); } }); if (toUpdate.length > 0) { configurationService.updateValues(toUpdate); } } class StandaloneBulkEditService implements IBulkEditService { declare readonly _serviceBrand: undefined; constructor( @IModelService private readonly _modelService: IModelService ) { // } hasPreviewHandler(): false { return false; } setPreviewHandler(): IDisposable { return Disposable.None; } async apply(editsIn: ResourceEdit[] | WorkspaceEdit, _options?: IBulkEditOptions): Promise<IBulkEditResult> { const edits = Array.isArray(editsIn) ? editsIn : ResourceEdit.convert(editsIn); const textEdits = new Map<ITextModel, ISingleEditOperation[]>(); for (const edit of edits) { if (!(edit instanceof ResourceTextEdit)) { throw new Error('bad edit - only text edits are supported'); } const model = this._modelService.getModel(edit.resource); if (!model) { throw new Error('bad edit - model not found'); } if (typeof edit.versionId === 'number' && model.getVersionId() !== edit.versionId) { throw new Error('bad state - model changed in the meantime'); } let array = textEdits.get(model); if (!array) { array = []; textEdits.set(model, array); } array.push(EditOperation.replaceMove(Range.lift(edit.textEdit.range), edit.textEdit.text)); } let totalEdits = 0; let totalFiles = 0; for (const [model, edits] of textEdits) { model.pushStackElement(); model.pushEditOperations([], edits, () => []); model.pushStackElement(); totalFiles += 1; totalEdits += edits.length; } return { ariaSummary: strings.format(StandaloneServicesNLS.bulkEditServiceSummary, totalEdits, totalFiles), isApplied: totalEdits > 0 }; } } class StandaloneUriLabelService implements ILabelService { declare readonly _serviceBrand: undefined; public readonly onDidChangeFormatters: Event<IFormatterChangeEvent> = Event.None; public getUriLabel(resource: URI, options?: { relative?: boolean; forceNoTildify?: boolean }): string { if (resource.scheme === 'file') { return resource.fsPath; } return resource.path; } getUriBasenameLabel(resource: URI): string { return basename(resource); } public getWorkspaceLabel(workspace: IWorkspaceIdentifier | ISingleFolderWorkspaceIdentifier | URI | IWorkspace, options?: { verbose: boolean }): string { return ''; } public getSeparator(scheme: string, authority?: string): '/' | '\\' { return '/'; } public registerFormatter(formatter: ResourceLabelFormatter): IDisposable { throw new Error('Not implemented'); } public registerCachedFormatter(formatter: ResourceLabelFormatter): IDisposable { return this.registerFormatter(formatter); } public getHostLabel(): string { return ''; } public getHostTooltip(): string | undefined { return undefined; } } class StandaloneContextViewService extends ContextViewService { constructor( @ILayoutService layoutService: ILayoutService, @ICodeEditorService private readonly _codeEditorService: ICodeEditorService, ) { super(layoutService); } override showContextView(delegate: IContextViewDelegate, container?: HTMLElement, shadowRoot?: boolean): IDisposable { if (!container) { const codeEditor = this._codeEditorService.getFocusedCodeEditor() || this._codeEditorService.getActiveCodeEditor(); if (codeEditor) { container = codeEditor.getContainerDomNode(); } } return super.showContextView(delegate, container, shadowRoot); } } class StandaloneWorkspaceTrustManagementService implements IWorkspaceTrustManagementService { _serviceBrand: undefined; private _neverEmitter = new Emitter<never>(); public readonly onDidChangeTrust: Event<boolean> = this._neverEmitter.event; onDidChangeTrustedFolders: Event<void> = this._neverEmitter.event; public readonly workspaceResolved = Promise.resolve(); public readonly workspaceTrustInitialized = Promise.resolve(); public readonly acceptsOutOfWorkspaceFiles = true; isWorkspaceTrusted(): boolean { return true; } isWorkspaceTrustForced(): boolean { return false; } canSetParentFolderTrust(): boolean { return false; } async setParentFolderTrust(trusted: boolean): Promise<void> { // noop } canSetWorkspaceTrust(): boolean { return false; } async setWorkspaceTrust(trusted: boolean): Promise<void> { // noop } getUriTrustInfo(uri: URI): Promise<IWorkspaceTrustUriInfo> { throw new Error('Method not supported.'); } async setUrisTrust(uri: URI[], trusted: boolean): Promise<void> { // noop } getTrustedUris(): URI[] { return []; } async setTrustedUris(uris: URI[]): Promise<void> { // noop } addWorkspaceTrustTransitionParticipant(participant: IWorkspaceTrustTransitionParticipant): IDisposable { throw new Error('Method not supported.'); } } class StandaloneLanguageService extends LanguageService { constructor() { super(); } } class StandaloneLogService extends LogService { constructor() { super(new ConsoleLogger()); } } class StandaloneContextMenuService extends ContextMenuService { constructor( @ITelemetryService telemetryService: ITelemetryService, @INotificationService notificationService: INotificationService, @IContextViewService contextViewService: IContextViewService, @IKeybindingService keybindingService: IKeybindingService, @IThemeService themeService: IThemeService, @IMenuService menuService: IMenuService, @IContextKeyService contextKeyService: IContextKeyService, ) { super(telemetryService, notificationService, contextViewService, keybindingService, themeService, menuService, contextKeyService); this.configure({ blockMouse: false }); // we do not want that in the standalone editor } } export interface IEditorOverrideServices { [index: string]: any; } registerSingleton(IConfigurationService, StandaloneConfigurationService, InstantiationType.Eager); registerSingleton(ITextResourceConfigurationService, StandaloneResourceConfigurationService, InstantiationType.Eager); registerSingleton(ITextResourcePropertiesService, StandaloneResourcePropertiesService, InstantiationType.Eager); registerSingleton(IWorkspaceContextService, StandaloneWorkspaceContextService, InstantiationType.Eager); registerSingleton(ILabelService, StandaloneUriLabelService, InstantiationType.Eager); registerSingleton(ITelemetryService, StandaloneTelemetryService, InstantiationType.Eager); registerSingleton(IDialogService, StandaloneDialogService, InstantiationType.Eager); registerSingleton(INotificationService, StandaloneNotificationService, InstantiationType.Eager); registerSingleton(IMarkerService, MarkerService, InstantiationType.Eager); registerSingleton(ILanguageService, StandaloneLanguageService, InstantiationType.Eager); registerSingleton(IStandaloneThemeService, StandaloneThemeService, InstantiationType.Eager); registerSingleton(ILogService, StandaloneLogService, InstantiationType.Eager); registerSingleton(IModelService, ModelService, InstantiationType.Eager); registerSingleton(IMarkerDecorationsService, MarkerDecorationsService, InstantiationType.Eager); registerSingleton(IContextKeyService, ContextKeyService, InstantiationType.Eager); registerSingleton(IProgressService, StandaloneProgressService, InstantiationType.Eager); registerSingleton(IEditorProgressService, StandaloneEditorProgressService, InstantiationType.Eager); registerSingleton(IStorageService, InMemoryStorageService, InstantiationType.Eager); registerSingleton(IEditorWorkerService, EditorWorkerService, InstantiationType.Eager); registerSingleton(IBulkEditService, StandaloneBulkEditService, InstantiationType.Eager); registerSingleton(IWorkspaceTrustManagementService, StandaloneWorkspaceTrustManagementService, InstantiationType.Eager); registerSingleton(ITextModelService, StandaloneTextModelService, InstantiationType.Eager); registerSingleton(IAccessibilityService, AccessibilityService, InstantiationType.Eager); registerSingleton(IListService, ListService, InstantiationType.Eager); registerSingleton(ICommandService, StandaloneCommandService, InstantiationType.Eager); registerSingleton(IKeybindingService, StandaloneKeybindingService, InstantiationType.Eager); registerSingleton(IQuickInputService, StandaloneQuickInputService, InstantiationType.Eager); registerSingleton(IContextViewService, StandaloneContextViewService, InstantiationType.Eager); registerSingleton(IOpenerService, OpenerService, InstantiationType.Eager); registerSingleton(IClipboardService, BrowserClipboardService, InstantiationType.Eager); registerSingleton(IContextMenuService, StandaloneContextMenuService, InstantiationType.Eager); registerSingleton(IMenuService, MenuService, InstantiationType.Eager); /** * We don't want to eagerly instantiate services because embedders get a one time chance * to override services when they create the first editor. */ export module StandaloneServices { const serviceCollection = new ServiceCollection(); for (const [id, descriptor] of getSingletonServiceDescriptors()) { serviceCollection.set(id, descriptor); } const instantiationService = new InstantiationService(serviceCollection, true); serviceCollection.set(IInstantiationService, instantiationService); export function get<T>(serviceId: ServiceIdentifier<T>): T { const r = serviceCollection.get(serviceId); if (!r) { throw new Error('Missing service ' + serviceId); } if (r instanceof SyncDescriptor) { return instantiationService.invokeFunction((accessor) => accessor.get(serviceId)); } else { return r; } } let initialized = false; export function initialize(overrides: IEditorOverrideServices): IInstantiationService { if (initialized) { return instantiationService; } initialized = true; // Add singletons that were registered after this module loaded for (const [id, descriptor] of getSingletonServiceDescriptors()) { if (!serviceCollection.get(id)) { serviceCollection.set(id, descriptor); } } // Initialize the service collection with the overrides, but only if the // service was not instantiated in the meantime. for (const serviceId in overrides) { if (overrides.hasOwnProperty(serviceId)) { const serviceIdentifier = createDecorator(serviceId); const r = serviceCollection.get(serviceIdentifier); if (r instanceof SyncDescriptor) { serviceCollection.set(serviceIdentifier, overrides[serviceId]); } } } return instantiationService; } }
src/vs/editor/standalone/browser/standaloneServices.ts
0
https://github.com/microsoft/vscode/commit/fe5f564db16038785936282be7f6b871f34b8bd1
[ 0.0002920870902016759, 0.00017590126662980765, 0.0001652969658607617, 0.0001749188668327406, 0.00001341394818155095 ]
{ "id": 2, "code_window": [ "\t\t\t} else {\n", "\t\t\t\tentry_path.into_owned()\n", "\t\t\t});\n", "\n", "\t\t\tif let Some(p) = path.parent() {\n", "\t\t\t\tfs::create_dir_all(&p)\n", "\t\t\t\t\t.map_err(|e| wrap(e, format!(\"could not create dir for {}\", p.display())))?;\n", "\t\t\t}\n", "\n", "\t\t\tentry\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tfs::create_dir_all(p)\n" ], "file_path": "cli/src/util/tar.rs", "type": "replace", "edit_start_line_idx": 89 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as fs from 'fs'; import { Uri } from 'vscode'; import { FileSystemProvider, FileType } from '../requests'; export function getNodeFileFS(): FileSystemProvider { function ensureFileUri(location: string) { if (!location.startsWith('file:')) { throw new Error('fileRequestService can only handle file URLs'); } } return { stat(location: string) { ensureFileUri(location); return new Promise((c, e) => { const uri = Uri.parse(location); fs.stat(uri.fsPath, (err, stats) => { if (err) { if (err.code === 'ENOENT') { return c({ type: FileType.Unknown, ctime: -1, mtime: -1, size: -1 }); } else { return e(err); } } let type = FileType.Unknown; if (stats.isFile()) { type = FileType.File; } else if (stats.isDirectory()) { type = FileType.Directory; } else if (stats.isSymbolicLink()) { type = FileType.SymbolicLink; } c({ type, ctime: stats.ctime.getTime(), mtime: stats.mtime.getTime(), size: stats.size }); }); }); }, readDirectory(location: string) { ensureFileUri(location); return new Promise((c, e) => { const path = Uri.parse(location).fsPath; fs.readdir(path, { withFileTypes: true }, (err, children) => { if (err) { return e(err); } c(children.map(stat => { if (stat.isSymbolicLink()) { return [stat.name, FileType.SymbolicLink]; } else if (stat.isDirectory()) { return [stat.name, FileType.Directory]; } else if (stat.isFile()) { return [stat.name, FileType.File]; } else { return [stat.name, FileType.Unknown]; } })); }); }); } }; }
extensions/html-language-features/client/src/node/nodeFs.ts
0
https://github.com/microsoft/vscode/commit/fe5f564db16038785936282be7f6b871f34b8bd1
[ 0.0042863329872488976, 0.0006880766013637185, 0.0001646970777073875, 0.00017584497982170433, 0.0013600182719528675 ]
{ "id": 2, "code_window": [ "\t\t\t} else {\n", "\t\t\t\tentry_path.into_owned()\n", "\t\t\t});\n", "\n", "\t\t\tif let Some(p) = path.parent() {\n", "\t\t\t\tfs::create_dir_all(&p)\n", "\t\t\t\t\t.map_err(|e| wrap(e, format!(\"could not create dir for {}\", p.display())))?;\n", "\t\t\t}\n", "\n", "\t\t\tentry\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tfs::create_dir_all(p)\n" ], "file_path": "cli/src/util/tar.rs", "type": "replace", "edit_start_line_idx": 89 }
// snippets from the Sass documentation at http://sass-lang.com/ /* css stuff */ /* charset */ @charset "UTF-8"; /* nested rules */ #main { width: 97%; p, div { font-size: 2em; a { font-weight: bold; } } pre { font-size: 3em; } } /* parent selector (&) */ #main { color: black; a { font-weight: bold; &:hover { color: red; } } } /* nested properties */ .funky { font: 2px/3px { family: fantasy; size: 30em; weight: bold; } color: black; } /* nesting conflicts */ tr.default { foo: { // properties foo : 1; } foo: 1px; // rule foo.bar { // selector foo : 1; } foo:bar { // selector foo : 1; } foo: 1px; // rule } /* extended comment syntax */ /* This comment is * several lines long. * since it uses the CSS comment syntax, * it will appear in the CSS output. */ body { color: black; } // These comments are only one line long each. // They won't appear in the CSS output, // since they use the single-line comment syntax. a { color: green; } /* variables */ $width: 5em; $width: "Second width?" !default; #main { $localvar: 6em; width: $width; $font-size: 12px; $line-height: 30px; font: #{$font-size}/#{$line-height}; } $name: foo; $attr: border; p.#{$name} { #{$attr}-color: blue; } /* variable declaration with whitespaces */ // Set the color of your columns $grid-background-column-color : rgba(100, 100, 225, 0.25) !default; /* operations*/ p { width: (1em + 2em) * 3; color: #010203 + #040506; font-family: sans- + "serif"; margin: 3px + 4px auto; content: "I ate #{5 + 10} pies!"; color: hsl(0, 100%, 50%); color: hsl($hue: 0, $saturation: 100%, $lightness: 50%); } /* functions*/ $grid-width: 40px; $gutter-width: 10px; @function grid-width($n) { @return $n * $grid-width + ($n - 1) * $gutter-width; } #sidebar { width: grid-width(5); } /* @import */ @import "foo.scss"; $family: unquote("Droid+Sans"); @import "rounded-corners", url("http://fonts.googleapis.com/css?family=#{$family}"); #main { @import "example"; } /* @media */ .sidebar { width: 300px; @media screen and (orientation: landscape) { width: 500px; } } /* @extend */ .error { border: 1px #f00; background-color: #fdd; } .seriousError { @extend .error; border-width: 3px; } #context a%extreme { color: blue; font-weight: bold; font-size: 2em; } .notice { @extend %extreme !optional; } /* @debug and @warn */ @debug 10em + 12em; @mixin adjust-location($x, $y) { @if unitless($x) { @warn "Assuming #{$x} to be in pixels"; $x: 1px * $x; } @if unitless($y) { @warn "Assuming #{$y} to be in pixels"; $y: 1px * $y; } position: relative; left: $x; top: $y; } /* control directives */ /* if statement */ p { @if 1 + 1 == 2 { border: 1px solid; } @if 5 < 3 { border: 2px dotted; } @if null { border: 3px double; } } /* if else statement */ $type: monster; p { @if $type == ocean { color: blue; } @else { color: black; } } /* for statement */ @for $i from 1 through 3 { .item-#{$i} { width: 2em * $i; } } /* each statement */ @each $animal in puma, sea-slug, egret, salamander { .#{$animal}-icon { background-image: url('/images/#{$animal}.png'); } } /* while statement */ $i: 6; @while $i > 0 { .item-#{$i} { width: 2em * $i; } $i: $i - 2; } /* function with controlstatements */ @function foo($total, $a) { @for $i from 0 to $total { @if (unit($a) == "%") and ($i == ($total - 1)) { $z: 100%; @return '1'; } } @return $grid; } /* @mixin simple*/ @mixin large-text { font: { family: Arial; size: 20px; weight: bold; } color: #ff0000; } .page-title { @include large-text; padding: 4px; } /* mixin with parameters */ @mixin sexy-border($color, $width: 1in) { border: { color: $color; width: $width; style: dashed; } } p { @include sexy-border(blue); } /* mixin with varargs */ @mixin box-shadow($shadows...) { -moz-box-shadow: $shadows; -webkit-box-shadow: $shadows; box-shadow: $shadows; } .shadows { @include box-shadow(0px 4px 5px #666, 2px 6px 10px #999); } /* include with varargs */ @mixin colors($text, $background, $border) { color: $text; background-color: $background; border-color: $border; } $values: #ff0000, #00ff00, #0000ff; .primary { @include colors($values...); } /* include with body */ @mixin apply-to-ie6-only { * html { @content; } } @include apply-to-ie6-only { #logo { background-image: url(/logo.gif); } } @if $attr { @mixin apply-to-ie6-only { } } /* attributes */ [rel="external"]::after { content: 's'; } /*page */ @page :left { margin-left: 4cm; margin-right: 3cm; } /* missing semicolons */ tr.default { foo.bar { $foo: 1px } foo: { foo : white } foo.bar1 { @extend tr.default } foo.bar2 { @import "compass" } bar: black } /* rules without whitespace */ legend {foo{a:s}margin-top:0;margin-bottom:#123;margin-top:s(1)} /* extend with interpolation variable */ @mixin error($a: false) { @extend .#{$a}; @extend ##{$a}; } #bar {a: 1px;} .bar {b: 1px;} foo { @include error('bar'); } /* css3: @font face */ @font-face { font-family: Delicious; src: url('Delicious-Roman.otf'); } /* rule names with variables */ .orbit-#{$d}-prev { #{$d}-style: 0; foo-#{$d}: 1; #{$d}-bar-#{$d}: 2; foo-#{$d}-bar: 1; } /* keyframes */ @-webkit-keyframes NAME-YOUR-ANIMATION { 0% { opacity: 0; } 100% { opacity: 1; } } @-moz-keyframes NAME-YOUR-ANIMATION { 0% { opacity: 0; } 100% { opacity: 1; } } @-o-keyframes NAME-YOUR-ANIMATION { 0% { opacity: 0; } 100% { opacity: 1; } } @keyframes NAME-YOUR-ANIMATION { 0% { opacity: 0; } 100% { opacity: 1; } } /* string escaping */ [data-icon='test-1']:before { content:'\\'; } /* a comment */ $var1: '\''; $var2: "\""; /* another comment */
extensions/vscode-colorize-tests/test/colorize-fixtures/test.scss
0
https://github.com/microsoft/vscode/commit/fe5f564db16038785936282be7f6b871f34b8bd1
[ 0.0001801619364414364, 0.0001754123077262193, 0.00016059022163972259, 0.00017692858818918467, 0.000004265059942554217 ]
{ "id": 0, "code_window": [ " passportConf.isAuthenticated,\n", " contactController.postDoneWithFirst100Hours\n", ");\n", "app.get(\n", " '/nonprofit-project-instructions',\n", " passportConf.isAuthenticated,\n", " resourcesController.nonprofitProjectInstructions\n", ");\n", "app.post(\n", " '/update-progress',\n", " passportConf.isAuthenticated,\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "//app.get(\n", "// '/nonprofit-project-instructions',\n", "// passportConf.isAuthenticated,\n", "// resourcesController.nonprofitProjectInstructions\n", "//);\n" ], "file_path": "app.js", "type": "replace", "edit_start_line_idx": 372 }
if (process.env.NODE_ENV !== 'development') { require('newrelic'); } require('dotenv').load(); // handle uncaught exceptions. Forever will restart process on shutdown process.on('uncaughtException', function (err) { console.error( (new Date()).toUTCString() + ' uncaughtException:', err.message ); console.error(err.stack); /* eslint-disable no-process-exit */ process.exit(1); /* eslint-enable no-process-exit */ }); var express = require('express'), accepts = require('accepts'), cookieParser = require('cookie-parser'), compress = require('compression'), session = require('express-session'), logger = require('morgan'), errorHandler = require('errorhandler'), methodOverride = require('method-override'), bodyParser = require('body-parser'), helmet = require('helmet'), MongoStore = require('connect-mongo')(session), flash = require('express-flash'), path = require('path'), mongoose = require('mongoose'), passport = require('passport'), expressValidator = require('express-validator'), connectAssets = require('connect-assets'), request = require('request'), /** * Controllers (route handlers). */ homeController = require('./controllers/home'), resourcesController = require('./controllers/resources'), userController = require('./controllers/user'), contactController = require('./controllers/contact'), nonprofitController = require('./controllers/nonprofits'), bonfireController = require('./controllers/bonfire'), coursewareController = require('./controllers/courseware'), fieldGuideController = require('./controllers/fieldGuide'), challengeMapController = require('./controllers/challengeMap'), /** * Stories */ storyController = require('./controllers/story'); /** * API keys and Passport configuration. */ secrets = require('./config/secrets'), passportConf = require('./config/passport'); /** * Create Express server. */ var app = express(); /** * Connect to MongoDB. */ mongoose.connect(secrets.db); mongoose.connection.on('error', function () { console.error( 'MongoDB Connection Error. Please make sure that MongoDB is running.' ); }); /** * Express configuration. */ app.set('port', process.env.PORT || 3000); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); app.use(compress()); var oneYear = 31557600000; app.use(express.static(__dirname + '/public', {maxAge: oneYear})); app.use(connectAssets({ paths: [ path.join(__dirname, 'public/css'), path.join(__dirname, 'public/js') ], helperContext: app.locals })); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: true})); app.use(expressValidator({ customValidators: { matchRegex: function (param, regex) { return regex.test(param); } } })); app.use(methodOverride()); app.use(cookieParser()); app.use(session({ resave: true, saveUninitialized: true, secret: secrets.sessionSecret, store: new MongoStore({ url: secrets.db, 'auto_reconnect': true }) })); app.use(passport.initialize()); app.use(passport.session()); app.use(flash()); app.disable('x-powered-by'); app.use(helmet.xssFilter()); app.use(helmet.noSniff()); app.use(helmet.xframe()); app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }); var trusted = [ "'self'", '*.freecodecamp.com', '*.gstatic.com', '*.google-analytics.com', '*.googleapis.com', '*.google.com', '*.gstatic.com', '*.doubleclick.net', '*.twitter.com', '*.twitch.tv', '*.twimg.com', "'unsafe-eval'", "'unsafe-inline'", '*.rafflecopter.com', '*.bootstrapcdn.com', '*.cloudflare.com', 'https://*.cloudflare.com', 'localhost:3001', 'ws://localhost:3001/', 'http://localhost:3001', 'localhost:3000', 'ws://localhost:3000/', 'http://localhost:3000', '*.ionicframework.com', 'https://syndication.twitter.com', '*.youtube.com', '*.jsdelivr.net', 'https://*.jsdelivr.net', '*.togetherjs.com', 'https://*.togetherjs.com', 'wss://hub.togetherjs.com', '*.ytimg.com', 'wss://fcctogether.herokuapp.com', '*.bitly.com', 'http://cdn.inspectlet.com/', 'http://hn.inspectlet.com/' ]; app.use(helmet.contentSecurityPolicy({ defaultSrc: trusted, scriptSrc: [ '*.optimizely.com', '*.aspnetcdn.com', '*.d3js.org', ].concat(trusted), 'connect-src': [ 'ws://*.rafflecopter.com', 'wss://*.rafflecopter.com', 'https://*.rafflecopter.com', 'ws://www.freecodecamp.com', 'http://www.freecodecamp.com' ].concat(trusted), styleSrc: trusted, imgSrc: [ '*.evernote.com', '*.amazonaws.com', 'data:', '*.licdn.com', '*.gravatar.com', '*.akamaihd.net', 'graph.facebook.com', '*.githubusercontent.com', '*.googleusercontent.com', '*' /* allow all input since we have user submitted images for public profile*/ ].concat(trusted), fontSrc: ['*.googleapis.com'].concat(trusted), mediaSrc: [ '*.amazonaws.com', '*.twitter.com' ].concat(trusted), frameSrc: [ '*.gitter.im', '*.gitter.im https:', '*.vimeo.com', '*.twitter.com', '*.rafflecopter.com', '*.ghbtns.com' ].concat(trusted), reportOnly: false, // set to true if you only want to report errors setAllHeaders: false, // set to true if you want to set all headers safari5: false // set to true if you want to force buggy CSP in Safari 5 })); app.use(function (req, res, next) { // Make user object available in templates. res.locals.user = req.user; next(); }); app.use(function (req, res, next) { // Remember original destination before login. var path = req.path.split('/')[1]; if (/auth|login|logout|signin|signup|fonts|favicon/i.test(path)) { return next(); } else if (/\/stories\/comments\/\w+/i.test(req.path)) { return next(); } req.session.returnTo = req.path; next(); }); app.use( express.static(path.join(__dirname, 'public'), {maxAge: 31557600000}) ); app.use(express.static(__dirname + '/public', { maxAge: 86400000 })); /** * Main routes. */ app.get('/', homeController.index); app.get('/privacy', function(req, res) { res.redirect(301, "/field-guide/free-code-camp's-privacy-policy"); }); app.get('/nonprofit-project-instructions', function(req, res) { res.redirect(301, "/field-guide/free-code-camp's-privacy-policy"); }); app.get('/chat', resourcesController.chat); app.get('/twitch', resourcesController.twitch); app.get('/map', challengeMapController.challengeMap); app.get('/live-pair-programming', function(req, res) { res.redirect(301, '/field-guide/live-stream-pair-programming-on-twitch.tv'); }); app.get('/install-screenhero', function(req, res) { res.redirect(301, '/field-guide/install-screenhero'); }); app.get('/guide-to-our-nonprofit-projects', function(req, res) { res.redirect(301, '/field-guide/a-guide-to-our-nonprofit-projects'); }); app.get('/chromebook', function(req, res) { res.redirect(301, '/field-guide/chromebook'); }); app.get('/deploy-a-website', function(req, res) { res.redirect(301, '/field-guide/deploy-a-website'); }); app.get('/gmail-shortcuts', function(req, res) { res.redirect(301, '/field-guide/gmail-shortcuts'); }); app.get('/nodeschool-challenges', function(req, res) { res.redirect(301, '/field-guide/nodeschool-challenges'); }); app.get('/news', function(req, res) { res.redirect(301, '/stories/hot'); }); app.get('/learn-to-code', resourcesController.about); app.get('/about', function(req, res) { res.redirect(301, '/learn-to-code'); }); app.get('/signin', userController.getSignin); app.get('/login', function(req, res) { res.redirect(301, '/signin'); }); app.post('/signin', userController.postSignin); app.get('/signout', userController.signout); app.get('/logout', function(req, res) { res.redirect(301, '/signout'); }); app.get('/forgot', userController.getForgot); app.post('/forgot', userController.postForgot); app.get('/reset/:token', userController.getReset); app.post('/reset/:token', userController.postReset); app.get('/email-signup', userController.getEmailSignup); app.get('/email-signin', userController.getEmailSignin); app.post('/email-signup', userController.postEmailSignup); app.post('/email-signin', userController.postSignin); app.get('/nonprofits', contactController.getNonprofitsForm); app.post('/nonprofits', contactController.postNonprofitsForm); /** * Nonprofit Project routes. */ app.get('/nonprofits', nonprofitController.nonprofitsHome); app.get('/nonprofits/directory', nonprofitController.nonprofitsDirectory); app.get('/nonprofits/are-you-with-a-registered-nonprofit', nonprofitController.areYouWithARegisteredNonprofit); app.get('/nonprofits/are-there-people-that-are-already-benefiting-from-your-services', nonprofitController.areTherePeopleThatAreAlreadyBenefitingFromYourServices); app.get('/nonprofits/in-exchange-we-ask', nonprofitController.inExchangeWeAsk); app.get('/nonprofits/ok-with-javascript', nonprofitController.okWithJavaScript); app.get('/nonprofits/how-can-free-code-camp-help-you', nonprofitController.howCanFreeCodeCampHelpYou); app.get('/nonprofits/what-does-your-nonprofit-do', nonprofitController.whatDoesYourNonprofitDo); app.get('/nonprofits/link-us-to-your-website', nonprofitController.linkUsToYourWebsite); app.get('/nonprofits/tell-us-your-name', nonprofitController.tellUsYourName); app.get('/nonprofits/tell-us-your-email', nonprofitController.tellUsYourEmail); app.get('/nonprofits/your-nonprofit-project-application-has-been-submitted', nonprofitController.yourNonprofitProjectApplicationHasBeenSubmitted); app.get('/nonprofits/other-solutions', nonprofitController.otherSolutions); app.get('/nonprofits/getNonprofitList', nonprofitController.showAllNonprofits); app.get('/nonprofits/interested-in-nonprofit/:nonprofitName', nonprofitController.interestedInNonprofit); app.get( '/nonprofits/:nonprofitName', nonprofitController.returnIndividualNonprofit ); app.get( '/done-with-first-100-hours', passportConf.isAuthenticated, contactController.getDoneWithFirst100Hours ); app.post( '/done-with-first-100-hours', passportConf.isAuthenticated, contactController.postDoneWithFirst100Hours ); app.get( '/nonprofit-project-instructions', passportConf.isAuthenticated, resourcesController.nonprofitProjectInstructions ); app.post( '/update-progress', passportConf.isAuthenticated, userController.updateProgress ); app.get('/api/slack', function(req, res) { if (req.user) { if (req.user.email) { var invite = { 'email': req.user.email, 'token': process.env.SLACK_KEY, 'set_active': true }; var headers = { 'User-Agent': 'Node Browser/0.0.1', 'Content-Type': 'application/x-www-form-urlencoded' }; var options = { url: 'https://freecode.slack.com/api/users.admin.invite', method: 'POST', headers: headers, form: invite }; request(options, function (error, response, body) { if (!error && response.statusCode === 200) { req.flash('success', { msg: "We've successfully requested an invite for you. Please check your email and follow the instructions from Slack." }); req.user.sentSlackInvite = true; req.user.save(function(err, user) { if (err) { next(err); } return res.redirect('back'); }); } else { req.flash('errors', { msg: "The invitation email did not go through for some reason. Please try again or <a href='mailto:[email protected]?subject=slack%20invite%20failed%20to%20send>email us</a>." }); return res.redirect('back'); } }) } else { req.flash('notice', { msg: "Before we can send your Slack invite, we need your email address. Please update your profile information here." }); return res.redirect('/account'); } } else { req.flash('notice', { msg: "You need to sign in to Free Code Camp before we can send you a Slack invite." }); return res.redirect('/account'); } }); /** * Camper News routes. */ app.get( '/stories/hotStories', storyController.hotJSON ); app.get( '/stories/recentStories', storyController.recentJSON ); app.get( '/stories/', function(req, res) { res.redirect(302, '/stories/hot'); } ); app.get( '/stories/comments/:id', storyController.comments ); app.post( '/stories/comment/', storyController.commentSubmit ); app.post( '/stories/comment/:id/comment', storyController.commentOnCommentSubmit ); app.get( '/stories/submit', storyController.submitNew ); app.get( '/stories/submit/new-story', storyController.preSubmit ); app.post( '/stories/preliminary', storyController.newStory ); app.post( '/stories/', storyController.storySubmission ); app.get( '/stories/hot', storyController.hot ); app.get( '/stories/recent', storyController.recent ); app.get( '/stories/search', storyController.search ); app.post( '/stories/search', storyController.getStories ); app.get( '/stories/:storyName', storyController.returnIndividualStory ); app.post( '/stories/upvote/', storyController.upvote ); /** * Challenge related routes */ app.get( '/challenges/', challengesController.returnNextChallenge ); app.get( '/challenges/:challengeNumber', challengesController.returnChallenge ); app.all('/account', passportConf.isAuthenticated); app.get('/account/api', userController.getAccountAngular); /** * API routes */ app.get('/api/github', resourcesController.githubCalls); app.get('/api/blogger', resourcesController.bloggerCalls); app.get('/api/trello', resourcesController.trelloCalls); /** * Bonfire related routes */ app.get('/field-guide/getFieldGuideList', fieldGuideController.showAllFieldGuides); app.get('/playground', bonfireController.index); app.get('/bonfires', bonfireController.returnNextBonfire); app.get('/bonfire-json-generator', bonfireController.returnGenerator); app.post('/bonfire-json-generator', bonfireController.generateChallenge); app.get('/bonfire-challenge-generator', bonfireController.publicGenerator); app.post('/bonfire-challenge-generator', bonfireController.testBonfire); app.get( '/bonfires/:bonfireName', bonfireController.returnIndividualBonfire ); app.get('/bonfire', function(req, res) { res.redirect(301, '/playground'); }); app.post('/completed-bonfire/', bonfireController.completedBonfire); /** * Field Guide related routes */ app.get('/field-guide/:fieldGuideName', fieldGuideController.returnIndividualFieldGuide); app.get('/field-guide', fieldGuideController.returnNextFieldGuide); app.post('/completed-field-guide/', fieldGuideController.completedFieldGuide); /** * Courseware related routes */ app.get('/challenges/', coursewareController.returnNextCourseware); app.get( '/challenges/:coursewareName', coursewareController.returnIndividualCourseware ); app.post('/completed-courseware/', coursewareController.completedCourseware); app.post('/completed-zipline-or-basejump', coursewareController.completedZiplineOrBasejump); // Unique Check API route app.get('/api/checkUniqueUsername/:username', userController.checkUniqueUsername); app.get('/api/checkExistingUsername/:username', userController.checkExistingUsername); app.get('/api/checkUniqueEmail/:email', userController.checkUniqueEmail); app.get('/account', userController.getAccount); app.post('/account/profile', userController.postUpdateProfile); app.post('/account/password', userController.postUpdatePassword); app.post('/account/delete', userController.postDeleteAccount); app.get('/account/unlink/:provider', userController.getOauthUnlink); app.get('/sitemap.xml', resourcesController.sitemap); /** * OAuth sign-in routes. */ var passportOptions = { successRedirect: '/', failureRedirect: '/login' }; app.get('/auth/twitter', passport.authenticate('twitter')); app.get( '/auth/twitter/callback', passport.authenticate('twitter', { successRedirect: '/', failureRedirect: '/login' }) ); app.get( '/auth/linkedin', passport.authenticate('linkedin', { state: 'SOME STATE' }) ); app.get( '/auth/linkedin/callback', passport.authenticate('linkedin', passportOptions) ); app.get( '/auth/facebook', passport.authenticate('facebook', {scope: ['email', 'user_location']}) ); app.get( '/auth/facebook/callback', passport.authenticate('facebook', passportOptions), function (req, res) { res.redirect(req.session.returnTo || '/'); } ); app.get('/auth/github', passport.authenticate('github')); app.get( '/auth/github/callback', passport.authenticate('github', passportOptions), function (req, res) { res.redirect(req.session.returnTo || '/'); } ); app.get( '/auth/google', passport.authenticate('google', {scope: 'profile email'}) ); app.get( '/auth/google/callback', passport.authenticate('google', passportOptions), function (req, res) { res.redirect(req.session.returnTo || '/'); } ); app.get('/induce-vomiting', function(req, res, next) { next(new Error('vomiting induced')); }); // put this route last app.get( '/:username', userController.returnUser ); /** * 500 Error Handler. */ if (process.env.NODE_ENV === 'development') { app.use(errorHandler({ log: true })); } else { // error handling in production app.use(function(err, req, res, next) { // respect err.status if (err.status) { res.statusCode = err.status; } // default status code to 500 if (res.statusCode < 400) { res.statusCode = 500; } // parse res type var accept = accepts(req); var type = accept.type('html', 'json', 'text'); var message = 'opps! Something went wrong. Please try again later'; if (type === 'html') { req.flash('errors', { msg: message }); return res.redirect('/'); // json } else if (type === 'json') { res.setHeader('Content-Type', 'application/json'); return res.send({ message: message }); // plain text } else { res.setHeader('Content-Type', 'text/plain'); return res.send(message); } }); } /** * Start Express server. */ app.listen(app.get('port'), function () { console.log( 'FreeCodeCamp server listening on port %d in %s mode', app.get('port'), app.get('env') ); }); module.exports = app;
app.js
1
https://github.com/freeCodeCamp/freeCodeCamp/commit/b9372b9af6809b7cdd3bd118d0d0be9eebab231a
[ 0.9967650175094604, 0.01888090744614601, 0.0001648193137953058, 0.00017345718515571207, 0.1211768314242363 ]
{ "id": 0, "code_window": [ " passportConf.isAuthenticated,\n", " contactController.postDoneWithFirst100Hours\n", ");\n", "app.get(\n", " '/nonprofit-project-instructions',\n", " passportConf.isAuthenticated,\n", " resourcesController.nonprofitProjectInstructions\n", ");\n", "app.post(\n", " '/update-progress',\n", " passportConf.isAuthenticated,\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "//app.get(\n", "// '/nonprofit-project-instructions',\n", "// passportConf.isAuthenticated,\n", "// resourcesController.nonprofitProjectInstructions\n", "//);\n" ], "file_path": "app.js", "type": "replace", "edit_start_line_idx": 372 }
<!-- Extensible HTML version 1.0 Frameset DTD This is the same as HTML 4 Frameset except for changes due to the differences between XML and SGML. Namespace = http://www.w3.org/1999/xhtml For further information, see: http://www.w3.org/TR/xhtml1 Copyright (c) 1998-2002 W3C (MIT, INRIA, Keio), All Rights Reserved. This DTD module is identified by the PUBLIC and SYSTEM identifiers: PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" SYSTEM "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd" $Revision: 1.2 $ $Date: 2004/04/07 18:09:50 $ --> <!--================ Character mnemonic entities =========================--> <!ENTITY % HTMLlat1 PUBLIC "-//W3C//ENTITIES Latin 1 for XHTML//EN" "xhtml-lat1.ent"> %HTMLlat1; <!ENTITY % HTMLsymbol PUBLIC "-//W3C//ENTITIES Symbols for XHTML//EN" "xhtml-symbol.ent"> %HTMLsymbol; <!ENTITY % HTMLspecial PUBLIC "-//W3C//ENTITIES Special for XHTML//EN" "xhtml-special.ent"> %HTMLspecial; <!--================== Imported Names ====================================--> <!ENTITY % ContentType "CDATA"> <!-- media type, as per [RFC2045] --> <!ENTITY % ContentTypes "CDATA"> <!-- comma-separated list of media types, as per [RFC2045] --> <!ENTITY % Charset "CDATA"> <!-- a character encoding, as per [RFC2045] --> <!ENTITY % Charsets "CDATA"> <!-- a space separated list of character encodings, as per [RFC2045] --> <!ENTITY % LanguageCode "NMTOKEN"> <!-- a language code, as per [RFC3066] --> <!ENTITY % Character "CDATA"> <!-- a single character, as per section 2.2 of [XML] --> <!ENTITY % Number "CDATA"> <!-- one or more digits --> <!ENTITY % LinkTypes "CDATA"> <!-- space-separated list of link types --> <!ENTITY % MediaDesc "CDATA"> <!-- single or comma-separated list of media descriptors --> <!ENTITY % URI "CDATA"> <!-- a Uniform Resource Identifier, see [RFC2396] --> <!ENTITY % UriList "CDATA"> <!-- a space separated list of Uniform Resource Identifiers --> <!ENTITY % Datetime "CDATA"> <!-- date and time information. ISO date format --> <!ENTITY % Script "CDATA"> <!-- script expression --> <!ENTITY % StyleSheet "CDATA"> <!-- style sheet data --> <!ENTITY % Text "CDATA"> <!-- used for titles etc. --> <!ENTITY % FrameTarget "NMTOKEN"> <!-- render in this frame --> <!ENTITY % Length "CDATA"> <!-- nn for pixels or nn% for percentage length --> <!ENTITY % MultiLength "CDATA"> <!-- pixel, percentage, or relative --> <!ENTITY % MultiLengths "CDATA"> <!-- comma-separated list of MultiLength --> <!ENTITY % Pixels "CDATA"> <!-- integer representing length in pixels --> <!-- these are used for image maps --> <!ENTITY % Shape "(rect|circle|poly|default)"> <!ENTITY % Coords "CDATA"> <!-- comma separated list of lengths --> <!-- used for object, applet, img, input and iframe --> <!ENTITY % ImgAlign "(top|middle|bottom|left|right)"> <!-- a color using sRGB: #RRGGBB as Hex values --> <!ENTITY % Color "CDATA"> <!-- There are also 16 widely known color names with their sRGB values: Black = #000000 Green = #008000 Silver = #C0C0C0 Lime = #00FF00 Gray = #808080 Olive = #808000 White = #FFFFFF Yellow = #FFFF00 Maroon = #800000 Navy = #000080 Red = #FF0000 Blue = #0000FF Purple = #800080 Teal = #008080 Fuchsia= #FF00FF Aqua = #00FFFF --> <!--=================== Generic Attributes ===============================--> <!-- core attributes common to most elements id document-wide unique id class space separated list of classes style associated style info title advisory title/amplification --> <!ENTITY % coreattrs "id ID #IMPLIED class CDATA #IMPLIED style %StyleSheet; #IMPLIED title %Text; #IMPLIED" > <!-- internationalization attributes lang language code (backwards compatible) xml:lang language code (as per XML 1.0 spec) dir direction for weak/neutral text --> <!ENTITY % i18n "lang %LanguageCode; #IMPLIED xml:lang %LanguageCode; #IMPLIED dir (ltr|rtl) #IMPLIED" > <!-- attributes for common UI events onclick a pointer button was clicked ondblclick a pointer button was double clicked onmousedown a pointer button was pressed down onmouseup a pointer button was released onmousemove a pointer was moved onto the element onmouseout a pointer was moved away from the element onkeypress a key was pressed and released onkeydown a key was pressed down onkeyup a key was released --> <!ENTITY % events "onclick %Script; #IMPLIED ondblclick %Script; #IMPLIED onmousedown %Script; #IMPLIED onmouseup %Script; #IMPLIED onmouseover %Script; #IMPLIED onmousemove %Script; #IMPLIED onmouseout %Script; #IMPLIED onkeypress %Script; #IMPLIED onkeydown %Script; #IMPLIED onkeyup %Script; #IMPLIED" > <!-- attributes for elements that can get the focus accesskey accessibility key character tabindex position in tabbing order onfocus the element got the focus onblur the element lost the focus --> <!ENTITY % focus "accesskey %Character; #IMPLIED tabindex %Number; #IMPLIED onfocus %Script; #IMPLIED onblur %Script; #IMPLIED" > <!ENTITY % attrs "%coreattrs; %i18n; %events;"> <!-- text alignment for p, div, h1-h6. The default is align="left" for ltr headings, "right" for rtl --> <!ENTITY % TextAlign "align (left|center|right|justify) #IMPLIED"> <!--=================== Text Elements ====================================--> <!ENTITY % special.extra "object | applet | img | map | iframe"> <!ENTITY % special.basic "br | span | bdo"> <!ENTITY % special "%special.basic; | %special.extra;"> <!ENTITY % fontstyle.extra "big | small | font | basefont"> <!ENTITY % fontstyle.basic "tt | i | b | u | s | strike "> <!ENTITY % fontstyle "%fontstyle.basic; | %fontstyle.extra;"> <!ENTITY % phrase.extra "sub | sup"> <!ENTITY % phrase.basic "em | strong | dfn | code | q | samp | kbd | var | cite | abbr | acronym"> <!ENTITY % phrase "%phrase.basic; | %phrase.extra;"> <!ENTITY % inline.forms "input | select | textarea | label | button"> <!-- these can occur at block or inline level --> <!ENTITY % misc.inline "ins | del | script"> <!-- these can only occur at block level --> <!ENTITY % misc "noscript | %misc.inline;"> <!ENTITY % inline "a | %special; | %fontstyle; | %phrase; | %inline.forms;"> <!-- %Inline; covers inline or "text-level" elements --> <!ENTITY % Inline "(#PCDATA | %inline; | %misc.inline;)*"> <!--================== Block level elements ==============================--> <!ENTITY % heading "h1|h2|h3|h4|h5|h6"> <!ENTITY % lists "ul | ol | dl | menu | dir"> <!ENTITY % blocktext "pre | hr | blockquote | address | center"> <!ENTITY % block "p | %heading; | div | %lists; | %blocktext; | isindex | fieldset | table"> <!-- %Flow; mixes block and inline and is used for list items etc. --> <!ENTITY % Flow "(#PCDATA | %block; | form | %inline; | %misc;)*"> <!--================== Content models for exclusions =====================--> <!-- a elements use %Inline; excluding a --> <!ENTITY % a.content "(#PCDATA | %special; | %fontstyle; | %phrase; | %inline.forms; | %misc.inline;)*"> <!-- pre uses %Inline excluding img, object, applet, big, small, sub, sup, font, or basefont --> <!ENTITY % pre.content "(#PCDATA | a | %special.basic; | %fontstyle.basic; | %phrase.basic; | %inline.forms; | %misc.inline;)*"> <!-- form uses %Flow; excluding form --> <!ENTITY % form.content "(#PCDATA | %block; | %inline; | %misc;)*"> <!-- button uses %Flow; but excludes a, form, form controls, iframe --> <!ENTITY % button.content "(#PCDATA | p | %heading; | div | %lists; | %blocktext; | table | br | span | bdo | object | applet | img | map | %fontstyle; | %phrase; | %misc;)*"> <!--================ Document Structure ==================================--> <!-- the namespace URI designates the document profile --> <!ELEMENT html (head, frameset)> <!ATTLIST html %i18n; id ID #IMPLIED xmlns %URI; #FIXED 'http://www.w3.org/1999/xhtml' > <!--================ Document Head =======================================--> <!ENTITY % head.misc "(script|style|meta|link|object|isindex)*"> <!-- content model is %head.misc; combined with a single title and an optional base element in any order --> <!ELEMENT head (%head.misc;, ((title, %head.misc;, (base, %head.misc;)?) | (base, %head.misc;, (title, %head.misc;))))> <!ATTLIST head %i18n; id ID #IMPLIED profile %URI; #IMPLIED > <!-- The title element is not considered part of the flow of text. It should be displayed, for example as the page header or window title. Exactly one title is required per document. --> <!ELEMENT title (#PCDATA)> <!ATTLIST title %i18n; id ID #IMPLIED > <!-- document base URI --> <!ELEMENT base EMPTY> <!ATTLIST base id ID #IMPLIED href %URI; #IMPLIED target %FrameTarget; #IMPLIED > <!-- generic metainformation --> <!ELEMENT meta EMPTY> <!ATTLIST meta %i18n; id ID #IMPLIED http-equiv CDATA #IMPLIED name CDATA #IMPLIED content CDATA #REQUIRED scheme CDATA #IMPLIED > <!-- Relationship values can be used in principle: a) for document specific toolbars/menus when used with the link element in document head e.g. start, contents, previous, next, index, end, help b) to link to a separate style sheet (rel="stylesheet") c) to make a link to a script (rel="script") d) by stylesheets to control how collections of html nodes are rendered into printed documents e) to make a link to a printable version of this document e.g. a PostScript or PDF version (rel="alternate" media="print") --> <!ELEMENT link EMPTY> <!ATTLIST link %attrs; charset %Charset; #IMPLIED href %URI; #IMPLIED hreflang %LanguageCode; #IMPLIED type %ContentType; #IMPLIED rel %LinkTypes; #IMPLIED rev %LinkTypes; #IMPLIED media %MediaDesc; #IMPLIED target %FrameTarget; #IMPLIED > <!-- style info, which may include CDATA sections --> <!ELEMENT style (#PCDATA)> <!ATTLIST style %i18n; id ID #IMPLIED type %ContentType; #REQUIRED media %MediaDesc; #IMPLIED title %Text; #IMPLIED xml:space (preserve) #FIXED 'preserve' > <!-- script statements, which may include CDATA sections --> <!ELEMENT script (#PCDATA)> <!ATTLIST script id ID #IMPLIED charset %Charset; #IMPLIED type %ContentType; #REQUIRED language CDATA #IMPLIED src %URI; #IMPLIED defer (defer) #IMPLIED xml:space (preserve) #FIXED 'preserve' > <!-- alternate content container for non script-based rendering --> <!ELEMENT noscript %Flow;> <!ATTLIST noscript %attrs; > <!--======================= Frames =======================================--> <!-- only one noframes element permitted per document --> <!ELEMENT frameset (frameset|frame|noframes)*> <!ATTLIST frameset %coreattrs; rows %MultiLengths; #IMPLIED cols %MultiLengths; #IMPLIED onload %Script; #IMPLIED onunload %Script; #IMPLIED > <!-- reserved frame names start with "_" otherwise starts with letter --> <!-- tiled window within frameset --> <!ELEMENT frame EMPTY> <!ATTLIST frame %coreattrs; longdesc %URI; #IMPLIED name NMTOKEN #IMPLIED src %URI; #IMPLIED frameborder (1|0) "1" marginwidth %Pixels; #IMPLIED marginheight %Pixels; #IMPLIED noresize (noresize) #IMPLIED scrolling (yes|no|auto) "auto" > <!-- inline subwindow --> <!ELEMENT iframe %Flow;> <!ATTLIST iframe %coreattrs; longdesc %URI; #IMPLIED name NMTOKEN #IMPLIED src %URI; #IMPLIED frameborder (1|0) "1" marginwidth %Pixels; #IMPLIED marginheight %Pixels; #IMPLIED scrolling (yes|no|auto) "auto" align %ImgAlign; #IMPLIED height %Length; #IMPLIED width %Length; #IMPLIED > <!-- alternate content container for non frame-based rendering --> <!ELEMENT noframes (body)> <!ATTLIST noframes %attrs; > <!--=================== Document Body ====================================--> <!ELEMENT body %Flow;> <!ATTLIST body %attrs; onload %Script; #IMPLIED onunload %Script; #IMPLIED background %URI; #IMPLIED bgcolor %Color; #IMPLIED text %Color; #IMPLIED link %Color; #IMPLIED vlink %Color; #IMPLIED alink %Color; #IMPLIED > <!ELEMENT div %Flow;> <!-- generic language/style container --> <!ATTLIST div %attrs; %TextAlign; > <!--=================== Paragraphs =======================================--> <!ELEMENT p %Inline;> <!ATTLIST p %attrs; %TextAlign; > <!--=================== Headings =========================================--> <!-- There are six levels of headings from h1 (the most important) to h6 (the least important). --> <!ELEMENT h1 %Inline;> <!ATTLIST h1 %attrs; %TextAlign; > <!ELEMENT h2 %Inline;> <!ATTLIST h2 %attrs; %TextAlign; > <!ELEMENT h3 %Inline;> <!ATTLIST h3 %attrs; %TextAlign; > <!ELEMENT h4 %Inline;> <!ATTLIST h4 %attrs; %TextAlign; > <!ELEMENT h5 %Inline;> <!ATTLIST h5 %attrs; %TextAlign; > <!ELEMENT h6 %Inline;> <!ATTLIST h6 %attrs; %TextAlign; > <!--=================== Lists ============================================--> <!-- Unordered list bullet styles --> <!ENTITY % ULStyle "(disc|square|circle)"> <!-- Unordered list --> <!ELEMENT ul (li)+> <!ATTLIST ul %attrs; type %ULStyle; #IMPLIED compact (compact) #IMPLIED > <!-- Ordered list numbering style 1 arabic numbers 1, 2, 3, ... a lower alpha a, b, c, ... A upper alpha A, B, C, ... i lower roman i, ii, iii, ... I upper roman I, II, III, ... The style is applied to the sequence number which by default is reset to 1 for the first list item in an ordered list. --> <!ENTITY % OLStyle "CDATA"> <!-- Ordered (numbered) list --> <!ELEMENT ol (li)+> <!ATTLIST ol %attrs; type %OLStyle; #IMPLIED compact (compact) #IMPLIED start %Number; #IMPLIED > <!-- single column list (DEPRECATED) --> <!ELEMENT menu (li)+> <!ATTLIST menu %attrs; compact (compact) #IMPLIED > <!-- multiple column list (DEPRECATED) --> <!ELEMENT dir (li)+> <!ATTLIST dir %attrs; compact (compact) #IMPLIED > <!-- LIStyle is constrained to: "(%ULStyle;|%OLStyle;)" --> <!ENTITY % LIStyle "CDATA"> <!-- list item --> <!ELEMENT li %Flow;> <!ATTLIST li %attrs; type %LIStyle; #IMPLIED value %Number; #IMPLIED > <!-- definition lists - dt for term, dd for its definition --> <!ELEMENT dl (dt|dd)+> <!ATTLIST dl %attrs; compact (compact) #IMPLIED > <!ELEMENT dt %Inline;> <!ATTLIST dt %attrs; > <!ELEMENT dd %Flow;> <!ATTLIST dd %attrs; > <!--=================== Address ==========================================--> <!-- information on author --> <!ELEMENT address (#PCDATA | %inline; | %misc.inline; | p)*> <!ATTLIST address %attrs; > <!--=================== Horizontal Rule ==================================--> <!ELEMENT hr EMPTY> <!ATTLIST hr %attrs; align (left|center|right) #IMPLIED noshade (noshade) #IMPLIED size %Pixels; #IMPLIED width %Length; #IMPLIED > <!--=================== Preformatted Text ================================--> <!-- content is %Inline; excluding "img|object|applet|big|small|sub|sup|font|basefont" --> <!ELEMENT pre %pre.content;> <!ATTLIST pre %attrs; width %Number; #IMPLIED xml:space (preserve) #FIXED 'preserve' > <!--=================== Block-like Quotes ================================--> <!ELEMENT blockquote %Flow;> <!ATTLIST blockquote %attrs; cite %URI; #IMPLIED > <!--=================== Text alignment ===================================--> <!-- center content --> <!ELEMENT center %Flow;> <!ATTLIST center %attrs; > <!--=================== Inserted/Deleted Text ============================--> <!-- ins/del are allowed in block and inline content, but its inappropriate to include block content within an ins element occurring in inline content. --> <!ELEMENT ins %Flow;> <!ATTLIST ins %attrs; cite %URI; #IMPLIED datetime %Datetime; #IMPLIED > <!ELEMENT del %Flow;> <!ATTLIST del %attrs; cite %URI; #IMPLIED datetime %Datetime; #IMPLIED > <!--================== The Anchor Element ================================--> <!-- content is %Inline; except that anchors shouldn't be nested --> <!ELEMENT a %a.content;> <!ATTLIST a %attrs; %focus; charset %Charset; #IMPLIED type %ContentType; #IMPLIED name NMTOKEN #IMPLIED href %URI; #IMPLIED hreflang %LanguageCode; #IMPLIED rel %LinkTypes; #IMPLIED rev %LinkTypes; #IMPLIED shape %Shape; "rect" coords %Coords; #IMPLIED target %FrameTarget; #IMPLIED > <!--===================== Inline Elements ================================--> <!ELEMENT span %Inline;> <!-- generic language/style container --> <!ATTLIST span %attrs; > <!ELEMENT bdo %Inline;> <!-- I18N BiDi over-ride --> <!ATTLIST bdo %coreattrs; %events; lang %LanguageCode; #IMPLIED xml:lang %LanguageCode; #IMPLIED dir (ltr|rtl) #REQUIRED > <!ELEMENT br EMPTY> <!-- forced line break --> <!ATTLIST br %coreattrs; clear (left|all|right|none) "none" > <!ELEMENT em %Inline;> <!-- emphasis --> <!ATTLIST em %attrs;> <!ELEMENT strong %Inline;> <!-- strong emphasis --> <!ATTLIST strong %attrs;> <!ELEMENT dfn %Inline;> <!-- definitional --> <!ATTLIST dfn %attrs;> <!ELEMENT code %Inline;> <!-- program code --> <!ATTLIST code %attrs;> <!ELEMENT samp %Inline;> <!-- sample --> <!ATTLIST samp %attrs;> <!ELEMENT kbd %Inline;> <!-- something user would type --> <!ATTLIST kbd %attrs;> <!ELEMENT var %Inline;> <!-- variable --> <!ATTLIST var %attrs;> <!ELEMENT cite %Inline;> <!-- citation --> <!ATTLIST cite %attrs;> <!ELEMENT abbr %Inline;> <!-- abbreviation --> <!ATTLIST abbr %attrs;> <!ELEMENT acronym %Inline;> <!-- acronym --> <!ATTLIST acronym %attrs;> <!ELEMENT q %Inline;> <!-- inlined quote --> <!ATTLIST q %attrs; cite %URI; #IMPLIED > <!ELEMENT sub %Inline;> <!-- subscript --> <!ATTLIST sub %attrs;> <!ELEMENT sup %Inline;> <!-- superscript --> <!ATTLIST sup %attrs;> <!ELEMENT tt %Inline;> <!-- fixed pitch font --> <!ATTLIST tt %attrs;> <!ELEMENT i %Inline;> <!-- italic font --> <!ATTLIST i %attrs;> <!ELEMENT b %Inline;> <!-- bold font --> <!ATTLIST b %attrs;> <!ELEMENT big %Inline;> <!-- bigger font --> <!ATTLIST big %attrs;> <!ELEMENT small %Inline;> <!-- smaller font --> <!ATTLIST small %attrs;> <!ELEMENT u %Inline;> <!-- underline --> <!ATTLIST u %attrs;> <!ELEMENT s %Inline;> <!-- strike-through --> <!ATTLIST s %attrs;> <!ELEMENT strike %Inline;> <!-- strike-through --> <!ATTLIST strike %attrs;> <!ELEMENT basefont EMPTY> <!-- base font size --> <!ATTLIST basefont id ID #IMPLIED size CDATA #REQUIRED color %Color; #IMPLIED face CDATA #IMPLIED > <!ELEMENT font %Inline;> <!-- local change to font --> <!ATTLIST font %coreattrs; %i18n; size CDATA #IMPLIED color %Color; #IMPLIED face CDATA #IMPLIED > <!--==================== Object ======================================--> <!-- object is used to embed objects as part of HTML pages. param elements should precede other content. Parameters can also be expressed as attribute/value pairs on the object element itself when brevity is desired. --> <!ELEMENT object (#PCDATA | param | %block; | form |%inline; | %misc;)*> <!ATTLIST object %attrs; declare (declare) #IMPLIED classid %URI; #IMPLIED codebase %URI; #IMPLIED data %URI; #IMPLIED type %ContentType; #IMPLIED codetype %ContentType; #IMPLIED archive %UriList; #IMPLIED standby %Text; #IMPLIED height %Length; #IMPLIED width %Length; #IMPLIED usemap %URI; #IMPLIED name NMTOKEN #IMPLIED tabindex %Number; #IMPLIED align %ImgAlign; #IMPLIED border %Pixels; #IMPLIED hspace %Pixels; #IMPLIED vspace %Pixels; #IMPLIED > <!-- param is used to supply a named property value. In XML it would seem natural to follow RDF and support an abbreviated syntax where the param elements are replaced by attribute value pairs on the object start tag. --> <!ELEMENT param EMPTY> <!ATTLIST param id ID #IMPLIED name CDATA #REQUIRED value CDATA #IMPLIED valuetype (data|ref|object) "data" type %ContentType; #IMPLIED > <!--=================== Java applet ==================================--> <!-- One of code or object attributes must be present. Place param elements before other content. --> <!ELEMENT applet (#PCDATA | param | %block; | form | %inline; | %misc;)*> <!ATTLIST applet %coreattrs; codebase %URI; #IMPLIED archive CDATA #IMPLIED code CDATA #IMPLIED object CDATA #IMPLIED alt %Text; #IMPLIED name NMTOKEN #IMPLIED width %Length; #REQUIRED height %Length; #REQUIRED align %ImgAlign; #IMPLIED hspace %Pixels; #IMPLIED vspace %Pixels; #IMPLIED > <!--=================== Images ===========================================--> <!-- To avoid accessibility problems for people who aren't able to see the image, you should provide a text description using the alt and longdesc attributes. In addition, avoid the use of server-side image maps. --> <!ELEMENT img EMPTY> <!ATTLIST img %attrs; src %URI; #REQUIRED alt %Text; #REQUIRED name NMTOKEN #IMPLIED longdesc %URI; #IMPLIED height %Length; #IMPLIED width %Length; #IMPLIED usemap %URI; #IMPLIED ismap (ismap) #IMPLIED align %ImgAlign; #IMPLIED border %Pixels; #IMPLIED hspace %Pixels; #IMPLIED vspace %Pixels; #IMPLIED > <!-- usemap points to a map element which may be in this document or an external document, although the latter is not widely supported --> <!--================== Client-side image maps ============================--> <!-- These can be placed in the same document or grouped in a separate document although this isn't yet widely supported --> <!ELEMENT map ((%block; | form | %misc;)+ | area+)> <!ATTLIST map %i18n; %events; id ID #REQUIRED class CDATA #IMPLIED style %StyleSheet; #IMPLIED title %Text; #IMPLIED name NMTOKEN #IMPLIED > <!ELEMENT area EMPTY> <!ATTLIST area %attrs; %focus; shape %Shape; "rect" coords %Coords; #IMPLIED href %URI; #IMPLIED nohref (nohref) #IMPLIED alt %Text; #REQUIRED target %FrameTarget; #IMPLIED > <!--================ Forms ===============================================--> <!ELEMENT form %form.content;> <!-- forms shouldn't be nested --> <!ATTLIST form %attrs; action %URI; #REQUIRED method (get|post) "get" name NMTOKEN #IMPLIED enctype %ContentType; "application/x-www-form-urlencoded" onsubmit %Script; #IMPLIED onreset %Script; #IMPLIED accept %ContentTypes; #IMPLIED accept-charset %Charsets; #IMPLIED target %FrameTarget; #IMPLIED > <!-- Each label must not contain more than ONE field Label elements shouldn't be nested. --> <!ELEMENT label %Inline;> <!ATTLIST label %attrs; for IDREF #IMPLIED accesskey %Character; #IMPLIED onfocus %Script; #IMPLIED onblur %Script; #IMPLIED > <!ENTITY % InputType "(text | password | checkbox | radio | submit | reset | file | hidden | image | button)" > <!-- the name attribute is required for all but submit & reset --> <!ELEMENT input EMPTY> <!-- form control --> <!ATTLIST input %attrs; %focus; type %InputType; "text" name CDATA #IMPLIED value CDATA #IMPLIED checked (checked) #IMPLIED disabled (disabled) #IMPLIED readonly (readonly) #IMPLIED size CDATA #IMPLIED maxlength %Number; #IMPLIED src %URI; #IMPLIED alt CDATA #IMPLIED usemap %URI; #IMPLIED onselect %Script; #IMPLIED onchange %Script; #IMPLIED accept %ContentTypes; #IMPLIED align %ImgAlign; #IMPLIED > <!ELEMENT select (optgroup|option)+> <!-- option selector --> <!ATTLIST select %attrs; name CDATA #IMPLIED size %Number; #IMPLIED multiple (multiple) #IMPLIED disabled (disabled) #IMPLIED tabindex %Number; #IMPLIED onfocus %Script; #IMPLIED onblur %Script; #IMPLIED onchange %Script; #IMPLIED > <!ELEMENT optgroup (option)+> <!-- option group --> <!ATTLIST optgroup %attrs; disabled (disabled) #IMPLIED label %Text; #REQUIRED > <!ELEMENT option (#PCDATA)> <!-- selectable choice --> <!ATTLIST option %attrs; selected (selected) #IMPLIED disabled (disabled) #IMPLIED label %Text; #IMPLIED value CDATA #IMPLIED > <!ELEMENT textarea (#PCDATA)> <!-- multi-line text field --> <!ATTLIST textarea %attrs; %focus; name CDATA #IMPLIED rows %Number; #REQUIRED cols %Number; #REQUIRED disabled (disabled) #IMPLIED readonly (readonly) #IMPLIED onselect %Script; #IMPLIED onchange %Script; #IMPLIED > <!-- The fieldset element is used to group form fields. Only one legend element should occur in the content and if present should only be preceded by whitespace. --> <!ELEMENT fieldset (#PCDATA | legend | %block; | form | %inline; | %misc;)*> <!ATTLIST fieldset %attrs; > <!ENTITY % LAlign "(top|bottom|left|right)"> <!ELEMENT legend %Inline;> <!-- fieldset label --> <!ATTLIST legend %attrs; accesskey %Character; #IMPLIED align %LAlign; #IMPLIED > <!-- Content is %Flow; excluding a, form, form controls, iframe --> <!ELEMENT button %button.content;> <!-- push button --> <!ATTLIST button %attrs; %focus; name CDATA #IMPLIED value CDATA #IMPLIED type (button|submit|reset) "submit" disabled (disabled) #IMPLIED > <!-- single-line text input control (DEPRECATED) --> <!ELEMENT isindex EMPTY> <!ATTLIST isindex %coreattrs; %i18n; prompt %Text; #IMPLIED > <!--======================= Tables =======================================--> <!-- Derived from IETF HTML table standard, see [RFC1942] --> <!-- The border attribute sets the thickness of the frame around the table. The default units are screen pixels. The frame attribute specifies which parts of the frame around the table should be rendered. The values are not the same as CALS to avoid a name clash with the valign attribute. --> <!ENTITY % TFrame "(void|above|below|hsides|lhs|rhs|vsides|box|border)"> <!-- The rules attribute defines which rules to draw between cells: If rules is absent then assume: "none" if border is absent or border="0" otherwise "all" --> <!ENTITY % TRules "(none | groups | rows | cols | all)"> <!-- horizontal placement of table relative to document --> <!ENTITY % TAlign "(left|center|right)"> <!-- horizontal alignment attributes for cell contents char alignment char, e.g. char=":" charoff offset for alignment char --> <!ENTITY % cellhalign "align (left|center|right|justify|char) #IMPLIED char %Character; #IMPLIED charoff %Length; #IMPLIED" > <!-- vertical alignment attributes for cell contents --> <!ENTITY % cellvalign "valign (top|middle|bottom|baseline) #IMPLIED" > <!ELEMENT table (caption?, (col*|colgroup*), thead?, tfoot?, (tbody+|tr+))> <!ELEMENT caption %Inline;> <!ELEMENT thead (tr)+> <!ELEMENT tfoot (tr)+> <!ELEMENT tbody (tr)+> <!ELEMENT colgroup (col)*> <!ELEMENT col EMPTY> <!ELEMENT tr (th|td)+> <!ELEMENT th %Flow;> <!ELEMENT td %Flow;> <!ATTLIST table %attrs; summary %Text; #IMPLIED width %Length; #IMPLIED border %Pixels; #IMPLIED frame %TFrame; #IMPLIED rules %TRules; #IMPLIED cellspacing %Length; #IMPLIED cellpadding %Length; #IMPLIED align %TAlign; #IMPLIED bgcolor %Color; #IMPLIED > <!ENTITY % CAlign "(top|bottom|left|right)"> <!ATTLIST caption %attrs; align %CAlign; #IMPLIED > <!-- colgroup groups a set of col elements. It allows you to group several semantically related columns together. --> <!ATTLIST colgroup %attrs; span %Number; "1" width %MultiLength; #IMPLIED %cellhalign; %cellvalign; > <!-- col elements define the alignment properties for cells in one or more columns. The width attribute specifies the width of the columns, e.g. width=64 width in screen pixels width=0.5* relative width of 0.5 The span attribute causes the attributes of one col element to apply to more than one column. --> <!ATTLIST col %attrs; span %Number; "1" width %MultiLength; #IMPLIED %cellhalign; %cellvalign; > <!-- Use thead to duplicate headers when breaking table across page boundaries, or for static headers when tbody sections are rendered in scrolling panel. Use tfoot to duplicate footers when breaking table across page boundaries, or for static footers when tbody sections are rendered in scrolling panel. Use multiple tbody sections when rules are needed between groups of table rows. --> <!ATTLIST thead %attrs; %cellhalign; %cellvalign; > <!ATTLIST tfoot %attrs; %cellhalign; %cellvalign; > <!ATTLIST tbody %attrs; %cellhalign; %cellvalign; > <!ATTLIST tr %attrs; %cellhalign; %cellvalign; bgcolor %Color; #IMPLIED > <!-- Scope is simpler than headers attribute for common tables --> <!ENTITY % Scope "(row|col|rowgroup|colgroup)"> <!-- th is for headers, td for data and for cells acting as both --> <!ATTLIST th %attrs; abbr %Text; #IMPLIED axis CDATA #IMPLIED headers IDREFS #IMPLIED scope %Scope; #IMPLIED rowspan %Number; "1" colspan %Number; "1" %cellhalign; %cellvalign; nowrap (nowrap) #IMPLIED bgcolor %Color; #IMPLIED width %Pixels; #IMPLIED height %Pixels; #IMPLIED > <!ATTLIST td %attrs; abbr %Text; #IMPLIED axis CDATA #IMPLIED headers IDREFS #IMPLIED scope %Scope; #IMPLIED rowspan %Number; "1" colspan %Number; "1" %cellhalign; %cellvalign; nowrap (nowrap) #IMPLIED bgcolor %Color; #IMPLIED width %Pixels; #IMPLIED height %Pixels; #IMPLIED >
bower_components/jsdom/test/level3/core/files/orig/xhtml1-frameset.dtd
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/b9372b9af6809b7cdd3bd118d0d0be9eebab231a
[ 0.00018090815865434706, 0.00017645303159952164, 0.00016450953262392431, 0.00017721611948218197, 0.0000029585842185042566 ]
{ "id": 0, "code_window": [ " passportConf.isAuthenticated,\n", " contactController.postDoneWithFirst100Hours\n", ");\n", "app.get(\n", " '/nonprofit-project-instructions',\n", " passportConf.isAuthenticated,\n", " resourcesController.nonprofitProjectInstructions\n", ");\n", "app.post(\n", " '/update-progress',\n", " passportConf.isAuthenticated,\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "//app.get(\n", "// '/nonprofit-project-instructions',\n", "// passportConf.isAuthenticated,\n", "// resourcesController.nonprofitProjectInstructions\n", "//);\n" ], "file_path": "app.js", "type": "replace", "edit_start_line_idx": 372 }
var mongoose = require('mongoose'); var secrets = require('../config/secrets'); /** * * @type {exports.Schema} */ var Long = mongoose.Types.Long; var nonprofitSchema = new mongoose.Schema({ name: String, requestedDeliverables: Array, whatDoesNonprofitDo: String, websiteLink: String, stakeholderName: String, stakeholderEmail: String, endUser: String, approvedDeliverables: Array, projectDescription: String, logoUrl: String, imageUrl: String, estimatedHours: 0, interestedCampers: [], confirmedCampers: [], currentStatus: String // "confirmed", "started", "completed", "aborted" }); module.exports = mongoose.model('Nonprofit', nonprofitSchema);
models/Nonprofit.js
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/b9372b9af6809b7cdd3bd118d0d0be9eebab231a
[ 0.00017420033691450953, 0.00017283030319958925, 0.00017110200133174658, 0.00017318857135251164, 0.0000012900097772217123 ]
{ "id": 0, "code_window": [ " passportConf.isAuthenticated,\n", " contactController.postDoneWithFirst100Hours\n", ");\n", "app.get(\n", " '/nonprofit-project-instructions',\n", " passportConf.isAuthenticated,\n", " resourcesController.nonprofitProjectInstructions\n", ");\n", "app.post(\n", " '/update-progress',\n", " passportConf.isAuthenticated,\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "//app.get(\n", "// '/nonprofit-project-instructions',\n", "// passportConf.isAuthenticated,\n", "// resourcesController.nonprofitProjectInstructions\n", "//);\n" ], "file_path": "app.js", "type": "replace", "edit_start_line_idx": 372 }
var dom = require("../../../../lib/jsdom/level3/core").dom.level3.core; exports.hc_staff = function() { var doc = new dom.Document("html"); var implementation = new dom.DOMImplementation(doc, { "XML" : ["1.0", "2.0"], "core": ["1.0", "2.0", "3.0"] }); var notations = new dom.NotationNodeMap( doc, doc.createNotationNode("notation1","notation1File", null), doc.createNotationNode("notation2",null, "notation2File") ); // TODO: consider importing the master list of entities // http://www.w3schools.com/tags/ref_symbols.asp var entities = new dom.EntityNodeMap( doc, doc.createEntityNode("alpha", doc.createTextNode("α")), doc.createEntityNode("beta", doc.createTextNode("&#946;")), doc.createEntityNode("gamma", doc.createTextNode("&#947;")), doc.createEntityNode("delta", doc.createTextNode("&#948;")), doc.createEntityNode("epsilon", doc.createTextNode("&#949;")) ); // <!ATTLIST acronym dir CDATA "ltr"> var defaultAttributes = new dom.NamedNodeMap(doc); var acronym = doc.createElementNS("http://www.w3.org/2000/xmlns/","acronym"); acronym.setAttribute("dir", "ltr"); defaultAttributes.setNamedItem(acronym); var doctype = new dom.DocumentType(doc, "xml", entities, notations, defaultAttributes); doc.doctype = doctype; doc.implementation = implementation; doc.appendChild(doc.createComment(" This is comment number 1.")); var html = doc.createElementNS("http://www.w3.org/2000/xmlns/","html"); var html = doc.appendChild(html); var head = doc.createElementNS("http://www.w3.org/2000/xmlns/","head"); var head = html.appendChild(head); var meta = doc.createElementNS("http://www.w3.org/2000/xmlns/","meta"); meta.setAttribute("http-equiv", "Content-Type"); meta.setAttribute("content", "text/html; charset=UTF-8"); head.appendChild(meta); var title = doc.createElementNS("http://www.w3.org/2000/xmlns/","title") title.appendChild(doc.createTextNode("hc_staff")); var title = head.appendChild(title); // make the tests work.... head.appendChild(doc.createElementNS("http://www.w3.org/2000/xmlns/","script")); head.appendChild(doc.createElementNS("http://www.w3.org/2000/xmlns/","script")); head.appendChild(doc.createElementNS("http://www.w3.org/2000/xmlns/","script")); var body = doc.createElementNS("http://www.w3.org/2000/xmlns/","body"); var staff = html.appendChild(body); var employees = []; var addresses = []; var names = []; var positions = []; var genders = []; var ids = []; var salaries = []; // create 5 employees for (var i=0; i<5; i++) { var employee = doc.createElementNS("http://www.w3.org/2000/xmlns/","p"); var address = doc.createElementNS("http://www.w3.org/2000/xmlns/","acronym"); var name = doc.createElementNS("http://www.w3.org/2000/xmlns/","strong"); var position = doc.createElementNS("http://www.w3.org/2000/xmlns/","code"); var gender = doc.createElementNS("http://www.w3.org/2000/xmlns/","var"); var id = doc.createElementNS("http://www.w3.org/2000/xmlns/","em"); var salary = doc.createElementNS("http://www.w3.org/2000/xmlns/","sup"); employee.appendChild(doc.createTextNode("\n")); employee.appendChild(id); employee.appendChild(doc.createTextNode("\n")); employee.appendChild(name); employee.appendChild(doc.createTextNode("\n")); employee.appendChild(position); employee.appendChild(doc.createTextNode("\n")); employee.appendChild(salary); employee.appendChild(doc.createTextNode("\n")); employee.appendChild(gender); employee.appendChild(doc.createTextNode("\n")); employee.appendChild(address); employee.appendChild(doc.createTextNode("\n")); staff.appendChild(employee); names.push(name); employees.push(employee); addresses.push(address); genders.push(gender); positions.push(position); ids.push(id); salaries.push(salary); } ids[0].appendChild(doc.createTextNode("EMP0001")); salaries[0].appendChild(doc.createTextNode("56,000")); addresses[0].setAttribute("title", "Yes"); addresses[0].appendChild(doc.createTextNode('1230 North Ave. Dallas, Texas 98551')); names[0].appendChild(doc.createTextNode("Margaret Martin")); genders[0].appendChild(doc.createTextNode("Female")); positions[0].appendChild(doc.createTextNode("Accountant")); ids[1].appendChild(doc.createTextNode("EMP0002")); salaries[1].appendChild(doc.createTextNode("35,000")); addresses[1].setAttribute("title", "Yes"); addresses[1].setAttribute("class", "Yes"); addresses[1].appendChild(doc.createTextNode("β Dallas, γ\n 98554")); names[1].appendChild(doc.createTextNode("Martha Raynolds")); names[1].appendChild(doc.createCDATASection("This is a CDATASection with EntityReference number 2 &amp;ent2;")); names[1].appendChild(doc.createCDATASection("This is an adjacent CDATASection with a reference to a tab &amp;tab;")); genders[1].appendChild(doc.createTextNode("Female")); positions[1].appendChild(doc.createTextNode("Secretary")); ids[2].appendChild(doc.createTextNode("EMP0003")); salaries[2].appendChild(doc.createTextNode("100,000")); addresses[2].setAttribute("title", "Yes"); addresses[2].setAttribute("class", "No"); addresses[2].appendChild(doc.createTextNode("PO Box 27 Irving, texas 98553")); names[2].appendChild(doc.createTextNode("Roger\n Jones")) ; genders[2].appendChild(doc.createEntityReference("&delta;"));//Text("&delta;")); positions[2].appendChild(doc.createTextNode("Department Manager")); ids[3].appendChild(doc.createTextNode("EMP0004")); salaries[3].appendChild(doc.createTextNode("95,000")); addresses[3].setAttribute("title", "Yes"); addresses[3].setAttribute("class", "Yα"); addresses[3].setAttribute("id", "emp4_addr"); addresses[3].appendChild(doc.createTextNode("27 South Road. Dallas, Texas 98556")); names[3].appendChild(doc.createTextNode("Jeny Oconnor")); genders[3].appendChild(doc.createTextNode("Female")); positions[3].appendChild(doc.createTextNode("Personal Director")); ids[4].appendChild(doc.createTextNode("EMP0005")); salaries[4].appendChild(doc.createTextNode("90,000")); addresses[4].setAttribute("title", "Yes"); addresses[4].appendChild(doc.createTextNode("1821 Nordic. Road, Irving Texas 98558")); names[4].appendChild(doc.createTextNode("Robert Myers")); genders[4].appendChild(doc.createTextNode("male")); positions[4].appendChild(doc.createTextNode("Computer Specialist")); doc.appendChild(doc.createProcessingInstruction("TEST-STYLE", "PIDATA")); doc.normalize(); return doc; };
bower_components/jsdom/test/level3/core/files/hc_staff.xml.js
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/b9372b9af6809b7cdd3bd118d0d0be9eebab231a
[ 0.00018156881560571492, 0.00017871716408990324, 0.00017326090892311186, 0.0001794526178855449, 0.000002049146360150189 ]
{ "id": 1, "code_window": [ " '/stories/upvote/',\n", " storyController.upvote\n", ");\n", "\n", "/**\n", " * Challenge related routes\n", " */\n", "app.get(\n", " '/challenges/',\n", " challengesController.returnNextChallenge\n", ");\n", "app.get(\n", " '/challenges/:challengeNumber',\n", " challengesController.returnChallenge\n", ");\n", "\n", "app.all('/account', passportConf.isAuthenticated);\n", "\n", "app.get('/account/api', userController.getAccountAngular);\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "app.js", "type": "replace", "edit_start_line_idx": 523 }
if (process.env.NODE_ENV !== 'development') { require('newrelic'); } require('dotenv').load(); // handle uncaught exceptions. Forever will restart process on shutdown process.on('uncaughtException', function (err) { console.error( (new Date()).toUTCString() + ' uncaughtException:', err.message ); console.error(err.stack); /* eslint-disable no-process-exit */ process.exit(1); /* eslint-enable no-process-exit */ }); var express = require('express'), accepts = require('accepts'), cookieParser = require('cookie-parser'), compress = require('compression'), session = require('express-session'), logger = require('morgan'), errorHandler = require('errorhandler'), methodOverride = require('method-override'), bodyParser = require('body-parser'), helmet = require('helmet'), MongoStore = require('connect-mongo')(session), flash = require('express-flash'), path = require('path'), mongoose = require('mongoose'), passport = require('passport'), expressValidator = require('express-validator'), connectAssets = require('connect-assets'), request = require('request'), /** * Controllers (route handlers). */ homeController = require('./controllers/home'), resourcesController = require('./controllers/resources'), userController = require('./controllers/user'), contactController = require('./controllers/contact'), nonprofitController = require('./controllers/nonprofits'), bonfireController = require('./controllers/bonfire'), coursewareController = require('./controllers/courseware'), fieldGuideController = require('./controllers/fieldGuide'), challengeMapController = require('./controllers/challengeMap'), /** * Stories */ storyController = require('./controllers/story'); /** * API keys and Passport configuration. */ secrets = require('./config/secrets'), passportConf = require('./config/passport'); /** * Create Express server. */ var app = express(); /** * Connect to MongoDB. */ mongoose.connect(secrets.db); mongoose.connection.on('error', function () { console.error( 'MongoDB Connection Error. Please make sure that MongoDB is running.' ); }); /** * Express configuration. */ app.set('port', process.env.PORT || 3000); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); app.use(compress()); var oneYear = 31557600000; app.use(express.static(__dirname + '/public', {maxAge: oneYear})); app.use(connectAssets({ paths: [ path.join(__dirname, 'public/css'), path.join(__dirname, 'public/js') ], helperContext: app.locals })); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: true})); app.use(expressValidator({ customValidators: { matchRegex: function (param, regex) { return regex.test(param); } } })); app.use(methodOverride()); app.use(cookieParser()); app.use(session({ resave: true, saveUninitialized: true, secret: secrets.sessionSecret, store: new MongoStore({ url: secrets.db, 'auto_reconnect': true }) })); app.use(passport.initialize()); app.use(passport.session()); app.use(flash()); app.disable('x-powered-by'); app.use(helmet.xssFilter()); app.use(helmet.noSniff()); app.use(helmet.xframe()); app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }); var trusted = [ "'self'", '*.freecodecamp.com', '*.gstatic.com', '*.google-analytics.com', '*.googleapis.com', '*.google.com', '*.gstatic.com', '*.doubleclick.net', '*.twitter.com', '*.twitch.tv', '*.twimg.com', "'unsafe-eval'", "'unsafe-inline'", '*.rafflecopter.com', '*.bootstrapcdn.com', '*.cloudflare.com', 'https://*.cloudflare.com', 'localhost:3001', 'ws://localhost:3001/', 'http://localhost:3001', 'localhost:3000', 'ws://localhost:3000/', 'http://localhost:3000', '*.ionicframework.com', 'https://syndication.twitter.com', '*.youtube.com', '*.jsdelivr.net', 'https://*.jsdelivr.net', '*.togetherjs.com', 'https://*.togetherjs.com', 'wss://hub.togetherjs.com', '*.ytimg.com', 'wss://fcctogether.herokuapp.com', '*.bitly.com', 'http://cdn.inspectlet.com/', 'http://hn.inspectlet.com/' ]; app.use(helmet.contentSecurityPolicy({ defaultSrc: trusted, scriptSrc: [ '*.optimizely.com', '*.aspnetcdn.com', '*.d3js.org', ].concat(trusted), 'connect-src': [ 'ws://*.rafflecopter.com', 'wss://*.rafflecopter.com', 'https://*.rafflecopter.com', 'ws://www.freecodecamp.com', 'http://www.freecodecamp.com' ].concat(trusted), styleSrc: trusted, imgSrc: [ '*.evernote.com', '*.amazonaws.com', 'data:', '*.licdn.com', '*.gravatar.com', '*.akamaihd.net', 'graph.facebook.com', '*.githubusercontent.com', '*.googleusercontent.com', '*' /* allow all input since we have user submitted images for public profile*/ ].concat(trusted), fontSrc: ['*.googleapis.com'].concat(trusted), mediaSrc: [ '*.amazonaws.com', '*.twitter.com' ].concat(trusted), frameSrc: [ '*.gitter.im', '*.gitter.im https:', '*.vimeo.com', '*.twitter.com', '*.rafflecopter.com', '*.ghbtns.com' ].concat(trusted), reportOnly: false, // set to true if you only want to report errors setAllHeaders: false, // set to true if you want to set all headers safari5: false // set to true if you want to force buggy CSP in Safari 5 })); app.use(function (req, res, next) { // Make user object available in templates. res.locals.user = req.user; next(); }); app.use(function (req, res, next) { // Remember original destination before login. var path = req.path.split('/')[1]; if (/auth|login|logout|signin|signup|fonts|favicon/i.test(path)) { return next(); } else if (/\/stories\/comments\/\w+/i.test(req.path)) { return next(); } req.session.returnTo = req.path; next(); }); app.use( express.static(path.join(__dirname, 'public'), {maxAge: 31557600000}) ); app.use(express.static(__dirname + '/public', { maxAge: 86400000 })); /** * Main routes. */ app.get('/', homeController.index); app.get('/privacy', function(req, res) { res.redirect(301, "/field-guide/free-code-camp's-privacy-policy"); }); app.get('/nonprofit-project-instructions', function(req, res) { res.redirect(301, "/field-guide/free-code-camp's-privacy-policy"); }); app.get('/chat', resourcesController.chat); app.get('/twitch', resourcesController.twitch); app.get('/map', challengeMapController.challengeMap); app.get('/live-pair-programming', function(req, res) { res.redirect(301, '/field-guide/live-stream-pair-programming-on-twitch.tv'); }); app.get('/install-screenhero', function(req, res) { res.redirect(301, '/field-guide/install-screenhero'); }); app.get('/guide-to-our-nonprofit-projects', function(req, res) { res.redirect(301, '/field-guide/a-guide-to-our-nonprofit-projects'); }); app.get('/chromebook', function(req, res) { res.redirect(301, '/field-guide/chromebook'); }); app.get('/deploy-a-website', function(req, res) { res.redirect(301, '/field-guide/deploy-a-website'); }); app.get('/gmail-shortcuts', function(req, res) { res.redirect(301, '/field-guide/gmail-shortcuts'); }); app.get('/nodeschool-challenges', function(req, res) { res.redirect(301, '/field-guide/nodeschool-challenges'); }); app.get('/news', function(req, res) { res.redirect(301, '/stories/hot'); }); app.get('/learn-to-code', resourcesController.about); app.get('/about', function(req, res) { res.redirect(301, '/learn-to-code'); }); app.get('/signin', userController.getSignin); app.get('/login', function(req, res) { res.redirect(301, '/signin'); }); app.post('/signin', userController.postSignin); app.get('/signout', userController.signout); app.get('/logout', function(req, res) { res.redirect(301, '/signout'); }); app.get('/forgot', userController.getForgot); app.post('/forgot', userController.postForgot); app.get('/reset/:token', userController.getReset); app.post('/reset/:token', userController.postReset); app.get('/email-signup', userController.getEmailSignup); app.get('/email-signin', userController.getEmailSignin); app.post('/email-signup', userController.postEmailSignup); app.post('/email-signin', userController.postSignin); app.get('/nonprofits', contactController.getNonprofitsForm); app.post('/nonprofits', contactController.postNonprofitsForm); /** * Nonprofit Project routes. */ app.get('/nonprofits', nonprofitController.nonprofitsHome); app.get('/nonprofits/directory', nonprofitController.nonprofitsDirectory); app.get('/nonprofits/are-you-with-a-registered-nonprofit', nonprofitController.areYouWithARegisteredNonprofit); app.get('/nonprofits/are-there-people-that-are-already-benefiting-from-your-services', nonprofitController.areTherePeopleThatAreAlreadyBenefitingFromYourServices); app.get('/nonprofits/in-exchange-we-ask', nonprofitController.inExchangeWeAsk); app.get('/nonprofits/ok-with-javascript', nonprofitController.okWithJavaScript); app.get('/nonprofits/how-can-free-code-camp-help-you', nonprofitController.howCanFreeCodeCampHelpYou); app.get('/nonprofits/what-does-your-nonprofit-do', nonprofitController.whatDoesYourNonprofitDo); app.get('/nonprofits/link-us-to-your-website', nonprofitController.linkUsToYourWebsite); app.get('/nonprofits/tell-us-your-name', nonprofitController.tellUsYourName); app.get('/nonprofits/tell-us-your-email', nonprofitController.tellUsYourEmail); app.get('/nonprofits/your-nonprofit-project-application-has-been-submitted', nonprofitController.yourNonprofitProjectApplicationHasBeenSubmitted); app.get('/nonprofits/other-solutions', nonprofitController.otherSolutions); app.get('/nonprofits/getNonprofitList', nonprofitController.showAllNonprofits); app.get('/nonprofits/interested-in-nonprofit/:nonprofitName', nonprofitController.interestedInNonprofit); app.get( '/nonprofits/:nonprofitName', nonprofitController.returnIndividualNonprofit ); app.get( '/done-with-first-100-hours', passportConf.isAuthenticated, contactController.getDoneWithFirst100Hours ); app.post( '/done-with-first-100-hours', passportConf.isAuthenticated, contactController.postDoneWithFirst100Hours ); app.get( '/nonprofit-project-instructions', passportConf.isAuthenticated, resourcesController.nonprofitProjectInstructions ); app.post( '/update-progress', passportConf.isAuthenticated, userController.updateProgress ); app.get('/api/slack', function(req, res) { if (req.user) { if (req.user.email) { var invite = { 'email': req.user.email, 'token': process.env.SLACK_KEY, 'set_active': true }; var headers = { 'User-Agent': 'Node Browser/0.0.1', 'Content-Type': 'application/x-www-form-urlencoded' }; var options = { url: 'https://freecode.slack.com/api/users.admin.invite', method: 'POST', headers: headers, form: invite }; request(options, function (error, response, body) { if (!error && response.statusCode === 200) { req.flash('success', { msg: "We've successfully requested an invite for you. Please check your email and follow the instructions from Slack." }); req.user.sentSlackInvite = true; req.user.save(function(err, user) { if (err) { next(err); } return res.redirect('back'); }); } else { req.flash('errors', { msg: "The invitation email did not go through for some reason. Please try again or <a href='mailto:[email protected]?subject=slack%20invite%20failed%20to%20send>email us</a>." }); return res.redirect('back'); } }) } else { req.flash('notice', { msg: "Before we can send your Slack invite, we need your email address. Please update your profile information here." }); return res.redirect('/account'); } } else { req.flash('notice', { msg: "You need to sign in to Free Code Camp before we can send you a Slack invite." }); return res.redirect('/account'); } }); /** * Camper News routes. */ app.get( '/stories/hotStories', storyController.hotJSON ); app.get( '/stories/recentStories', storyController.recentJSON ); app.get( '/stories/', function(req, res) { res.redirect(302, '/stories/hot'); } ); app.get( '/stories/comments/:id', storyController.comments ); app.post( '/stories/comment/', storyController.commentSubmit ); app.post( '/stories/comment/:id/comment', storyController.commentOnCommentSubmit ); app.get( '/stories/submit', storyController.submitNew ); app.get( '/stories/submit/new-story', storyController.preSubmit ); app.post( '/stories/preliminary', storyController.newStory ); app.post( '/stories/', storyController.storySubmission ); app.get( '/stories/hot', storyController.hot ); app.get( '/stories/recent', storyController.recent ); app.get( '/stories/search', storyController.search ); app.post( '/stories/search', storyController.getStories ); app.get( '/stories/:storyName', storyController.returnIndividualStory ); app.post( '/stories/upvote/', storyController.upvote ); /** * Challenge related routes */ app.get( '/challenges/', challengesController.returnNextChallenge ); app.get( '/challenges/:challengeNumber', challengesController.returnChallenge ); app.all('/account', passportConf.isAuthenticated); app.get('/account/api', userController.getAccountAngular); /** * API routes */ app.get('/api/github', resourcesController.githubCalls); app.get('/api/blogger', resourcesController.bloggerCalls); app.get('/api/trello', resourcesController.trelloCalls); /** * Bonfire related routes */ app.get('/field-guide/getFieldGuideList', fieldGuideController.showAllFieldGuides); app.get('/playground', bonfireController.index); app.get('/bonfires', bonfireController.returnNextBonfire); app.get('/bonfire-json-generator', bonfireController.returnGenerator); app.post('/bonfire-json-generator', bonfireController.generateChallenge); app.get('/bonfire-challenge-generator', bonfireController.publicGenerator); app.post('/bonfire-challenge-generator', bonfireController.testBonfire); app.get( '/bonfires/:bonfireName', bonfireController.returnIndividualBonfire ); app.get('/bonfire', function(req, res) { res.redirect(301, '/playground'); }); app.post('/completed-bonfire/', bonfireController.completedBonfire); /** * Field Guide related routes */ app.get('/field-guide/:fieldGuideName', fieldGuideController.returnIndividualFieldGuide); app.get('/field-guide', fieldGuideController.returnNextFieldGuide); app.post('/completed-field-guide/', fieldGuideController.completedFieldGuide); /** * Courseware related routes */ app.get('/challenges/', coursewareController.returnNextCourseware); app.get( '/challenges/:coursewareName', coursewareController.returnIndividualCourseware ); app.post('/completed-courseware/', coursewareController.completedCourseware); app.post('/completed-zipline-or-basejump', coursewareController.completedZiplineOrBasejump); // Unique Check API route app.get('/api/checkUniqueUsername/:username', userController.checkUniqueUsername); app.get('/api/checkExistingUsername/:username', userController.checkExistingUsername); app.get('/api/checkUniqueEmail/:email', userController.checkUniqueEmail); app.get('/account', userController.getAccount); app.post('/account/profile', userController.postUpdateProfile); app.post('/account/password', userController.postUpdatePassword); app.post('/account/delete', userController.postDeleteAccount); app.get('/account/unlink/:provider', userController.getOauthUnlink); app.get('/sitemap.xml', resourcesController.sitemap); /** * OAuth sign-in routes. */ var passportOptions = { successRedirect: '/', failureRedirect: '/login' }; app.get('/auth/twitter', passport.authenticate('twitter')); app.get( '/auth/twitter/callback', passport.authenticate('twitter', { successRedirect: '/', failureRedirect: '/login' }) ); app.get( '/auth/linkedin', passport.authenticate('linkedin', { state: 'SOME STATE' }) ); app.get( '/auth/linkedin/callback', passport.authenticate('linkedin', passportOptions) ); app.get( '/auth/facebook', passport.authenticate('facebook', {scope: ['email', 'user_location']}) ); app.get( '/auth/facebook/callback', passport.authenticate('facebook', passportOptions), function (req, res) { res.redirect(req.session.returnTo || '/'); } ); app.get('/auth/github', passport.authenticate('github')); app.get( '/auth/github/callback', passport.authenticate('github', passportOptions), function (req, res) { res.redirect(req.session.returnTo || '/'); } ); app.get( '/auth/google', passport.authenticate('google', {scope: 'profile email'}) ); app.get( '/auth/google/callback', passport.authenticate('google', passportOptions), function (req, res) { res.redirect(req.session.returnTo || '/'); } ); app.get('/induce-vomiting', function(req, res, next) { next(new Error('vomiting induced')); }); // put this route last app.get( '/:username', userController.returnUser ); /** * 500 Error Handler. */ if (process.env.NODE_ENV === 'development') { app.use(errorHandler({ log: true })); } else { // error handling in production app.use(function(err, req, res, next) { // respect err.status if (err.status) { res.statusCode = err.status; } // default status code to 500 if (res.statusCode < 400) { res.statusCode = 500; } // parse res type var accept = accepts(req); var type = accept.type('html', 'json', 'text'); var message = 'opps! Something went wrong. Please try again later'; if (type === 'html') { req.flash('errors', { msg: message }); return res.redirect('/'); // json } else if (type === 'json') { res.setHeader('Content-Type', 'application/json'); return res.send({ message: message }); // plain text } else { res.setHeader('Content-Type', 'text/plain'); return res.send(message); } }); } /** * Start Express server. */ app.listen(app.get('port'), function () { console.log( 'FreeCodeCamp server listening on port %d in %s mode', app.get('port'), app.get('env') ); }); module.exports = app;
app.js
1
https://github.com/freeCodeCamp/freeCodeCamp/commit/b9372b9af6809b7cdd3bd118d0d0be9eebab231a
[ 0.9675195217132568, 0.02095375396311283, 0.0001621272531338036, 0.0001736892736516893, 0.12714418768882751 ]
{ "id": 1, "code_window": [ " '/stories/upvote/',\n", " storyController.upvote\n", ");\n", "\n", "/**\n", " * Challenge related routes\n", " */\n", "app.get(\n", " '/challenges/',\n", " challengesController.returnNextChallenge\n", ");\n", "app.get(\n", " '/challenges/:challengeNumber',\n", " challengesController.returnChallenge\n", ");\n", "\n", "app.all('/account', passportConf.isAuthenticated);\n", "\n", "app.get('/account/api', userController.getAccountAngular);\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "app.js", "type": "replace", "edit_start_line_idx": 523 }
var path = require('path'); var jsdom = require('../lib/jsdom'); var fs = require('fs'); function toPathname(dirname, relativePath) { var pathname = path.resolve(dirname, relativePath).replace(/\\/g, '/'); if (pathname[0] !== '/') { pathname = '/' + pathname; } return pathname; } function toFileUrl(dirname, relativePath) { return 'file://' + toPathname(dirname, relativePath); } exports.toFileUrl = function (dirname) { return function (relativePath) { return toFileUrl(dirname, relativePath); }; }; exports.toPathname = function (dirname) { return function (relativePath) { return toPathname(dirname, relativePath); }; }; exports.load = function (dirname) { var fileCache = Object.create(null); return function (name, options) { options = options || {}; var file = path.resolve(dirname, 'files/' + name + '.html'); if (!options.url) { options.url = toFileUrl(dirname, file); } var contents = fileCache[file] || fs.readFileSync(file, 'utf8'); var doc = jsdom.jsdom(null, null, options); var window = doc.createWindow(); doc.parent = window; window.loadComplete = function () {}; doc.innerHTML = contents; fileCache[file] = contents; return doc; }; };
bower_components/jsdom/test/util.js
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/b9372b9af6809b7cdd3bd118d0d0be9eebab231a
[ 0.00017600147111807019, 0.00017175282118842006, 0.00016649204189889133, 0.0001722517772577703, 0.0000028868794288428035 ]
{ "id": 1, "code_window": [ " '/stories/upvote/',\n", " storyController.upvote\n", ");\n", "\n", "/**\n", " * Challenge related routes\n", " */\n", "app.get(\n", " '/challenges/',\n", " challengesController.returnNextChallenge\n", ");\n", "app.get(\n", " '/challenges/:challengeNumber',\n", " challengesController.returnChallenge\n", ");\n", "\n", "app.all('/account', passportConf.isAuthenticated);\n", "\n", "app.get('/account/api', userController.getAccountAngular);\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "app.js", "type": "replace", "edit_start_line_idx": 523 }
<!doctype html> <title>CodeMirror: Common Lisp mode</title> <meta charset="utf-8"/> <link rel=stylesheet href="../../doc/docs.css"> <link rel="stylesheet" href="../../lib/codemirror.css"> <script src="../../lib/codemirror.js"></script> <script src="commonlisp.js"></script> <style>.CodeMirror {background: #f8f8f8;}</style> <div id=nav> <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a> <ul> <li><a href="../../index.html">Home</a> <li><a href="../../doc/manual.html">Manual</a> <li><a href="https://github.com/codemirror/codemirror">Code</a> </ul> <ul> <li><a href="../index.html">Language modes</a> <li><a class=active href="#">Common Lisp</a> </ul> </div> <article> <h2>Common Lisp mode</h2> <form><textarea id="code" name="code">(in-package :cl-postgres) ;; These are used to synthesize reader and writer names for integer ;; reading/writing functions when the amount of bytes and the ;; signedness is known. Both the macro that creates the functions and ;; some macros that use them create names this way. (eval-when (:compile-toplevel :load-toplevel :execute) (defun integer-reader-name (bytes signed) (intern (with-standard-io-syntax (format nil "~a~a~a~a" '#:read- (if signed "" '#:u) '#:int bytes)))) (defun integer-writer-name (bytes signed) (intern (with-standard-io-syntax (format nil "~a~a~a~a" '#:write- (if signed "" '#:u) '#:int bytes))))) (defmacro integer-reader (bytes) "Create a function to read integers from a binary stream." (let ((bits (* bytes 8))) (labels ((return-form (signed) (if signed `(if (logbitp ,(1- bits) result) (dpb result (byte ,(1- bits) 0) -1) result) `result)) (generate-reader (signed) `(defun ,(integer-reader-name bytes signed) (socket) (declare (type stream socket) #.*optimize*) ,(if (= bytes 1) `(let ((result (the (unsigned-byte 8) (read-byte socket)))) (declare (type (unsigned-byte 8) result)) ,(return-form signed)) `(let ((result 0)) (declare (type (unsigned-byte ,bits) result)) ,@(loop :for byte :from (1- bytes) :downto 0 :collect `(setf (ldb (byte 8 ,(* 8 byte)) result) (the (unsigned-byte 8) (read-byte socket)))) ,(return-form signed)))))) `(progn ;; This causes weird errors on SBCL in some circumstances. Disabled for now. ;; (declaim (inline ,(integer-reader-name bytes t) ;; ,(integer-reader-name bytes nil))) (declaim (ftype (function (t) (signed-byte ,bits)) ,(integer-reader-name bytes t))) ,(generate-reader t) (declaim (ftype (function (t) (unsigned-byte ,bits)) ,(integer-reader-name bytes nil))) ,(generate-reader nil))))) (defmacro integer-writer (bytes) "Create a function to write integers to a binary stream." (let ((bits (* 8 bytes))) `(progn (declaim (inline ,(integer-writer-name bytes t) ,(integer-writer-name bytes nil))) (defun ,(integer-writer-name bytes nil) (socket value) (declare (type stream socket) (type (unsigned-byte ,bits) value) #.*optimize*) ,@(if (= bytes 1) `((write-byte value socket)) (loop :for byte :from (1- bytes) :downto 0 :collect `(write-byte (ldb (byte 8 ,(* byte 8)) value) socket))) (values)) (defun ,(integer-writer-name bytes t) (socket value) (declare (type stream socket) (type (signed-byte ,bits) value) #.*optimize*) ,@(if (= bytes 1) `((write-byte (ldb (byte 8 0) value) socket)) (loop :for byte :from (1- bytes) :downto 0 :collect `(write-byte (ldb (byte 8 ,(* byte 8)) value) socket))) (values))))) ;; All the instances of the above that we need. (integer-reader 1) (integer-reader 2) (integer-reader 4) (integer-reader 8) (integer-writer 1) (integer-writer 2) (integer-writer 4) (defun write-bytes (socket bytes) "Write a byte-array to a stream." (declare (type stream socket) (type (simple-array (unsigned-byte 8)) bytes) #.*optimize*) (write-sequence bytes socket)) (defun write-str (socket string) "Write a null-terminated string to a stream \(encoding it when UTF-8 support is enabled.)." (declare (type stream socket) (type string string) #.*optimize*) (enc-write-string string socket) (write-uint1 socket 0)) (declaim (ftype (function (t unsigned-byte) (simple-array (unsigned-byte 8) (*))) read-bytes)) (defun read-bytes (socket length) "Read a byte array of the given length from a stream." (declare (type stream socket) (type fixnum length) #.*optimize*) (let ((result (make-array length :element-type '(unsigned-byte 8)))) (read-sequence result socket) result)) (declaim (ftype (function (t) string) read-str)) (defun read-str (socket) "Read a null-terminated string from a stream. Takes care of encoding when UTF-8 support is enabled." (declare (type stream socket) #.*optimize*) (enc-read-string socket :null-terminated t)) (defun skip-bytes (socket length) "Skip a given number of bytes in a binary stream." (declare (type stream socket) (type (unsigned-byte 32) length) #.*optimize*) (dotimes (i length) (read-byte socket))) (defun skip-str (socket) "Skip a null-terminated string." (declare (type stream socket) #.*optimize*) (loop :for char :of-type fixnum = (read-byte socket) :until (zerop char))) (defun ensure-socket-is-closed (socket &amp;key abort) (when (open-stream-p socket) (handler-case (close socket :abort abort) (error (error) (warn "Ignoring the error which happened while trying to close PostgreSQL socket: ~A" error))))) </textarea></form> <script> var editor = CodeMirror.fromTextArea(document.getElementById("code"), {lineNumbers: true}); </script> <p><strong>MIME types defined:</strong> <code>text/x-common-lisp</code>.</p> </article>
public/js/lib/codemirror/mode/commonlisp/index.html
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/b9372b9af6809b7cdd3bd118d0d0be9eebab231a
[ 0.00017388186824973673, 0.00017026334535330534, 0.00016010583203751594, 0.00017112100613303483, 0.000003070536877203267 ]
{ "id": 1, "code_window": [ " '/stories/upvote/',\n", " storyController.upvote\n", ");\n", "\n", "/**\n", " * Challenge related routes\n", " */\n", "app.get(\n", " '/challenges/',\n", " challengesController.returnNextChallenge\n", ");\n", "app.get(\n", " '/challenges/:challengeNumber',\n", " challengesController.returnChallenge\n", ");\n", "\n", "app.all('/account', passportConf.isAuthenticated);\n", "\n", "app.get('/account/api', userController.getAccountAngular);\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "app.js", "type": "replace", "edit_start_line_idx": 523 }
[ { "name": "Learn how Free Code Camp Works", "time": 2, "video": "114486344", "challengeNumber": 0, "steps": [ "Watch this 1-minute video, or simply read this summary.", "Welcome to Free Code Camp. We're a community of busy people learning to code.", "We built this community because learning to code is hard. But anyone who can stay motivated can learn to code. And the best way to stay motivated is to code with friends.", "To maximize accessibility, all our challenges are self-paced, browser-based, and free.", "All of us start with the same 100 hours of interactive coding challenges. These cover Computer Science and databases. They also cover in-demand JavaScript tools like jQuery, Node.js and MongoDB.", "Once we have a basic understanding of web development, we'll spend another 900 hours putting that theory into practice. We'll build full stack solutions for nonprofits.", "By the end of this process, we'll be good at coding. We'll have a portfolio of apps with happy users to prove it. We'll also have an alumni network of fellow coders and nonprofits ready to serve as references.", "If you make it through Free Code Camp, you will be able to get a coding job. There are far more job openings out there than there are qualified coders to fill them.", "Also, for every pure coding job, there are at least 5 additional jobs that require some coding skills. So even if you decide not to pursue coding as a career, you'll still walk away with a valuable job skill.", "There are 3 keys to succeeding in our community: do the challenges, make friends, and find a routine.", "Now it's time to join our chatroom. Click the \"I've completed this challenge\" button to move on to your next challenge." ] }, { "name": "Join Our Chat Room", "time": 5, "video": "124555254", "challengeNumber": 1, "steps": [ "Now we're going to join the Free Code Camp chat room. You can come here any time of day to hang out, ask questions, or find another camper to pair program with.", "Make sure your Free Code Camp account includes your email address. You can do this here: <a href='/account' target='_blank'>http://freecodecamp.com/account</a>.", "Click this link, which will email you an invite to Free Code Camp's Slack chat room: <a href='/api/slack' target='_blank'>http://freecodecamp.com/api/slack</a>.", "Now check your email and click the link in the email from Slack", "Complete the sign up process, then update your biographical information and upload an image. A picture of your face works best. This is how people will see you in the chat room, so put your best foot forward.", "Now enter the general chat room and introduce yourself to our chat room by typing: \"hello world!\".", "Tell your fellow campers how you found Free Code Camp. Also tell us why you want to learn to code.", "Keep the chat room open while you work through the other challenges. That way you ask for help if you get stuck on a challenge. You can also socialize when you feel like taking a break.", "You can also access this chat room by clicking the \"Chat\" button in the upper right hand corner." ] }, { "name": "Check out Camper News", "time": 5, "video": "124553410", "challengeNumber": 2, "steps": [ "Camper News is the best place for our campers to share and discuss helpful links.", "Click \"News\" in the upper right hand corner.", "You'll see a variety of links that have been submitted. Click on the \"Discuss\" button under one of them.", "You can upvote links. This will push the link up the rankings of hot links.", "You an also comment on a link. If someone responds to your comment, you'll get an email notification so you can come back and respond to them.", "You can also submit links. You can modify the link's headline and also leave an initial comment about the link.", "You can view the portfolio pages of any camper who has posted links or comments on Camper News. Just click on their photo.", "When you submit a link, you'll get a point. You will also get a point each time someone upvotes your link." ] }, { "name": "Build a Personal Website", "time": 60, "video": "114627406", "challengeNumber": 3, "steps": [ "There are tons of interactive HTML and CSS tutorials out there, but Nathan Bashaw and Christine Bower's Dash tutorials - which they built for General Assembly - are our favorite.", "Go to <a href='https://dash.generalassemb.ly/projects/annas-website-1' target='_blank'>https://dash.generalassemb.ly/projects/annas-website-1</a> and get started with your first project."] }, { "name": "Build a Responsive Blog Theme", "time": 60, "video": "114578441", "challengeNumber": 4, "steps": [ "Next, let's learn about responsive web design and continue learning about HTML and CSS.", "A responsive website will automatically adapt to changes in your browser's width. This means that you can make one version of a website that will look good on desktop, tablet and phone.", "Later, we'll use Twitter's Bootstrap CSS framework to build responsive websites.", "You can check it out here: <a href='http://getbootstrap.com/' target='_blank'>http://getbootstrap.com/</a>.", "Go to <a href='https://dash.generalassemb.ly/projects/jeffs-blog-1' target='_blank'>https://dash.generalassemb.ly/projects/jeffs-blog-1</a> and complete the second project." ] }, { "name": "Build a Small Business Website", "time": 60, "video": "114578438", "challengeNumber": 5, "steps": [ "Ready for some more HTML and CSS fundamentals?", "Go to <a href='https://dash.generalassemb.ly/projects/eshas-restaurant-1' target='_blank'>https://dash.generalassemb.ly/projects/eshas-restaurant-1</a> and complete the third project."] }, { "name": "Tweak HTML and CSS in CodePen", "time": 10, "video": "110752744", "challengeNumber": 6, "steps": [ "Now we're going to learn how to use a tool called CodePen, which lets you experiment with HTML and CSS, and even create single-page web applications, right in your browser!", "Go to <a href='http://www.newsweek.com/' target='_blank'>http://www.newsweek.com/</a>", "Change the window size. Note that Newsweek.com is using <strong>Responsive Design</strong>.", "Right-click an area of the page that doesn't have any HTML elements on it, then choose 'view page source'.", "Select all the text, then copy it.", "Go to <a href='http://codepen.io/pen/' target='_blank'>http://codepen.io/pen/</a>", "Paste the HTML you copied from Newsweek.com into the HTML field of CodePen.", "You now have your own customizable version of the Newsweek.com website. See if you can change some of the text and images." ] }, { "name": "Build a CSS Robot", "time": 60, "video": "114578436", "challengeNumber": 7, "steps": [ "Now let's learn some more CSS, and a small amount of a JavaScript-based tool called jQuery.", "Go to <a href='https://dash.generalassemb.ly/projects/cotbots-1' target='_blank'>https://dash.generalassemb.ly/projects/cotbots-1</a> and complete the fourth project."] }, { "name": "Get Started with jQuery", "time": 30, "video": "114578435", "challengeNumber": 8, "steps": [ "jQuery is a powerful tool for manipulating HTML elements.", "It's a lot easier to use than JavaScript itself, so we'll learn it first.", "It's also extremely popular with employers, so we're going to learn it well.", "Code School has an excellent free course that will walk us through the basics of jQuery.", "Go to <a href='http://try.jquery.com/levels/1/challenges/1' target='_blank'>http://try.jquery.com/levels/1/challenges/1</a> and complete the first section." ] }, { "name": "Traverse the DOM", "time": 30, "video": "114591805", "challengeNumber": 9, "steps": [ "Now let's learn more about DOM traversal - that is, moving from one HTML element to the next.", "Go to <a href='http://try.jquery.com/levels/2/challenges/1' target='_blank'>http://try.jquery.com/levels/2/challenges/1</a> and complete the second section." ] }, { "name": "Work with the DOM", "time": 30, "video": "114591804", "challengeNumber": 10, "steps": [ "Let's learn some more advanced ways to use jQuery to manipulate the DOM.", "Go to <a href='http://try.jquery.com/levels/3/challenges/1' target='_blank'>http://try.jquery.com/levels/3/challenges/1</a> and complete the third section." ] }, { "name": "Listen for DOM Events", "time": 30, "video": "114591802", "challengeNumber": 11, "steps": [ "Now let's learn how to use jQuery Listeners. These will \"listen\" for something to happen, and then trigger a subsequent event", "Go to <a href='http://try.jquery.com/levels/4/challenges/1' target='_blank'>http://try.jquery.com/levels/4/challenges/1</a> and complete the fourth section." ] }, { "name": "Use jQuery for Styling", "time": 30, "video": "114591801", "challengeNumber": 12, "steps": [ "Finally, let's use jQuery to manipulate the way websites look by changing the CSS of elements.", "Go to <a href='http://try.jquery.com/levels/5/challenges/1' target='_blank'>http://try.jquery.com/levels/5/challenges/1</a> and complete the fifth section." ] }, { "name": "Build a MadLibs Game", "time": 60, "video": "114591799", "challengeNumber": 13, "steps": [ "Now that we've built a foundation in jQuery, let's go back to Dash and do its last challenge.", "If you aren't familiar with Mad Libs, they basically involve inserting random nouns, adjectives and verbs into stories. The stories that result are often hilarious.", "Go to <a href='https://dash.generalassemb.ly/projects/mad-libs-1' target='_blank'>https://dash.generalassemb.ly/projects/mad-libs-1</a> and complete the fifth project." ] }, { "name": "Discover Chrome's DevTools", "time": 90, "video": "110752743", "challengeNumber": 14, "steps": [ "It's time to learn the most powerful tool your browser has - the Development Tools!", "If you aren't already using Chrome, you'll want to download it here: <a href='http://www.google.com/chrome/' target='_blank'>http://www.google.com/chrome/</a>. While it's true that Firefox has a tool called Firebug that is very similar to Chrome's DevTools, we will use Chrome for this challenge.", "Note that this course, jointly produced by Google and Code School, is technologically impressive, but occasionally buggy. If you encounter a bug, just ignore it and keep going.", "Go to <a href='http://discover-devtools.codeschool.com' target='_blank'>http://discover-devtools.codeschool.com</a> and complete this short course." ] }, { "name": "Tackle jQuery Exercises", "time": 60, "video": "113173612", "challengeNumber": 15, "steps": [ "We've built some special jQuery challenges to help you reinforce your knowledge of this fundamental skill.", "There are many correct ways to solve each of these exercises. After you complete the challenge, you can compare your solution with our solution by pressing the \"#solution-button\" button.", "Go to <a href='http://freecodecamp.com/jquery-exercises' target='_blank'>http://freecodecamp.com/jquery-exercises</a> and complete the exercises." ] }, { "name": "Customize Bootstrap", "time": 15, "video": "110752741", "challengeNumber": 16, "steps": [ "Let's learn a little more about Twitter's responsive CSS framework, Bootstrap, and how we can add some custom themes to it.", "Go to <a href='http://getbootstrap.com/components/' target='_blank'>http://getbootstrap.com/components/</a>", "Right-click an area of the page that doesn't have any HTML elements on it, then choose 'view page source'.", "Select all the text, then copy it.", "Go to <a href='http://codepen.io/pen/' target='_blank'>http://codepen.io/pen/</a>", "Paste the HTML you copied from GetBootStrap.com into the HTML field of CodePen.", "Go to <a href='http://bootswatch.com/' target='_blank'>http://bootswatch.com/</a>", "Decide which theme you want to use.", "Click the down arrow next to the download button and choose 'bootstrap.css'.", "Select all the text, then copy it.", "Go back to CodePen and paste the CSS you copied from Bootswatch.com into the CSS field of CodePen.", "Your Bootswatch CSS should now be applied to the HTML from the GetBootStrap page.", "This page is currently using a two-column layout, with the main content on the left and additional navigation on the right. See if you can make it a one-column layout." ] }, { "name": "Inject Animation into CSS", "time": 15, "video": "110752740", "challengeNumber": 17, "steps": [ "You may have noticed some sites have cool animations. Actually, animating DOM elements is pretty straightforward if you use a CSS library called Animate.css.", "Go to <a href='http://daneden.github.io/animate.css/' target='_blank'>http://daneden.github.io/animate.css/</a> and try out some of the CSS animations.", "Go to <a href='http://codepen.io/ossia/pen/bGegt' target='_blank'>http://codepen.io/ossia/pen/bGegt</a>.", "Press the \"Fork\" button. This will fork, meaning create a copy of, the CodePen.", "Click the gear in the CSS column.", "Click \"Add another resource\" and start typing \"animate.css\". Click on the dropdown results to autocomplete it.", "Now that you have Animate.css enabled, use jQuery and the \"toggleClass\" method to add an animated class to all h1 elements when you click the \"Press Me\" button." ] }, { "name": "Learn Basic Computer Science", "time": 120, "video": "114628241", "challengeNumber": 18, "steps": [ "Stanford has an excellent free online Computer Science curriculum. This interactive course uses a modified version of JavaScript. It will cover a lot of concepts quickly.", "Note that Harvard also has an excellent introduction to computer science course called CS50, but it takes more than 100 hours to complete, and doesn't use JavaScript.", "Despite being completely self-paced, Stanford's CS101 course is broken up into weeks. Each of the following challenges will address one of those weeks.", "Go to <a href='https://class.stanford.edu/courses/Engineering/CS101/Summer2014/courseware/z54/z1/' target='_blank'>https://class.stanford.edu/courses/Engineering/CS101/Summer2014/courseware/z54/z1/</a> and complete the first week's course work." ] }, { "name": "Learn Loops", "time": 120, "video": "114597348", "challengeNumber": 19, "steps": [ "Now let's tackle week 2 of Stanford's Intro to Computer Science course.", "This will introduce us to loops, a fundamental feature of every programming language.", "Go to <a href='https://class.stanford.edu/courses/Engineering/CS101/Summer2014/courseware/z100/a7a70ce6e4724c58862ee6007284face/' target='_blank'>https://class.stanford.edu/courses/Engineering/CS101/Summer2014/courseware/z100/a7a70ce6e4724c58862ee6007284face/</a> and complete Week 2." ] }, { "name": "Learn Computer Hardware", "time": 120, "video": "114597347", "challengeNumber": 20, "steps": [ "Week 3 of Stanford's Intro to Computer Science covers computer hardware and explains Moore's law of exponential growth in the price-performance of processors.", "This challenge will also give you an understanding of how bits and bytes work.", "Go to <a href='https://class.stanford.edu/courses/Engineering/CS101/Summer2014/courseware/z143/z101/' target='_blank'>https://class.stanford.edu/courses/Engineering/CS101/Summer2014/courseware/z143/z101/</a> and complete Week 3." ] }, { "name": "Learn Computer Networking", "time": 120, "video": "114604811", "challengeNumber": 21, "steps": [ "Now that you've learned about computer hardware, it's time to learn about the software that runs on top of it.", "Particularly important, you will learn about networks and TCP/IP - the protocol that powers the internet.", "Go to <a href='https://class.stanford.edu/courses/Engineering/CS101/Summer2014/courseware/z187/z144/' target='_blank'>https://class.stanford.edu/courses/Engineering/CS101/Summer2014/courseware/z187/z144/</a> and complete Week 4." ] }, { "name": "Learn Boolean Logic", "time": 120, "video": "114604812", "challengeNumber": 22, "steps": [ "Now we'll do some more table exercises and learn boolean logic.", "We'll also learn the difference between digital data and analog data.", "Go to <a href='https://class.stanford.edu/courses/Engineering/CS101/Summer2014/courseware/z208/z188/' target='_blank'>https://class.stanford.edu/courses/Engineering/CS101/Summer2014/courseware/z208/z188/</a> and complete Week 5." ] }, { "name": "Learn Computer Security", "time": 120, "video": "114604813", "challengeNumber": 23, "steps": [ "We're almost done with Stanford's Introduction to Computer Science course!", "We'll learn about one of the most important inventions of the 20th century - spreadsheets.", "We'll also learn about Computer Security and some of the more common vulnerabilities software systems have.", "Go to <a href='https://class.stanford.edu/courses/Engineering/CS101/Summer2014/courseware/z229/z213/' target='_blank'>https://class.stanford.edu/courses/Engineering/CS101/Summer2014/courseware/z229/z213/</a> and complete Week 6, the final week of the course." ] }, { "name": "Build an Adventure Game", "time": 60, "video": "114604814", "challengeNumber": 24, "steps": [ "Now that you understand some Computer Science fundamentals, let's focus on programming JavaScript!", "We're going to work through Codecademy's famous interactive JavaScript course.", "This course will teach us some JavaScript fundamentals while guiding us through the process of building interesting web apps, all within Codecademy's learner-friendly environment!", "Go to <a href='http://www.codecademy.com/courses/getting-started-v2/0/1' target='_blank'>http://www.codecademy.com/courses/getting-started-v2/0/1</a> and complete the section.", "Be sure to also complete this section: <a href='http://www.codecademy.com/courses/javascript-beginner-en-x9DnD/0/1' target='_blank'>http://www.codecademy.com/courses/javascript-beginner-en-x9DnD/0/1</a>." ] }, { "name": "Build Rock Paper Scissors", "time": 60, "video": "114604815", "challengeNumber": 25, "steps": [ "Now we'll learn how JavaScript functions work, and use them to build a simple Rock Paper Scissors game.", "Go to <a href='http://www.codecademy.com/courses/javascript-beginner-en-6LzGd/0/1' target='_blank'>http://www.codecademy.com/courses/javascript-beginner-en-6LzGd/0/1</a> and complete the section.", "Be sure to also complete this section: <a href='http://www.codecademy.com/courses/javascript-beginner-en-Bthev-mskY8/0/1' target='_blank'>http://www.codecademy.com/courses/javascript-beginner-en-Bthev-mskY8/0/1</a>." ] }, { "name": "Learn JavaScript For Loops", "time": 60, "video": "114614220", "challengeNumber": 26, "steps": [ "Let's learn more about the loops that make virtually all programs possible - the \"For Loop\" and \"While Loop\". First, we'll learn the For Loop.", "Go to <a href='http://www.codecademy.com/courses/javascript-beginner-en-NhsaT/0/1' target='_blank'>http://www.codecademy.com/courses/javascript-beginner-en-NhsaT/0/1web</a> and complete both the both For and While loop section.", "Be sure to also complete this section: <a href='http://www.codecademy.com/courses/javascript-beginner-en-XEDZA/0/1' target='_blank'>http://www.codecademy.com/courses/javascript-beginner-en-XEDZA/0/1</a>." ] }, { "name": "Learn JavaScript While Loops", "time": 60, "video": "114612889", "challengeNumber": 27, "steps": [ "Go to <a href='http://www.codecademy.com/courses/javascript-beginner-en-ASGIv/0/1' target='_blank'>http://www.codecademy.com/courses/javascript-beginner-en-ASGIv/0/1</a> and complete the section.", "Be sure to also complete this section: <a href='http://www.codecademy.com/courses/javascript-beginner-en-mrTNH-6VIZ9/0/1' target='_blank'>http://www.codecademy.com/courses/javascript-beginner-en-mrTNH-6VIZ9/0/1</a>." ] }, { "name": "Learn Control Flow", "time": 60, "video": "114612888", "challengeNumber": 28, "steps": [ "Much of human reasoning can be broken down into what we call Boolean Logic. Lucky for us, computers can think the same way! Let's learn how to instruct our computers by writing \"If Statements\" and \"Else Statements\".", "We'll also learn some advanced \"Control Flow\" principals, such as ways we can exit loops early.", "Go to <a href='http://www.codecademy.com/courses/javascript-beginner-en-qDwp0/0/1' target='_blank'>http://www.codecademy.com/courses/javascript-beginner-en-qDwp0/0/1</a> and complete the section.", "Be sure to also complete this section: <a href='http://www.codecademy.com/courses/javascript-beginner-en-ZA2rb/0/1' target='_blank'>http://www.codecademy.com/courses/javascript-beginner-en-ZA2rb/0/1</a>." ] }, { "name": "Build a Contact List", "time": 60, "video": "114612887", "challengeNumber": 29, "steps": [ "Up to this point, you've been working mostly with strings and numbers. Now we're going to learn more complicated data structures, like \"Arrays\" and \"Objects\".", "Go to <a href='http://www.codecademy.com/courses/javascript-beginner-en-9Sgpi/0/1' target='_blank'>http://www.codecademy.com/courses/javascript-beginner-en-9Sgpi/0/1</a> and complete the section.", "Be sure to also complete this section: <a href='http://www.codecademy.com/courses/javascript-beginner-en-3bmfN/0/1' target='_blank'>http://www.codecademy.com/courses/javascript-beginner-en-3bmfN/0/1</a>." ] }, { "name": "Build an Address Book", "time": 60, "video": "114612885", "challengeNumber": 30, "steps": [ "Let's learn more about objects.", "Go to <a href='http://www.codecademy.com/courses/spencer-sandbox/0/1' target='_blank'>http://www.codecademy.com/courses/spencer-sandbox/0/1</a> and complete the section.", "Be sure to also complete this section: <a href='http://www.codecademy.com/courses/building-an-address-book/0/1?curriculum_id=506324b3a7dffd00020bf661' target='_blank'>http://www.codecademy.com/courses/building-an-address-book/0/1?curriculum_id=506324b3a7dffd00020bf661</a>." ] }, { "name": "Build a Cash Register", "time": 60, "video": "114612882", "challengeNumber": 31, "steps": [ "In this final Codecademy section, we'll learn even more about JavaScript objects.", "Go to <a href='http://www.codecademy.com/courses/objects-ii/0/1' target='_blank'>http://www.codecademy.com/courses/objects-ii/0/1</a> and complete this section.", "Be sure to also complete the final section: <a href='http://www.codecademy.com/courses/close-the-super-makert/0/1' target='_blank'>http://www.codecademy.com/courses/close-the-super-makert/0/1</a>." ] }, { "name": "Get Help the Hacker Way", "time": 30, "video": "111500801", "challengeNumber": 32, "steps": [ "Watch the video to learn the RSAP (Read, Search, Ask, Post) methodology for getting help.", "Try an intelligent Google query that involves JavaScript and filters for this year (since JavaScript changes).", "Go to <a href='http://stackoverflow.com/' target='_blank'>http://stackoverflow.com/</a> and view the recent questions.", "Go to <a href='http://webchat.freenode.net/' target='_blank'>http://webchat.freenode.net/</a> and create an IRC account.", "Join the #LearnJavaScript chat room and introduce yourself as a Free Code Camp student.", "Finally, we have a special chat room specifically for getting help with tools you learn through Free Code Camp Challenges. Go to <a href='https://gitter.im/FreeCodeCamp/Help' target='_blank'>https://gitter.im/FreeCodeCamp/Help</a>. Keep this chat open while you work on the remaining challenges.", "Now you have several ways of getting help when you're stuck." ] }, { "name": "Learn Regular Expressions", "time": 60, "video": "112547802", "challengeNumber": 33, "steps": [ "You can use a Regular Expression, or \"Regex\", to select specific types of characters in text.", "Check out <a href='http://www.regexr.com' target='_blank'>http://www.regexr.com</a>. It's a Regular Expression Sandbox.", "Now go to <a href='http://www.regexone.com' target='_blank'>http://www.regexone.com</a> and complete the tutorial and exercises 1 - 6.", "Note that you can click \"continue\" to move on to the next step as soon as all the tasks have green check marks beside them. You can often do this just by using the wildcard \"dot\" operator, but try to use the techniques that each lesson recommends." ] }, { "name": "Pair Program on Bonfires", "time": 60, "video": "119657641", "challengeNumber": 34, "steps": [ "OK, we're finally ready to start pair programming!", "Pair Programming is where two people code together on the same computer. It is an efficient way to collaborate, and widely practiced at software companies. Pair Programming is one of the core concepts of \"Agile\" Software Development, which you will hear more about later.", "Many people use Skype or Google Hangouts to pair program, but if you talk with professional software engineers, they will tell you that it's not really pair programming unless both people have the ability to use the keyboard and mouse.", "The most popular tool for pair programming is Screen Hero. You can download Screen Hero for <a href='http://links.screenhero.com/e/c/eyJlbWFpbF9pZCI6Ik1qQTNNem9XQkNJQ1pBQUNjd0FYQVZrVEdnRkxNamtfX0JWZEdGVEpSZkVCWlRwbFpXRTBNamM0WVMxaE56SmlMVEV4WlRRdE9HUXpZUzFpWXpVNE1HRTJNalkxTldNNk1UUTJNVEEyQUE9PSIsInBvc2l0aW9uIjowLCJocmVmIjoiaHR0cDovL2RsLnNjcmVlbmhlcm8uY29tL3NtYXJ0ZG93bmxvYWQvZklYQU1UUUJBTEtQQkhQTC9TY3JlZW5oZXJvLnppcD9zb3VyY2U9d2ViIn0=' target='_blank'>Mac</a> or <a href='http://links.screenhero.com/e/c/eyJlbWFpbF9pZCI6Ik1qQTNNem9XQkNJQ1pBQUNjd0FYQVZrVEdnRkxNamtfX0JWZEdGVEpSZkVCWlRwbFpXRTBNamM0WVMxaE56SmlMVEV4WlRRdE9HUXpZUzFpWXpVNE1HRTJNalkxTldNNk1UUTJNVEEyQUE9PSIsInBvc2l0aW9uIjoxLCJocmVmIjoiaHR0cDovL2RsLnNjcmVlbmhlcm8uY29tL3NtYXJ0ZG93bmxvYWQvZklYQU1UUUJBTEtQQkhQTC9TY3JlZW5oZXJvLXNldHVwLmV4ZSJ9' target='_blank'>Windows</a>. Create your new user account from within the app.", "We have a special chat room for people ready to pair program. Go to <a href='https://gitter.im/FreeCodeCamp/LetsPair' target='_blank'>https://gitter.im/FreeCodeCamp/LetsPair</a> and type \"Hello Pair Programmers!\"", "If someone is available, they will be your \"pair\" - the person you pair programming with.", "If no one gets back to you in the first few minutes, don't worry. There will be lots of opportunities to pair program in the future.", "If someone does get back to you, private message them and ask for the email address they used to register Screen Hero.", "Add them as a new contact in Screen Hero, then click the monitor-looking button to attempt to share your screen with them.", "Once the Screen Hero session starts, your screen's margins will glow orange. You are now sharing your screen.", "Your pair will have their own cursor, and will be able to type text on his or her and keyboard.", "Now it's time to tackle our Bonfires.", "Go to <a href='http://freecodecamp.com/bonfires' target='_blank'>http://freecodecamp.com/bonfires</a> and start working through our Bonfire challenges.", "Once you you finish pair programming, end the session in Screen Hero session.", "Congratulations! You have completed your first pair programming session.", "Try to pair program with different campers until you've completed all the Bonfire challenges. This is a big time investment, but the JavaScript practice you'll get, along with the scripting and algorithm experience, are well worth it!", "You can complete Bonfire challenges while you continue to work through Free Code Camp's challenges. Take your time.", "Mark this challenge as complete and move on." ] }, { "name": "Manage Source Code with Git", "time": 30, "video": "114635309", "challengeNumber": 35, "steps": [ "Revision Control Systems like Git ensure that, no matter how you experiment with your code, you can always roll back your app to a stable previous state.", "Git is also a great way to share and contribute to open source software.", "Go to <a href='https://www.codeschool.com/courses/try-git' target='_blank'>https://www.codeschool.com/courses/try-git</a> and complete this short interactive course." ] }, { "name": "Get Started with Node.js", "time": 45, "video": "114686471", "challengeNumber": 36, "steps": [ "Note that this Code School course is no longer free. We have free alternatives to this course <a href='/nodeschool-challenges' target='_blank'>here</a>.", "Now that we understand some Computer Science and JavaScript programming, you're ready to move on to Full-stack JavaScript!", "The first step is to familiarize ourselves Node.js, the JavaScript-based web server that most full-stack JavaScript apps use.", "When you're ready, go to <a href='http://campus.codeschool.com/courses/real-time-web-with-node-js/level/1/video/1' target='_blank'>http://campus.codeschool.com/courses/real-time-web-with-node-js/level/1/video/1</a> and complete the first chapter." ] }, { "name": "Try Node.js Events", "time": 45, "video": "114684206", "challengeNumber": 37, "steps": [ "Note that this Code School course is no longer free. We have free alternatives to this course <a href='/nodeschool-challenges' target='_blank'>here</a>.", "One of the reasons Node.js is so fast is that it is \"evented.\" It processes events in an asynchronous manner.", "As a result, Node.js relies on asynchronous callbacks.", "We'll learn more about how events and callbacks work in this exciting Code School lesson.", "Go to <a href='http://campus.codeschool.com/courses/real-time-web-with-node-js/level/2/video/1' target='_blank'>http://campus.codeschool.com/courses/real-time-web-with-node-js/level/2/video/1</a> and complete the section." ] }, { "name": "Try Node.js Streams", "time": 45, "video": "114684209", "challengeNumber": 38, "steps": [ "Note that this Code School course is no longer free. We have free alternatives to this course <a href='/nodeschool-challenges' target='_blank'>here</a>.", "In this Code School lesson, we'll learn about streaming data back and forth between the client to the server.", "We'll also learn about FS, or File System, an important Node.js module for streaming data.", "Go to <a href='http://campus.codeschool.com/courses/real-time-web-with-node-js/level/3/video/1' target='_blank'>http://campus.codeschool.com/courses/real-time-web-with-node-js/level/3/video/1</a> and complete the section." ] }, { "name": "Learn how Node.js Modules Work", "time": 45, "video": "114684213", "challengeNumber": 39, "steps": [ "Note that this Code School course is no longer free. We have free alternatives to this course <a href='/nodeschool-challenges' target='_blank'>here</a>.", "One of the most exciting features of Node.js is NPM - Node Package Manager", "With NPM, you quickly install any of thousands of Node.js modules into your app, and it will automatically handle the other modules that each module dependends upon downstream.", "In this lesson, we'll learn how to include these modules in our Node.js app by requiring them as variables.", "Go to <a href='http://campus.codeschool.com/courses/real-time-web-with-node-js/level/4/video/1' target='_blank'>http://campus.codeschool.com/courses/real-time-web-with-node-js/level/4/video/1</a> and complete the section." ] }, { "name": "Start an Express.js Server", "time": 45, "video": "114684247", "challengeNumber": 40, "steps": [ "Note that this Code School course is no longer free. We have free alternatives to this course <a href='/nodeschool-challenges' target='_blank'>here</a>.", "We'll complete Code School's Express.js course shortly after completing this course, but this challenge will give you a quick tour of the Express.js framework.", "Go to <a href='http://campus.codeschool.com/courses/real-time-web-with-node-js/level/5/video/1' target='_blank'>http://campus.codeschool.com/courses/real-time-web-with-node-js/level/5/video/1</a> and complete the section." ] }, { "name": "Use Socket.io", "time": 45, "video": "114684530", "challengeNumber": 41, "steps": [ "Note that this Code School course is no longer free. We have free alternatives to this course <a href='/nodeschool-challenges' target='_blank'>here</a>.", "Go to <a href='http://campus.codeschool.com/courses/real-time-web-with-node-js/level/6/video/1' target='_blank'>http://campus.codeschool.com/courses/real-time-web-with-node-js/level/6/video/1</a> and complete the section." ] }, { "name": "Use Redis to Persist Data", "time": 45, "video": "114684532", "challengeNumber": 42, "steps": [ "Note that this Code School course is no longer free. We have free alternatives to this course <a href='/nodeschool-challenges' target='_blank'>here</a>.", "Redis is a key-value store, which is a type of non-relational database. It's one of the fastest and easiest ways to persist data.", "Even though we'll ultimately use MongoDB and other technologies to persist data, Redis is quite easy to learn and is still worth learning.", "Go to <a href='http://campus.codeschool.com/courses/real-time-web-with-node-js/level/7/video/1' target='_blank'>http://campus.codeschool.com/courses/real-time-web-with-node-js/level/7/video/1</a> and complete the section." ] }, { "name": "Dive Deeper into Express.js", "time": 45, "video": "114684533", "challengeNumber": 43, "steps": [ "Note that this Code School course is no longer free. We have free alternatives to this course <a href='/nodeschool-challenges' target='_blank'>here</a>.", "Go to <a href='http://campus.codeschool.com/courses/building-blocks-of-express-js/level/1/video/1' target='_blank'>http://campus.codeschool.com/courses/building-blocks-of-express-js/level/1/video/1</a> and complete the section." ] }, { "name": "Setup Express.js Middleware", "time": 45, "video": "114684535", "challengeNumber": 44, "steps": [ "Note that this Code School course is no longer free. We have free alternatives to this course <a href='/nodeschool-challenges' target='_blank'>here</a>.", "Express.js makes extensive use of middleware - a stack of functions that run sequentially in response to a specific event.", "Let's learn how to incorporate modules and middleware into our Express.js app.", "Go to <a href='http://campus.codeschool.com/courses/building-blocks-of-express-js/level/2/video/1' target='_blank'>http://campus.codeschool.com/courses/building-blocks-of-express-js/level/2/video/1</a> and complete the section." ] }, { "name": "Take Advantage of Parameters", "time": 45, "video": "114684537", "challengeNumber": 45, "steps": [ "Note that this Code School course is no longer free. We have free alternatives to this course <a href='/nodeschool-challenges' target='_blank'>here</a>.", "Have you ever noticed a question mark in your browser's address bar, followed by a series of strings? Those are parameters. Parameters are an efficient way to pass information to the server between page loads.", "We'll learn about parameters, along with a powerful Express.js feature called Dynamic Routing, in this exciting Code School lesson.", "Go to <a href='http://campus.codeschool.com/courses/building-blocks-of-express-js/level/3/video/1' target='_blank'>http://campus.codeschool.com/courses/building-blocks-of-express-js/level/3/video/1</a> and complete the section." ] }, { "name": "Add the Body Parser", "time": 45, "video": "114684720", "challengeNumber": 46, "steps": [ "Note that this Code School course is no longer free. We have free alternatives to this course <a href='/nodeschool-challenges' target='_blank'>here</a>.", "Now we'll add the Body Parser module to Express.js. Body Parser is a powerful middleware that helps with routing.", "We'll also learn more about HTTP Requests, such as Post and Delete.", "Go to <a href='http://campus.codeschool.com/courses/building-blocks-of-express-js/level/4/video/1' target='_blank'>http://campus.codeschool.com/courses/building-blocks-of-express-js/level/4/video/1</a> and complete the section." ] }, { "name": "Configure Routes in Express.js", "time": 45, "video": "114684724", "challengeNumber": 47, "steps": [ "Note that this Code School course is no longer free. We have free alternatives to this course <a href='/nodeschool-challenges' target='_blank'>here</a>.", "For this last Code School Express.js challenge, we'll refactor our routes.", "Go to <a href='http://campus.codeschool.com/courses/building-blocks-of-express-js/level/5/video/1' target='_blank'>http://campus.codeschool.com/courses/building-blocks-of-express-js/level/5/video/1</a> and complete the section." ] }, { "name": "Try MongoDB", "time": 30, "video": "114685061", "challengeNumber": 48, "steps": [ "MongoDB is a popular NoSQL (Not Only SQL) database used by many JavaScript apps.", "Go to <a href='http://try.mongodb.org/' target='_blank'>http://try.mongodb.org/</a> and work through their interactive MongoDB tutorial." ] }, { "name": "Get Started with Angular.js", "time": 45, "video": "114684726", "challengeNumber": 49, "steps": [ "Code School has a short, free Angular.js course. This will give us a quick tour of Angular.js's mechanics and features.", "In this course, we'll build a virtual shop entirely in Angular.js.", "Go to <a href='http://campus.codeschool.com/courses/shaping-up-with-angular-js/level/1/section/1/video/1' target='_blank'>http://campus.codeschool.com/courses/shaping-up-with-angular-js/level/1/section/1/video/1</a> and complete the section." ] }, { "name": "Apply Angular.js Directives", "time": 45, "video": "114684727", "challengeNumber": 50, "steps": [ "Directives serve as markers in your HTML. When Angular.js compiles your HTML, it will can alter the behavior of DOM elements based on the directives you've used.", "Let's learn how these powerful directives work, and how to use them to make your web apps more dynamic", "Go to <a href='http://campus.codeschool.com/courses/shaping-up-with-angular-js/level/2/section/1/video/1' target='_blank'>http://campus.codeschool.com/courses/shaping-up-with-angular-js/level/2/section/1/video/1</a> and complete the section." ] }, { "name": "Power Forms with Angular.js", "time": 45, "video": "114684729", "challengeNumber": 51, "steps": [ "One area where Angular.js really shines is its powerful web forms.", "Learn how to create reactive Angular.js forms, including real-time form validation.", "Go to <a href='http://campus.codeschool.com/courses/shaping-up-with-angular-js/level/3/section/1/video/1' target='_blank'>http://campus.codeschool.com/courses/shaping-up-with-angular-js/level/3/section/1/video/1</a> and complete the section." ] }, { "name": "Customize Angular.js Directives", "time": 45, "video": "114685062", "challengeNumber": 52, "steps": [ "Now we'll learn how to modify existing Angular.js directives, and even build directives of your own.", "Go to <a href='http://campus.codeschool.com/courses/shaping-up-with-angular-js/level/4/section/1/video/1' target='_blank'>http://campus.codeschool.com/courses/shaping-up-with-angular-js/level/4/section/1/video/1</a> and complete the section." ] }, { "name": "Create Angular.js Services", "time": 45, "video": "114685060", "challengeNumber": 53, "steps": [ "Services are functions that you can use and reuse throughout your Angular.js app to get things done.", "We'll learn how to use services in this final Code School Angular.js challenge.", "Go to <a href='http://campus.codeschool.com/courses/shaping-up-with-angular-js/level/5/section/1/video/1' target='_blank'>http://campus.codeschool.com/courses/shaping-up-with-angular-js/level/5/section/1/video/1</a> and complete the section." ] } ]
seed_data/challenges.json
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/b9372b9af6809b7cdd3bd118d0d0be9eebab231a
[ 0.0003419680579099804, 0.00017363586812280118, 0.00016405682254116982, 0.0001700331486063078, 0.000021625577574013732 ]
{ "id": 2, "code_window": [ " }\n", " }\n", " var date1 = new Date(\"10/15/2014\");\n", " var date2 = new Date();\n", "\n", "\n", " livePairProgramming: function(req, res) {\n", " res.render('resources/live-pair-programming', {\n", " title: 'Live Pair Programming'\n", " });\n", " },\n", "\n", " var timeDiff = Math.abs(date2.getTime() - date1.getTime());\n", " var daysRunning = Math.ceil(timeDiff / (1000 * 3600 * 24));\n", " var announcements = resources.announcements;\n", " function numberWithCommas(x) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "controllers/resources.js", "type": "replace", "edit_start_line_idx": 151 }
var async = require('async'), User = require('../models/User'), Challenge = require('./../models/Challenge'), Bonfire = require('./../models/Bonfire'), Story = require('./../models/Story'), FieldGuide = require('./../models/FieldGuide'), Nonprofit = require('./../models/Nonprofit'), Comment = require('./../models/Comment'), resources = require('./resources.json'), steps = resources.steps, secrets = require('./../config/secrets'), bonfires = require('../seed_data/bonfires.json'), nonprofits = require('../seed_data/nonprofits.json'), coursewares = require('../seed_data/coursewares.json'), fieldGuides = require('../seed_data/field-guides.json'), moment = require('moment'), https = require('https'), debug = require('debug')('freecc:cntr:resources'), cheerio = require('cheerio'), request = require('request'), R = require('ramda'); /** * GET / * Resources. */ Array.zip = function(left, right, combinerFunction) { var counter, results = []; for (counter = 0; counter < Math.min(left.length, right.length); counter++) { results.push(combinerFunction(left[counter], right[counter])); } return results; }; module.exports = { privacy: function privacy(req, res) { res.render('resources/privacy', { title: 'Privacy' }); }, sitemap: function sitemap(req, res, next) { var appUrl = 'http://www.freecodecamp.com'; var now = moment(new Date()).format('YYYY-MM-DD'); User.find({'profile.username': {'$ne': '' }}, function(err, users) { if (err) { debug('User err: ', err); return next(err); } Courseware.find({}, function (err, challenges) { if (err) { debug('User err: ', err); return next(err); } Bonfire.find({}, function (err, bonfires) { if (err) { debug('User err: ', err); return next(err); } Story.find({}, function (err, stories) { if (err) { debug('User err: ', err); return next(err); } Nonprofit.find({}, function (err, nonprofits) { if (err) { debug('User err: ', err); return next(err); } FieldGuide.find({}, function (err, fieldGuides) { if (err) { debug('User err: ', err); return next(err); } res.header('Content-Type', 'application/xml'); res.render('resources/sitemap', { appUrl: appUrl, now: now, users: users, challenges: challenges, bonfires: bonfires, stories: stories, nonprofits: nonprofits, fieldGuides: fieldGuides }); }); }); }); }); }); }); }, chat: function chat(req, res) { if (req.user && req.user.progressTimestamps.length > 5) { res.redirect('http://gitter.im/freecodecamp/freecodecamp'); } else { res.render('resources/chat', { title: "Watch us code live on Twitch.tv" }); } }, twitch: function twitch(req, res) { res.render('resources/twitch', { title: "Enter Free Code Camp's Chat Rooms" }); }, githubCalls: function(req, res) { var githubHeaders = {headers: {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1521.3 Safari/537.36'}, port:80 }; request('https://api.github.com/repos/freecodecamp/freecodecamp/pulls?client_id=' + secrets.github.clientID + '&client_secret=' + secrets.github.clientSecret, githubHeaders, function(err, status1, pulls) { pulls = pulls ? Object.keys(JSON.parse(pulls)).length : "Can't connect to github"; request('https://api.github.com/repos/freecodecamp/freecodecamp/issues?client_id=' + secrets.github.clientID + '&client_secret=' + secrets.github.clientSecret, githubHeaders, function (err, status2, issues) { issues = ((pulls === parseInt(pulls)) && issues) ? Object.keys(JSON.parse(issues)).length - pulls : "Can't connect to GitHub"; res.send({"issues": issues, "pulls" : pulls}); }); }); }, trelloCalls: function(req, res, next) { request('https://trello.com/1/boards/BA3xVpz9/cards?key=' + secrets.trello.key, function(err, status, trello) { if (err) { return next(err); } trello = (status && status.statusCode === 200) ? (JSON.parse(trello)) : "Can't connect to to Trello"; res.end(JSON.stringify(trello)); }); }, bloggerCalls: function(req, res, next) { request('https://www.googleapis.com/blogger/v3/blogs/2421288658305323950/posts?key=' + secrets.blogger.key, function (err, status, blog) { if (err) { return next(err); } blog = (status && status.statusCode === 200) ? JSON.parse(blog) : "Can't connect to Blogger"; res.end(JSON.stringify(blog)); }); }, about: function(req, res, next) { if (req.user) { if (!req.user.profile.picture || req.user.profile.picture === "https://s3.amazonaws.com/freecodecamp/favicons/apple-touch-icon-180x180.png") { req.user.profile.picture = "https://s3.amazonaws.com/freecodecamp/camper-image-placeholder.png"; req.user.save(); } } var date1 = new Date("10/15/2014"); var date2 = new Date(); livePairProgramming: function(req, res) { res.render('resources/live-pair-programming', { title: 'Live Pair Programming' }); }, var timeDiff = Math.abs(date2.getTime() - date1.getTime()); var daysRunning = Math.ceil(timeDiff / (1000 * 3600 * 24)); var announcements = resources.announcements; function numberWithCommas(x) { return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); } User.count({}, function (err, c3) { if (err) { debug('User err: ', err); return next(err); } User.count({'points': {'$gt': 53}}, function (err, all) { if (err) { debug('User err: ', err); return next(err); } res.render('resources/learn-to-code', { title: 'About Free Code Camp', daysRunning: daysRunning, c3: numberWithCommas(c3), announcements: announcements }); }); }); }, randomPhrase: function() { var phrases = resources.phrases; return phrases[Math.floor(Math.random() * phrases.length)]; }, randomVerb: function() { var verbs = resources.verbs; return verbs[Math.floor(Math.random() * verbs.length)]; }, randomCompliment: function() { var compliments = resources.compliments; return compliments[Math.floor(Math.random() * compliments.length)]; }, allBonfireIds: function() { return bonfires.map(function(elem) { return { _id: elem._id, difficulty: elem.difficulty } }) .sort(function(a, b) { return a.difficulty - b.difficulty; }) .map(function(elem) { return elem._id; }); }, allFieldGuideIds: function() { return fieldGuides.map(function(elem) { return { _id: elem._id, } }) .map(function(elem) { return elem._id; }); }, allBonfireNames: function() { return bonfires.map(function(elem) { return { name: elem.name, difficulty: elem.difficulty, _id: elem._id } }) .sort(function(a, b) { return a.difficulty - b.difficulty; }) .map (function(elem) { return { name : elem.name, _id: elem._id } }); }, allFieldGuideNames: function() { return fieldGuides.map(function(elem) { return { name: elem.name } }) }, allNonprofitNames: function() { return nonprofits.map(function(elem) { return { name: elem.name } }) }, allCoursewareIds: function() { return coursewares.map(function(elem) { return { _id: elem._id, difficulty: elem.difficulty }; }) .sort(function(a, b) { return a.difficulty - b.difficulty; }) .map(function(elem) { return elem._id; }); }, allCoursewareNames: function() { return coursewares.map(function(elem) { return { name: elem.name, difficulty: elem.difficulty, challengeType: elem.challengeType, _id: elem._id }; }) .sort(function(a, b) { return a.difficulty - b.difficulty; }) .map (function(elem) { return { name: elem.name, challengeType: elem.challengeType, _id: elem._id }; }); }, whichEnvironment: function() { return process.env.NODE_ENV; }, getURLTitle: function(url, callback) { (function () { var result = {title: '', image: '', url: '', description: ''}; request(url, function (error, response, body) { if (!error && response.statusCode === 200) { var $ = cheerio.load(body); var metaDescription = $("meta[name='description']"); var metaImage = $("meta[property='og:image']"); var urlImage = metaImage.attr('content') ? metaImage.attr('content') : ''; var description = metaDescription.attr('content') ? metaDescription.attr('content') : ''; result.title = $('title').text().length < 141 ? $('title').text() : $('title').text().slice(0, 137) + " ..."; result.image = urlImage; result.description = description; callback(null, result); } else { callback('failed'); } }); })(); }, updateUserStoryPictures: function(userId, picture, username, cb) { var counter = 0, foundStories, foundComments; Story.find({'author.userId': userId}, function(err, stories) { if (err) { return cb(err); } foundStories = stories; counter++; saveStoriesAndComments(); }); Comment.find({'author.userId': userId}, function(err, comments) { if (err) { return cb(err); } foundComments = comments; counter++; saveStoriesAndComments(); }); function saveStoriesAndComments() { if (counter !== 2) { return; } var tasks = []; R.forEach(function(comment) { comment.author.picture = picture; comment.author.username = username; comment.markModified('author'); tasks.push(function(cb) { comment.save(cb); }); }, foundComments); R.forEach(function(story) { story.author.picture = picture; story.author.username = username; story.markModified('author'); tasks.push(function(cb) { story.save(cb); }); }, foundStories); async.parallel(tasks, function(err) { if (err) { return cb(err); } cb(); }); } } };
controllers/resources.js
1
https://github.com/freeCodeCamp/freeCodeCamp/commit/b9372b9af6809b7cdd3bd118d0d0be9eebab231a
[ 0.9984089732170105, 0.10368476808071136, 0.0001629464968573302, 0.00017187306366395205, 0.30188441276550293 ]
{ "id": 2, "code_window": [ " }\n", " }\n", " var date1 = new Date(\"10/15/2014\");\n", " var date2 = new Date();\n", "\n", "\n", " livePairProgramming: function(req, res) {\n", " res.render('resources/live-pair-programming', {\n", " title: 'Live Pair Programming'\n", " });\n", " },\n", "\n", " var timeDiff = Math.abs(date2.getTime() - date1.getTime());\n", " var daysRunning = Math.ceil(timeDiff / (1000 * 3600 * 24));\n", " var announcements = resources.announcements;\n", " function numberWithCommas(x) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "controllers/resources.js", "type": "replace", "edit_start_line_idx": 151 }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <HTML> <HEAD> <META HTTP-EQUIV="Content-Type" CONTENT="text/html; CHARSET=utf-8"> <TITLE>NIST DOM HTML Test - MENU</TITLE> </HEAD> <BODY onload="parent.loadComplete()"> <MENU COMPACT="COMPACT"> <LI>Interview</LI> <LI>Paperwork</LI> <LI>Give start date</LI> </MENU> </BODY> </HTML>
bower_components/jsdom/test/level2/html/files/menu.html
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/b9372b9af6809b7cdd3bd118d0d0be9eebab231a
[ 0.00017190641665365547, 0.00016887560195755213, 0.0001658447872614488, 0.00016887560195755213, 0.0000030308146961033344 ]
{ "id": 2, "code_window": [ " }\n", " }\n", " var date1 = new Date(\"10/15/2014\");\n", " var date2 = new Date();\n", "\n", "\n", " livePairProgramming: function(req, res) {\n", " res.render('resources/live-pair-programming', {\n", " title: 'Live Pair Programming'\n", " });\n", " },\n", "\n", " var timeDiff = Math.abs(date2.getTime() - date1.getTime());\n", " var daysRunning = Math.ceil(timeDiff / (1000 * 3600 * 24));\n", " var announcements = resources.announcements;\n", " function numberWithCommas(x) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "controllers/resources.js", "type": "replace", "edit_start_line_idx": 151 }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <HTML> <HEAD> <META HTTP-EQUIV="Content-Type" CONTENT="text/html; CHARSET=utf-8"> <TITLE>NIST DOM HTML Test - Applet</TITLE> </HEAD> <BODY onload="parent.loadComplete()"> <P> <APPLET ALIGN="bottom" ALT="Applet Number 1" ARCHIVE="" CODE="org/w3c/domts/DOMTSApplet.class" CODEBASE="applets" HEIGHT="306" HSPACE="0" NAME="applet1" VSPACE="0" WIDTH="301"></APPLET> </P> </BODY> </HTML>
bower_components/jsdom/test/level2/html/files/applet.html
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/b9372b9af6809b7cdd3bd118d0d0be9eebab231a
[ 0.0001737618731567636, 0.00017154263332486153, 0.0001693233789410442, 0.00017154263332486153, 0.000002219247107859701 ]
{ "id": 2, "code_window": [ " }\n", " }\n", " var date1 = new Date(\"10/15/2014\");\n", " var date2 = new Date();\n", "\n", "\n", " livePairProgramming: function(req, res) {\n", " res.render('resources/live-pair-programming', {\n", " title: 'Live Pair Programming'\n", " });\n", " },\n", "\n", " var timeDiff = Math.abs(date2.getTime() - date1.getTime());\n", " var daysRunning = Math.ceil(timeDiff / (1000 * 3600 * 24));\n", " var announcements = resources.announcements;\n", " function numberWithCommas(x) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "controllers/resources.js", "type": "replace", "edit_start_line_idx": 151 }
<!DOCTYPE html [ <!ATTLIST p attrExtEnt ENTITY #IMPLIED> <!ENTITY ent1 "Hello"> <!ENTITY ent2 SYSTEM "world.txt"> <!ENTITY entExt SYSTEM "earth.gif" NDATA gif> <!NOTATION gif SYSTEM "viewgif.exe"> ]> <html xmlns="http://www.w3.org/1999/xhtml"><head><title>canonicalform05</title></head><body onload="parent.loadComplete()"> <p attrExtEnt="entExt"> &ent1;, &ent2;! </p></body></html> <!-- Let world.txt contain "world" (excluding the quotes) -->
bower_components/jsdom/test/level3/core/files/orig/canonicalform05.xml
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/b9372b9af6809b7cdd3bd118d0d0be9eebab231a
[ 0.00017565475718583912, 0.00017211581871379167, 0.00016857688024174422, 0.00017211581871379167, 0.000003538938472047448 ]
{ "id": 3, "code_window": [ " });\n", "};\n", "\n", " story.save(function(err) {\n", " if (err) {\n", " return next(err);\n", " }\n", " res.send(JSON.stringify({\n", " storyLink: story.storyLink.replace(/\\s/g, '-').toLowerCase()\n", " }));\n", " });\n", "};\n", "\n", "exports.commentSubmit = function(req, res, next) {\n", " var data = req.body.data;\n", " if (req.user._id.toString() !== data.author.userId.toString()) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "controllers/story.js", "type": "replace", "edit_start_line_idx": 361 }
var gulp = require('gulp'), debug = require('debug')('freecc:gulp'), bower = require('bower-main-files'), nodemon = require('gulp-nodemon'), sync = require('browser-sync'), reload = sync.reload, inject = require('gulp-inject'), reloadDelay = 1000, eslint = require('gulp-eslint'); var paths = { server: './app.js', serverIgnore: [] }; gulp.task('inject', function() { gulp.src('views/home.jade') .pipe(inject(gulp.src(bower()), { //ignorePath: '/public' })) .pipe(gulp.dest('views')); }); gulp.task('serve', function(cb) { var called = false; nodemon({ script: paths.server, ext: '.js', ignore: paths.serverIgnore, env: { 'NODE_ENV': 'development', 'DEBUG': 'freecc:*' } }) .on('start', function() { if (!called) { called = true; setTimeout(function() { cb(); }, reloadDelay); } }) .on('restart', function(files) { if (files) { debug('Files that changes: ', files); } setTimeout(function() { debug('Restarting browsers'); reload(); }, reloadDelay); }); }); gulp.task('sync', ['serve'], function() { sync.init(null, { proxy: 'http://localhost:3000', logLeval: 'debug', files: ['public/js/lib/*/*.{js, jsx}'], port: 3001, open: true, reloadDelay: reloadDelay }); }); gulp.task('lint', function() { return gulp.src(['public/js/lib/**/*']) .pipe(eslint()) .pipe(eslint.format()); }); gulp.task('default', ['lint', 'serve', 'sync']);
gulpfile.js
1
https://github.com/freeCodeCamp/freeCodeCamp/commit/b9372b9af6809b7cdd3bd118d0d0be9eebab231a
[ 0.00017456912610214204, 0.00017165669123642147, 0.00016672494530212134, 0.0001726092305034399, 0.00000240622898672882 ]
{ "id": 3, "code_window": [ " });\n", "};\n", "\n", " story.save(function(err) {\n", " if (err) {\n", " return next(err);\n", " }\n", " res.send(JSON.stringify({\n", " storyLink: story.storyLink.replace(/\\s/g, '-').toLowerCase()\n", " }));\n", " });\n", "};\n", "\n", "exports.commentSubmit = function(req, res, next) {\n", " var data = req.body.data;\n", " if (req.user._id.toString() !== data.author.userId.toString()) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "controllers/story.js", "type": "replace", "edit_start_line_idx": 361 }
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE /** * Link to the project's GitHub page: * https://github.com/duralog/CodeMirror */ (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode('livescript', function(){ var tokenBase = function(stream, state) { var next_rule = state.next || "start"; if (next_rule) { state.next = state.next; var nr = Rules[next_rule]; if (nr.splice) { for (var i$ = 0; i$ < nr.length; ++i$) { var r = nr[i$], m; if (r.regex && (m = stream.match(r.regex))) { state.next = r.next || state.next; return r.token; } } stream.next(); return 'error'; } if (stream.match(r = Rules[next_rule])) { if (r.regex && stream.match(r.regex)) { state.next = r.next; return r.token; } else { stream.next(); return 'error'; } } } stream.next(); return 'error'; }; var external = { startState: function(){ return { next: 'start', lastToken: null }; }, token: function(stream, state){ while (stream.pos == stream.start) var style = tokenBase(stream, state); state.lastToken = { style: style, indent: stream.indentation(), content: stream.current() }; return style.replace(/\./g, ' '); }, indent: function(state){ var indentation = state.lastToken.indent; if (state.lastToken.content.match(indenter)) { indentation += 2; } return indentation; } }; return external; }); var identifier = '(?![\\d\\s])[$\\w\\xAA-\\uFFDC](?:(?!\\s)[$\\w\\xAA-\\uFFDC]|-[A-Za-z])*'; var indenter = RegExp('(?:[({[=:]|[-~]>|\\b(?:e(?:lse|xport)|d(?:o|efault)|t(?:ry|hen)|finally|import(?:\\s*all)?|const|var|let|new|catch(?:\\s*' + identifier + ')?))\\s*$'); var keywordend = '(?![$\\w]|-[A-Za-z]|\\s*:(?![:=]))'; var stringfill = { token: 'string', regex: '.+' }; var Rules = { start: [ { token: 'comment.doc', regex: '/\\*', next: 'comment' }, { token: 'comment', regex: '#.*' }, { token: 'keyword', regex: '(?:t(?:h(?:is|row|en)|ry|ypeof!?)|c(?:on(?:tinue|st)|a(?:se|tch)|lass)|i(?:n(?:stanceof)?|mp(?:ort(?:\\s+all)?|lements)|[fs])|d(?:e(?:fault|lete|bugger)|o)|f(?:or(?:\\s+own)?|inally|unction)|s(?:uper|witch)|e(?:lse|x(?:tends|port)|val)|a(?:nd|rguments)|n(?:ew|ot)|un(?:less|til)|w(?:hile|ith)|o[fr]|return|break|let|var|loop)' + keywordend }, { token: 'constant.language', regex: '(?:true|false|yes|no|on|off|null|void|undefined)' + keywordend }, { token: 'invalid.illegal', regex: '(?:p(?:ackage|r(?:ivate|otected)|ublic)|i(?:mplements|nterface)|enum|static|yield)' + keywordend }, { token: 'language.support.class', regex: '(?:R(?:e(?:gExp|ferenceError)|angeError)|S(?:tring|yntaxError)|E(?:rror|valError)|Array|Boolean|Date|Function|Number|Object|TypeError|URIError)' + keywordend }, { token: 'language.support.function', regex: '(?:is(?:NaN|Finite)|parse(?:Int|Float)|Math|JSON|(?:en|de)codeURI(?:Component)?)' + keywordend }, { token: 'variable.language', regex: '(?:t(?:hat|il|o)|f(?:rom|allthrough)|it|by|e)' + keywordend }, { token: 'identifier', regex: identifier + '\\s*:(?![:=])' }, { token: 'variable', regex: identifier }, { token: 'keyword.operator', regex: '(?:\\.{3}|\\s+\\?)' }, { token: 'keyword.variable', regex: '(?:@+|::|\\.\\.)', next: 'key' }, { token: 'keyword.operator', regex: '\\.\\s*', next: 'key' }, { token: 'string', regex: '\\\\\\S[^\\s,;)}\\]]*' }, { token: 'string.doc', regex: '\'\'\'', next: 'qdoc' }, { token: 'string.doc', regex: '"""', next: 'qqdoc' }, { token: 'string', regex: '\'', next: 'qstring' }, { token: 'string', regex: '"', next: 'qqstring' }, { token: 'string', regex: '`', next: 'js' }, { token: 'string', regex: '<\\[', next: 'words' }, { token: 'string.regex', regex: '//', next: 'heregex' }, { token: 'string.regex', regex: '\\/(?:[^[\\/\\n\\\\]*(?:(?:\\\\.|\\[[^\\]\\n\\\\]*(?:\\\\.[^\\]\\n\\\\]*)*\\])[^[\\/\\n\\\\]*)*)\\/[gimy$]{0,4}', next: 'key' }, { token: 'constant.numeric', regex: '(?:0x[\\da-fA-F][\\da-fA-F_]*|(?:[2-9]|[12]\\d|3[0-6])r[\\da-zA-Z][\\da-zA-Z_]*|(?:\\d[\\d_]*(?:\\.\\d[\\d_]*)?|\\.\\d[\\d_]*)(?:e[+-]?\\d[\\d_]*)?[\\w$]*)' }, { token: 'lparen', regex: '[({[]' }, { token: 'rparen', regex: '[)}\\]]', next: 'key' }, { token: 'keyword.operator', regex: '\\S+' }, { token: 'text', regex: '\\s+' } ], heregex: [ { token: 'string.regex', regex: '.*?//[gimy$?]{0,4}', next: 'start' }, { token: 'string.regex', regex: '\\s*#{' }, { token: 'comment.regex', regex: '\\s+(?:#.*)?' }, { token: 'string.regex', regex: '\\S+' } ], key: [ { token: 'keyword.operator', regex: '[.?@!]+' }, { token: 'identifier', regex: identifier, next: 'start' }, { token: 'text', regex: '', next: 'start' } ], comment: [ { token: 'comment.doc', regex: '.*?\\*/', next: 'start' }, { token: 'comment.doc', regex: '.+' } ], qdoc: [ { token: 'string', regex: ".*?'''", next: 'key' }, stringfill ], qqdoc: [ { token: 'string', regex: '.*?"""', next: 'key' }, stringfill ], qstring: [ { token: 'string', regex: '[^\\\\\']*(?:\\\\.[^\\\\\']*)*\'', next: 'key' }, stringfill ], qqstring: [ { token: 'string', regex: '[^\\\\"]*(?:\\\\.[^\\\\"]*)*"', next: 'key' }, stringfill ], js: [ { token: 'string', regex: '[^\\\\`]*(?:\\\\.[^\\\\`]*)*`', next: 'key' }, stringfill ], words: [ { token: 'string', regex: '.*?\\]>', next: 'key' }, stringfill ] }; for (var idx in Rules) { var r = Rules[idx]; if (r.splice) { for (var i = 0, len = r.length; i < len; ++i) { var rr = r[i]; if (typeof rr.regex === 'string') { Rules[idx][i].regex = new RegExp('^' + rr.regex); } } } else if (typeof rr.regex === 'string') { Rules[idx].regex = new RegExp('^' + r.regex); } } CodeMirror.defineMIME('text/x-livescript', 'livescript'); });
public/js/lib/codemirror/mode/livescript/livescript.js
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/b9372b9af6809b7cdd3bd118d0d0be9eebab231a
[ 0.00017506587028037757, 0.00016966339899227023, 0.0001638971734791994, 0.00017052804469130933, 0.000002986440222230158 ]
{ "id": 3, "code_window": [ " });\n", "};\n", "\n", " story.save(function(err) {\n", " if (err) {\n", " return next(err);\n", " }\n", " res.send(JSON.stringify({\n", " storyLink: story.storyLink.replace(/\\s/g, '-').toLowerCase()\n", " }));\n", " });\n", "};\n", "\n", "exports.commentSubmit = function(req, res, next) {\n", " var data = req.body.data;\n", " if (req.user._id.toString() !== data.author.userId.toString()) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "controllers/story.js", "type": "replace", "edit_start_line_idx": 361 }
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE /** * Tag-closer extension for CodeMirror. * * This extension adds an "autoCloseTags" option that can be set to * either true to get the default behavior, or an object to further * configure its behavior. * * These are supported options: * * `whenClosing` (default true) * Whether to autoclose when the '/' of a closing tag is typed. * `whenOpening` (default true) * Whether to autoclose the tag when the final '>' of an opening * tag is typed. * `dontCloseTags` (default is empty tags for HTML, none for XML) * An array of tag names that should not be autoclosed. * `indentTags` (default is block tags for HTML, none for XML) * An array of tag names that should, when opened, cause a * blank line to be added inside the tag, and the blank line and * closing line to be indented. * * See demos/closetag.html for a usage example. */ (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror"), require("../fold/xml-fold")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../fold/xml-fold"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { CodeMirror.defineOption("autoCloseTags", false, function(cm, val, old) { if (old != CodeMirror.Init && old) cm.removeKeyMap("autoCloseTags"); if (!val) return; var map = {name: "autoCloseTags"}; if (typeof val != "object" || val.whenClosing) map["'/'"] = function(cm) { return autoCloseSlash(cm); }; if (typeof val != "object" || val.whenOpening) map["'>'"] = function(cm) { return autoCloseGT(cm); }; cm.addKeyMap(map); }); var htmlDontClose = ["area", "base", "br", "col", "command", "embed", "hr", "img", "input", "keygen", "link", "meta", "param", "source", "track", "wbr"]; var htmlIndent = ["applet", "blockquote", "body", "button", "div", "dl", "fieldset", "form", "frameset", "h1", "h2", "h3", "h4", "h5", "h6", "head", "html", "iframe", "layer", "legend", "object", "ol", "p", "select", "table", "ul"]; function autoCloseGT(cm) { if (cm.getOption("disableInput")) return CodeMirror.Pass; var ranges = cm.listSelections(), replacements = []; for (var i = 0; i < ranges.length; i++) { if (!ranges[i].empty()) return CodeMirror.Pass; var pos = ranges[i].head, tok = cm.getTokenAt(pos); var inner = CodeMirror.innerMode(cm.getMode(), tok.state), state = inner.state; if (inner.mode.name != "xml" || !state.tagName) return CodeMirror.Pass; var opt = cm.getOption("autoCloseTags"), html = inner.mode.configuration == "html"; var dontCloseTags = (typeof opt == "object" && opt.dontCloseTags) || (html && htmlDontClose); var indentTags = (typeof opt == "object" && opt.indentTags) || (html && htmlIndent); var tagName = state.tagName; if (tok.end > pos.ch) tagName = tagName.slice(0, tagName.length - tok.end + pos.ch); var lowerTagName = tagName.toLowerCase(); // Don't process the '>' at the end of an end-tag or self-closing tag if (!tagName || tok.type == "string" && (tok.end != pos.ch || !/[\"\']/.test(tok.string.charAt(tok.string.length - 1)) || tok.string.length == 1) || tok.type == "tag" && state.type == "closeTag" || tok.string.indexOf("/") == (tok.string.length - 1) || // match something like <someTagName /> dontCloseTags && indexOf(dontCloseTags, lowerTagName) > -1 || closingTagExists(cm, tagName, pos, state, true)) return CodeMirror.Pass; var indent = indentTags && indexOf(indentTags, lowerTagName) > -1; replacements[i] = {indent: indent, text: ">" + (indent ? "\n\n" : "") + "</" + tagName + ">", newPos: indent ? CodeMirror.Pos(pos.line + 1, 0) : CodeMirror.Pos(pos.line, pos.ch + 1)}; } for (var i = ranges.length - 1; i >= 0; i--) { var info = replacements[i]; cm.replaceRange(info.text, ranges[i].head, ranges[i].anchor, "+insert"); var sel = cm.listSelections().slice(0); sel[i] = {head: info.newPos, anchor: info.newPos}; cm.setSelections(sel); if (info.indent) { cm.indentLine(info.newPos.line, null, true); cm.indentLine(info.newPos.line + 1, null, true); } } } function autoCloseSlash(cm) { if (cm.getOption("disableInput")) return CodeMirror.Pass; var ranges = cm.listSelections(), replacements = []; for (var i = 0; i < ranges.length; i++) { if (!ranges[i].empty()) return CodeMirror.Pass; var pos = ranges[i].head, tok = cm.getTokenAt(pos); var inner = CodeMirror.innerMode(cm.getMode(), tok.state), state = inner.state; if (tok.type == "string" || tok.string.charAt(0) != "<" || tok.start != pos.ch - 1) return CodeMirror.Pass; // Kludge to get around the fact that we are not in XML mode // when completing in JS/CSS snippet in htmlmixed mode. Does not // work for other XML embedded languages (there is no general // way to go from a mixed mode to its current XML state). if (inner.mode.name != "xml") { if (cm.getMode().name == "htmlmixed" && inner.mode.name == "javascript") replacements[i] = "/script>"; else if (cm.getMode().name == "htmlmixed" && inner.mode.name == "css") replacements[i] = "/style>"; else return CodeMirror.Pass; } else { if (!state.context || !state.context.tagName || closingTagExists(cm, state.context.tagName, pos, state)) return CodeMirror.Pass; replacements[i] = "/" + state.context.tagName + ">"; } } cm.replaceSelections(replacements); ranges = cm.listSelections(); for (var i = 0; i < ranges.length; i++) if (i == ranges.length - 1 || ranges[i].head.line < ranges[i + 1].head.line) cm.indentLine(ranges[i].head.line); } function indexOf(collection, elt) { if (collection.indexOf) return collection.indexOf(elt); for (var i = 0, e = collection.length; i < e; ++i) if (collection[i] == elt) return i; return -1; } // If xml-fold is loaded, we use its functionality to try and verify // whether a given tag is actually unclosed. function closingTagExists(cm, tagName, pos, state, newTag) { if (!CodeMirror.scanForClosingTag) return false; var end = Math.min(cm.lastLine() + 1, pos.line + 500); var nextClose = CodeMirror.scanForClosingTag(cm, pos, null, end); if (!nextClose || nextClose.tag != tagName) return false; var cx = state.context; // If the immediate wrapping context contains onCx instances of // the same tag, a closing tag only exists if there are at least // that many closing tags of that type following. for (var onCx = newTag ? 1 : 0; cx && cx.tagName == tagName; cx = cx.prev) ++onCx; pos = nextClose.to; for (var i = 1; i < onCx; i++) { var next = CodeMirror.scanForClosingTag(cm, pos, null, end); if (!next || next.tag != tagName) return false; pos = next.to; } return true; } });
public/js/lib/codemirror/addon/edit/closetag.js
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/b9372b9af6809b7cdd3bd118d0d0be9eebab231a
[ 0.0006485831108875573, 0.00020098398090340197, 0.00016234166105277836, 0.00017180587747134268, 0.0001156353609985672 ]
{ "id": 3, "code_window": [ " });\n", "};\n", "\n", " story.save(function(err) {\n", " if (err) {\n", " return next(err);\n", " }\n", " res.send(JSON.stringify({\n", " storyLink: story.storyLink.replace(/\\s/g, '-').toLowerCase()\n", " }));\n", " });\n", "};\n", "\n", "exports.commentSubmit = function(req, res, next) {\n", " var data = req.body.data;\n", " if (req.user._id.toString() !== data.author.userId.toString()) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "controllers/story.js", "type": "replace", "edit_start_line_idx": 361 }
var testcase = require('nodeunit').testCase; var events = require("../../lib/jsdom/level2/events").dom.level2.events; var EventMonitor = function() { self = this; self.atEvents = []; self.bubbledEvents = []; self.capturedEvents = []; self.allEvents = []; self.handleEvent = function(event) { self.allEvents.push(event); switch(event.eventPhase) { case event.CAPTURING_PHASE: self.capturedEvents.push(event); break; case event.AT_TARGET: self.atEvents.push(event); break; case event.BUBBLING_PHASE: self.bubbledEvents.push(event); break; default: throw new events.EventException(0, "Unspecified event phase"); } }; }; var _setUp = function() { var doc = require('./events/files/hc_staff.xml').hc_staff(); var monitor = this.monitor = new EventMonitor(); this.win = doc._parentWindow; this.title = doc.getElementsByTagName("title").item(0); this.body = doc.getElementsByTagName("body").item(0); this.plist = doc.getElementsByTagName("p").item(0); this.event = doc.createEvent("Events"); this._handleEvent = function(type) { return(function(event) { event[type](); monitor.handleEvent(event) }); } } var _tearDown = function(xs) { xs = ['monitor', 'title', 'body', 'plist', 'event', '_handleEvent'].concat(xs ? xs : []); var self = this; xs.forEach(function(x){ self[x] = undefined; delete(self[x]); }) } // A document is created using implementation.createDocument and cast to a DocumentEvent interface. // @author Curt Arnold // @see http://www.w3.org/TR/DOM-Level-2-Events/events#Events-DocumentEvent exports['DocumentEvent interface'] = function (test) { var doc = require('./events/files/hc_staff.xml').hc_staff(); test.ok((doc.createEvent instanceof Function), "should have createEvent function"); test.done(); } // A document is created using implementation.createDocument and cast to a EventTarget interface. // @author Curt Arnold // @see http://www.w3.org/TR/DOM-Level-2-Events/events#Events-EventTarget exports['EventTarget interface'] = function (test) { var doc = require('./events/files/hc_staff.xml').hc_staff(); test.ok((doc instanceof events.EventTarget), 'should be an instance of EventTarget'); test.done(); } // An object implementing the Event interface is created by using DocumentEvent.createEvent method with an eventType // @author Curt Arnold // @see http://www.w3.org/TR/DOM-Level-2-Events/events#Events-DocumentEvent-createEvent exports['create event with each event type'] = function(test){ var doc = require('./events/files/hc_staff.xml').hc_staff(), event_types = {'Events': events.Event, 'MutationEvents': events.MutationEvent, 'UIEvents': events.UIEvent, 'MouseEvents': events.MouseEvent , 'HTMLEvents': events.Event}; test.expect(10); for (var type in event_types) { var event = doc.createEvent(type); test.notEqual(event, null, "should not be null for " + type); test.ok((event instanceof event_types[type]),"should be instanceof " + type); } test.done(); } // @author Curt Arnold // @see http://www.w3.org/TR/DOM-Level-2-Events/events#Events-EventTarget-dispatchEvent // @see http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-17189187 // @see http://www.w3.org/TR/DOM-Level-2-Events/events#xpointer(id('Events-EventTarget-dispatchEvent')/raises/exception[@name='EventException']/descr/p[substring-before(.,':')='UNSPECIFIED_EVENT_TYPE_ERR']) exports['dispatch event'] = testcase({ setUp: function(cb){ this.doc = require('./events/files/hc_staff.xml').hc_staff(); cb(); }, tearDown: function(cb){ _tearDown.call(this, 'doc'); cb(); }, 'a null reference passed to dispatchEvent': function (test) { var doc = this.doc; test.throws(function(){ doc.dispatchEvent(null) }, events.EventException, 'should throw an exception'); // TODO: figure out the best way to test (exception.code == 0) and (exception.message == 'Null event') test.done(); }, 'a created but not initialized event passed to dispatchEvent': function (test) { var doc = this.doc, event_types = ['Events', 'MutationEvents', 'UIEvents', 'MouseEvents', 'HTMLEvents']; test.expect(event_types.length); event_types.forEach(function(type){ test.throws(function(){ doc.dispatchEvent(doc.createEvent(type)) }, events.EventException, 'should throw an exception for ' + type); // Should raise UNSPECIFIED_EVENT_TYPE_ERR EventException. // TODO: figure out the best way to test (exception.code == 0) and (exception.message == 'Uninitialized event') }) test.done(); }, 'an Event initialized with a empty name passed to dispatchEvent': function (test) { var doc = this.doc, event = doc.createEvent("Events"); event.initEvent("",false,false); test.throws(function(){ doc.dispatchEvent(event) }, events.EventException, 'should throw an exception'); // Should raise UNSPECIFIED_EVENT_TYPE_ERR EventException. // TODO: figure out the best way to test (exception.code == 0) and (exception.message == 'Uninitialized event') test.done(); }, // An EventListener registered on the target node with capture false, should receive any event fired on that node. 'EventListener with capture false': function (test) { var monitor = new EventMonitor(); this.doc.addEventListener("foo", monitor.handleEvent, false); var event = this.doc.createEvent("Events"); event.initEvent("foo",true,false); this.doc.dispatchEvent(event); test.expect(3); test.equal(monitor.atEvents.length, 1, 'should receive atEvent'); test.equal(monitor.bubbledEvents.length, 0, 'should not receive at bubble phase'); test.equal(monitor.capturedEvents.length, 0, 'should not receive at capture phase'); test.done(); }, // An event is dispatched to the document with a capture listener attached. // A capturing EventListener will not be triggered by events dispatched directly to the EventTarget upon which it is registered. 'EventListener with capture true': function (test) { var monitor = new EventMonitor(); this.doc.addEventListener("foo", monitor.handleEvent, true); var event = this.doc.createEvent("Events"); event.initEvent("foo",true,false); this.doc.dispatchEvent(event); test.expect(3); test.equal(monitor.atEvents.length, 0, 'should not receive atEvent'); test.equal(monitor.bubbledEvents.length, 0, 'should not receive at bubble phase'); test.equal(monitor.capturedEvents.length, 0, 'should not receive at capture phase'); test.done(); }, // The same monitor is registered twice and an event is dispatched. The monitor should receive only one handleEvent call. 'EventListener is registered twice': function (test) { var monitor = new EventMonitor(); this.doc.addEventListener("foo", monitor.handleEvent, false); this.doc.addEventListener("foo", monitor.handleEvent, false); var event = this.doc.createEvent("Events"); event.initEvent("foo",true,false); this.doc.dispatchEvent(event); test.expect(3); test.equal(monitor.atEvents.length, 1, 'should receive atEvent only once'); test.equal(monitor.bubbledEvents.length, 0, 'should not receive at bubble phase'); test.equal(monitor.capturedEvents.length, 0, 'should not receive at capture phase'); test.done(); }, // The same monitor is registered twice, removed once, and an event is dispatched. The monitor should receive only no handleEvent calls. 'EventListener is registered twice, removed once': function (test) { var monitor = new EventMonitor(); this.doc.addEventListener("foo", monitor.handleEvent, false); this.doc.addEventListener("foo", monitor.handleEvent, false); this.doc.removeEventListener("foo", monitor.handleEvent, false); var event = this.doc.createEvent("Events"); event.initEvent("foo",true,false); this.doc.dispatchEvent(event); test.equal(monitor.allEvents.length, 0, 'should not receive any handleEvent calls'); test.done(); }, // A monitor is added, multiple calls to removeEventListener are made with similar but not identical arguments, and an event is dispatched. // The monitor should receive handleEvent calls. 'EventListener is registered, other listeners (similar but not identical) are removed': function (test) { var monitor = new EventMonitor(); var other = {handleEvent: function(){}} this.doc.addEventListener("foo", monitor.handleEvent, false); this.doc.removeEventListener("foo", monitor.handleEvent, true); this.doc.removeEventListener("food", monitor.handleEvent, false); this.doc.removeEventListener("foo", other.handleEvent, false); var event = this.doc.createEvent("Events"); event.initEvent("foo",true,false); this.doc.dispatchEvent(event); test.equal(monitor.allEvents.length, 1, 'should still receive the handleEvent call'); test.done(); }, // Two listeners are registered on the same target, each of which will remove both itself and the other on the first event. Only one should see the event since event listeners can never be invoked after being removed. 'two EventListeners which both handle by unregistering itself and the other': function (test) { // setup var es = []; var ls = []; var EventListener1 = function() { ls.push(this); } var EventListener2 = function() { ls.push(this); } EventListener1.prototype.handleEvent = function(event) { _handleEvent(event); } EventListener2.prototype.handleEvent = function(event) { _handleEvent(event); } var _handleEvent = function(event) { es.push(event); ls.forEach(function(l){ event.currentTarget.removeEventListener("foo", l.handleEvent, false); }) } // test var listener1 = new EventListener1(); var listener2 = new EventListener2(); this.doc.addEventListener("foo", listener1.handleEvent, false); this.doc.addEventListener("foo", listener2.handleEvent, false); var event = this.doc.createEvent("Events"); event.initEvent("foo",true,false); this.doc.dispatchEvent(event); test.equal(es.length, 1, 'should only be handled by one EventListener'); test.done(); } }) // The Event.initEvent method is called for event returned by DocumentEvent.createEvent("Events") and DocumentEvent.createEvent("MutationEvents") // The state is checked to see if it reflects the parameters. // @author Curt Arnold // @see http://www.w3.org/TR/DOM-Level-2-Events/events#Events-Event-initEvent exports['init event'] = testcase({ setUp: function(cb){ var doc = require('./events/files/hc_staff.xml').hc_staff(); this._events = ['Events', 'MutationEvents'].map(function(t){ return(doc.createEvent(t)); }) cb(); }, tearDown: function(cb){ _tearDown.call(this, '_events'); cb(); }, 'set state from params, bubble no cancel': function (test) { test.expect(8); this._events.forEach(function(event){ test.notEqual(event, null, 'event should not be null for ' + event.eventType); event.initEvent('rotate', true, false); test.equal(event.type, 'rotate', 'event type should be \"rotate\" for ' + event.eventType); test.equal(event.bubbles, true, 'event should bubble for ' + event.eventType); test.equal(event.cancelable, false, 'event should not be cancelable for ' + event.eventType); }) test.done(); }, 'set state from params, cancel no bubble': function (test) { test.expect(8); this._events.forEach(function(event){ test.notEqual(event, null, 'event should not be null for' + event.eventType); event.initEvent('rotate', false, true); test.equal(event.type, 'rotate', 'event type should be \"rotate\" for ' + event.eventType); test.equal(event.bubbles, false, 'event should not bubble for ' + event.eventType); test.equal(event.cancelable, true, 'event should be cancelable for ' + event.eventType); }) test.done(); }, 'initEvent called multiple times, final time is definitive': function (test) { test.expect(14); this._events.forEach(function(event){ test.notEqual(event, null, 'event should not be null for ' + event.eventType); // rotate event.initEvent("rotate", true, true); test.equal(event.type, 'rotate', 'event type should be \"rotate\" for ' + event.eventType); test.equal(event.bubbles, true, 'event should bubble for ' + event.eventType); test.equal(event.cancelable, true, 'event should be cancelable for ' + event.eventType); // shear event.initEvent("shear", false, false); test.equal(event.type, 'shear', 'event type should be \"shear\" for ' + event.eventType); test.equal(event.bubbles, false, 'event should not bubble for ' + event.eventType); test.equal(event.cancelable, false, 'event should not be cancelable for ' + event.eventType); }) test.done(); }, }) exports['capture event'] = testcase({ setUp: function(cb){ _setUp.call(this); this.event.initEvent("foo",true,false); cb(); }, tearDown: function(cb){ _tearDown.call(this); cb(); }, 'all capturing listeners in a direct line from dispatched node will receive the event': function(test) { this.plist.addEventListener("foo", this.monitor.handleEvent, true); this.plist.firstChild.addEventListener("foo", this.monitor.handleEvent, false); this.plist.firstChild.dispatchEvent(this.event); test.expect(3); test.equal(this.monitor.atEvents.length, 1, 'should be at 1 event'); test.equal(this.monitor.bubbledEvents.length, 0, 'should not have any bubbled events'); test.equal(this.monitor.capturedEvents.length, 1, 'should have captured 1 event'); test.done(); }, 'only capture listeners in a direct line from target to the document node should receive the event': function(test) { var self = this; this.title.addEventListener("foo", this.monitor.handleEvent, true); this.plist.addEventListener("foo", function(event) { event.preventDefault(); self.monitor.handleEvent(event) }, false); this.plist.firstChild.addEventListener("foo", this.monitor.handleEvent, false); var return_val = this.plist.firstChild.dispatchEvent(this.event); test.expect(4); test.equal(return_val, false, 'dispatchEvent should return *false*'); test.equal(this.monitor.atEvents.length, 1, 'should be at 1 event'); test.equal(this.monitor.bubbledEvents.length, 1, 'should have bubbled 1 event'); test.equal(this.monitor.capturedEvents.length, 0, 'should not have captured any events'); test.done(); } }) exports['bubble event'] = testcase({ setUp: function(cb){ _setUp.call(this); this.event.initEvent("foo",true,false); cb(); }, tearDown: function(cb){ _tearDown.call(this); cb(); }, 'all non-capturing listeners in a direct line from dispatched node will receive a bubbling event': function(test) { this.win.addEventListener("foo", this.monitor.handleEvent, false); this.plist.addEventListener("foo", this.monitor.handleEvent, false); this.plist.firstChild.addEventListener("foo", this.monitor.handleEvent, false); this.plist.firstChild.dispatchEvent(this.event); test.expect(3); test.equal(this.monitor.atEvents.length, 1, 'should be at 1 event'); test.equal(this.monitor.bubbledEvents.length, 2, 'should have 2 bubbled events'); test.equal(this.monitor.capturedEvents.length, 0, 'should not have any captured events'); test.done(); }, 'only bubble listeners in a direct line from target to the document node should receive the event': function(test) { this.win.addEventListener("foo", this.monitor.handleEvent, false); this.title.addEventListener("foo", this.monitor.handleEvent, false); this.plist.addEventListener("foo", this._handleEvent('preventDefault'), true); this.plist.firstChild.addEventListener("foo", this.monitor.handleEvent, false); var return_val = this.plist.firstChild.dispatchEvent(this.event); test.expect(4); test.equal(return_val, false, 'dispatchEvent should return *false*'); test.equal(this.monitor.atEvents.length, 1, 'should be at 1 event'); test.equal(this.monitor.bubbledEvents.length, 1, 'should have 1 bubbled event'); test.equal(this.monitor.capturedEvents.length, 1, 'should have captured 1 event'); test.done(); }, 'if an event does not bubble, bubble listeners should not receive the event': function(test) { this.win.addEventListener("foo", this.monitor.handleEvent, false); this.body.addEventListener("foo", this.monitor.handleEvent, true); this.plist.addEventListener("foo", this._handleEvent('preventDefault'), false); this.plist.firstChild.addEventListener("foo", this.monitor.handleEvent, false); this.event.initEvent("foo",false,false); var return_val = this.plist.firstChild.dispatchEvent(this.event); test.expect(4); test.equal(return_val, false, 'dispatchEvent should return *false*'); test.equal(this.monitor.atEvents.length, 1, 'should be at 1 event'); test.equal(this.monitor.bubbledEvents.length, 0, 'should not have any bubbled events'); test.equal(this.monitor.capturedEvents.length, 1, 'should have captured 1 event'); test.done(); } }) exports['stop propagation'] = testcase({ setUp: function(cb){ _setUp.call(this); this.event.initEvent("foo",true,false); cb(); }, tearDown: function(cb){ _tearDown.call(this); cb(); }, 'should prevent the target from receiving the event': function(test) { this.win.addEventListener("foo", this.monitor.handleEvent, false); this.plist.addEventListener("foo", this._handleEvent('stopPropagation'), true); this.plist.firstChild.addEventListener("foo", this.monitor.handleEvent, false); this.plist.firstChild.dispatchEvent(this.event); test.expect(3); test.equal(this.monitor.atEvents.length, 0, 'should be at 0 events'); test.equal(this.monitor.bubbledEvents.length, 0, 'should have no bubbled events'); test.equal(this.monitor.capturedEvents.length, 1, 'should have 1 captured event'); test.done(); }, 'should prevent all listeners from receiving the event': function(test) { this.win.addEventListener("foo", this.monitor.handleEvent, false); this.body.addEventListener("foo", this.monitor.handleEvent, false); this.plist.addEventListener("foo", this._handleEvent('stopPropagation'), false); this.plist.firstChild.addEventListener("foo", this.monitor.handleEvent, false); this.plist.firstChild.dispatchEvent(this.event); test.expect(3); test.equal(this.monitor.atEvents.length, 1, 'should be at 1 event'); test.equal(this.monitor.bubbledEvents.length, 1, 'should have 1 bubbled event'); test.equal(this.monitor.capturedEvents.length, 0, 'should have no captured events'); test.done(); } }) exports['prevent default'] = testcase({ setUp: function(cb){ _setUp.call(this); this.event.initEvent("foo",true,true); cb(); }, tearDown: function(cb){ _tearDown.call(this); cb(); }, 'a cancelable event can have its default event disabled': function(test) { this.body.addEventListener("foo", this.monitor.handleEvent, true); this.plist.addEventListener("foo", this._handleEvent('preventDefault'), false); this.plist.firstChild.addEventListener("foo", this.monitor.handleEvent, false); var return_val = this.plist.firstChild.dispatchEvent(this.event); test.expect(4); test.equal(return_val, true, 'dispatchEvent should return *true*'); test.equal(this.monitor.atEvents.length, 1, 'should be at 1 event'); test.equal(this.monitor.bubbledEvents.length, 1, 'should have bubbled 1 event'); test.equal(this.monitor.capturedEvents.length, 1, 'should have captured 1 event'); test.done(); }, 'a non-cancelable event cannot have its default event disabled': function(test) { this.body.addEventListener("foo", this.monitor.handleEvent, true); this.plist.addEventListener("foo", this._handleEvent('preventDefault'), false); this.plist.firstChild.addEventListener("foo", this.monitor.handleEvent, false); this.event.initEvent("foo",true,false); var return_val = this.plist.firstChild.dispatchEvent(this.event); test.expect(4); test.equal(return_val, false, 'dispatchEvent should return *false*'); test.equal(this.monitor.atEvents.length, 1, 'should be at 1 event'); test.equal(this.monitor.bubbledEvents.length, 1, 'should have bubbled 1 event'); test.equal(this.monitor.capturedEvents.length, 1, 'should have captured 1 event'); test.done(); } })
bower_components/jsdom/test/level2/events.js
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/b9372b9af6809b7cdd3bd118d0d0be9eebab231a
[ 0.00017638418648857623, 0.0001706877228571102, 0.0001626876910449937, 0.00017164958990179002, 0.0000035960840705229202 ]
{ "id": 4, "code_window": [ " return gulp.src(['public/js/lib/**/*'])\n", " .pipe(eslint())\n", " .pipe(eslint.format());\n", "});\n", "\n", "gulp.task('default', ['lint', 'serve', 'sync']);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace" ], "after_edit": [ "gulp.task('default', ['serve', 'sync']);" ], "file_path": "gulpfile.js", "type": "replace", "edit_start_line_idx": 70 }
if (process.env.NODE_ENV !== 'development') { require('newrelic'); } require('dotenv').load(); // handle uncaught exceptions. Forever will restart process on shutdown process.on('uncaughtException', function (err) { console.error( (new Date()).toUTCString() + ' uncaughtException:', err.message ); console.error(err.stack); /* eslint-disable no-process-exit */ process.exit(1); /* eslint-enable no-process-exit */ }); var express = require('express'), accepts = require('accepts'), cookieParser = require('cookie-parser'), compress = require('compression'), session = require('express-session'), logger = require('morgan'), errorHandler = require('errorhandler'), methodOverride = require('method-override'), bodyParser = require('body-parser'), helmet = require('helmet'), MongoStore = require('connect-mongo')(session), flash = require('express-flash'), path = require('path'), mongoose = require('mongoose'), passport = require('passport'), expressValidator = require('express-validator'), connectAssets = require('connect-assets'), request = require('request'), /** * Controllers (route handlers). */ homeController = require('./controllers/home'), resourcesController = require('./controllers/resources'), userController = require('./controllers/user'), contactController = require('./controllers/contact'), nonprofitController = require('./controllers/nonprofits'), bonfireController = require('./controllers/bonfire'), coursewareController = require('./controllers/courseware'), fieldGuideController = require('./controllers/fieldGuide'), challengeMapController = require('./controllers/challengeMap'), /** * Stories */ storyController = require('./controllers/story'); /** * API keys and Passport configuration. */ secrets = require('./config/secrets'), passportConf = require('./config/passport'); /** * Create Express server. */ var app = express(); /** * Connect to MongoDB. */ mongoose.connect(secrets.db); mongoose.connection.on('error', function () { console.error( 'MongoDB Connection Error. Please make sure that MongoDB is running.' ); }); /** * Express configuration. */ app.set('port', process.env.PORT || 3000); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); app.use(compress()); var oneYear = 31557600000; app.use(express.static(__dirname + '/public', {maxAge: oneYear})); app.use(connectAssets({ paths: [ path.join(__dirname, 'public/css'), path.join(__dirname, 'public/js') ], helperContext: app.locals })); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: true})); app.use(expressValidator({ customValidators: { matchRegex: function (param, regex) { return regex.test(param); } } })); app.use(methodOverride()); app.use(cookieParser()); app.use(session({ resave: true, saveUninitialized: true, secret: secrets.sessionSecret, store: new MongoStore({ url: secrets.db, 'auto_reconnect': true }) })); app.use(passport.initialize()); app.use(passport.session()); app.use(flash()); app.disable('x-powered-by'); app.use(helmet.xssFilter()); app.use(helmet.noSniff()); app.use(helmet.xframe()); app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }); var trusted = [ "'self'", '*.freecodecamp.com', '*.gstatic.com', '*.google-analytics.com', '*.googleapis.com', '*.google.com', '*.gstatic.com', '*.doubleclick.net', '*.twitter.com', '*.twitch.tv', '*.twimg.com', "'unsafe-eval'", "'unsafe-inline'", '*.rafflecopter.com', '*.bootstrapcdn.com', '*.cloudflare.com', 'https://*.cloudflare.com', 'localhost:3001', 'ws://localhost:3001/', 'http://localhost:3001', 'localhost:3000', 'ws://localhost:3000/', 'http://localhost:3000', '*.ionicframework.com', 'https://syndication.twitter.com', '*.youtube.com', '*.jsdelivr.net', 'https://*.jsdelivr.net', '*.togetherjs.com', 'https://*.togetherjs.com', 'wss://hub.togetherjs.com', '*.ytimg.com', 'wss://fcctogether.herokuapp.com', '*.bitly.com', 'http://cdn.inspectlet.com/', 'http://hn.inspectlet.com/' ]; app.use(helmet.contentSecurityPolicy({ defaultSrc: trusted, scriptSrc: [ '*.optimizely.com', '*.aspnetcdn.com', '*.d3js.org', ].concat(trusted), 'connect-src': [ 'ws://*.rafflecopter.com', 'wss://*.rafflecopter.com', 'https://*.rafflecopter.com', 'ws://www.freecodecamp.com', 'http://www.freecodecamp.com' ].concat(trusted), styleSrc: trusted, imgSrc: [ '*.evernote.com', '*.amazonaws.com', 'data:', '*.licdn.com', '*.gravatar.com', '*.akamaihd.net', 'graph.facebook.com', '*.githubusercontent.com', '*.googleusercontent.com', '*' /* allow all input since we have user submitted images for public profile*/ ].concat(trusted), fontSrc: ['*.googleapis.com'].concat(trusted), mediaSrc: [ '*.amazonaws.com', '*.twitter.com' ].concat(trusted), frameSrc: [ '*.gitter.im', '*.gitter.im https:', '*.vimeo.com', '*.twitter.com', '*.rafflecopter.com', '*.ghbtns.com' ].concat(trusted), reportOnly: false, // set to true if you only want to report errors setAllHeaders: false, // set to true if you want to set all headers safari5: false // set to true if you want to force buggy CSP in Safari 5 })); app.use(function (req, res, next) { // Make user object available in templates. res.locals.user = req.user; next(); }); app.use(function (req, res, next) { // Remember original destination before login. var path = req.path.split('/')[1]; if (/auth|login|logout|signin|signup|fonts|favicon/i.test(path)) { return next(); } else if (/\/stories\/comments\/\w+/i.test(req.path)) { return next(); } req.session.returnTo = req.path; next(); }); app.use( express.static(path.join(__dirname, 'public'), {maxAge: 31557600000}) ); app.use(express.static(__dirname + '/public', { maxAge: 86400000 })); /** * Main routes. */ app.get('/', homeController.index); app.get('/privacy', function(req, res) { res.redirect(301, "/field-guide/free-code-camp's-privacy-policy"); }); app.get('/nonprofit-project-instructions', function(req, res) { res.redirect(301, "/field-guide/free-code-camp's-privacy-policy"); }); app.get('/chat', resourcesController.chat); app.get('/twitch', resourcesController.twitch); app.get('/map', challengeMapController.challengeMap); app.get('/live-pair-programming', function(req, res) { res.redirect(301, '/field-guide/live-stream-pair-programming-on-twitch.tv'); }); app.get('/install-screenhero', function(req, res) { res.redirect(301, '/field-guide/install-screenhero'); }); app.get('/guide-to-our-nonprofit-projects', function(req, res) { res.redirect(301, '/field-guide/a-guide-to-our-nonprofit-projects'); }); app.get('/chromebook', function(req, res) { res.redirect(301, '/field-guide/chromebook'); }); app.get('/deploy-a-website', function(req, res) { res.redirect(301, '/field-guide/deploy-a-website'); }); app.get('/gmail-shortcuts', function(req, res) { res.redirect(301, '/field-guide/gmail-shortcuts'); }); app.get('/nodeschool-challenges', function(req, res) { res.redirect(301, '/field-guide/nodeschool-challenges'); }); app.get('/news', function(req, res) { res.redirect(301, '/stories/hot'); }); app.get('/learn-to-code', resourcesController.about); app.get('/about', function(req, res) { res.redirect(301, '/learn-to-code'); }); app.get('/signin', userController.getSignin); app.get('/login', function(req, res) { res.redirect(301, '/signin'); }); app.post('/signin', userController.postSignin); app.get('/signout', userController.signout); app.get('/logout', function(req, res) { res.redirect(301, '/signout'); }); app.get('/forgot', userController.getForgot); app.post('/forgot', userController.postForgot); app.get('/reset/:token', userController.getReset); app.post('/reset/:token', userController.postReset); app.get('/email-signup', userController.getEmailSignup); app.get('/email-signin', userController.getEmailSignin); app.post('/email-signup', userController.postEmailSignup); app.post('/email-signin', userController.postSignin); app.get('/nonprofits', contactController.getNonprofitsForm); app.post('/nonprofits', contactController.postNonprofitsForm); /** * Nonprofit Project routes. */ app.get('/nonprofits', nonprofitController.nonprofitsHome); app.get('/nonprofits/directory', nonprofitController.nonprofitsDirectory); app.get('/nonprofits/are-you-with-a-registered-nonprofit', nonprofitController.areYouWithARegisteredNonprofit); app.get('/nonprofits/are-there-people-that-are-already-benefiting-from-your-services', nonprofitController.areTherePeopleThatAreAlreadyBenefitingFromYourServices); app.get('/nonprofits/in-exchange-we-ask', nonprofitController.inExchangeWeAsk); app.get('/nonprofits/ok-with-javascript', nonprofitController.okWithJavaScript); app.get('/nonprofits/how-can-free-code-camp-help-you', nonprofitController.howCanFreeCodeCampHelpYou); app.get('/nonprofits/what-does-your-nonprofit-do', nonprofitController.whatDoesYourNonprofitDo); app.get('/nonprofits/link-us-to-your-website', nonprofitController.linkUsToYourWebsite); app.get('/nonprofits/tell-us-your-name', nonprofitController.tellUsYourName); app.get('/nonprofits/tell-us-your-email', nonprofitController.tellUsYourEmail); app.get('/nonprofits/your-nonprofit-project-application-has-been-submitted', nonprofitController.yourNonprofitProjectApplicationHasBeenSubmitted); app.get('/nonprofits/other-solutions', nonprofitController.otherSolutions); app.get('/nonprofits/getNonprofitList', nonprofitController.showAllNonprofits); app.get('/nonprofits/interested-in-nonprofit/:nonprofitName', nonprofitController.interestedInNonprofit); app.get( '/nonprofits/:nonprofitName', nonprofitController.returnIndividualNonprofit ); app.get( '/done-with-first-100-hours', passportConf.isAuthenticated, contactController.getDoneWithFirst100Hours ); app.post( '/done-with-first-100-hours', passportConf.isAuthenticated, contactController.postDoneWithFirst100Hours ); app.get( '/nonprofit-project-instructions', passportConf.isAuthenticated, resourcesController.nonprofitProjectInstructions ); app.post( '/update-progress', passportConf.isAuthenticated, userController.updateProgress ); app.get('/api/slack', function(req, res) { if (req.user) { if (req.user.email) { var invite = { 'email': req.user.email, 'token': process.env.SLACK_KEY, 'set_active': true }; var headers = { 'User-Agent': 'Node Browser/0.0.1', 'Content-Type': 'application/x-www-form-urlencoded' }; var options = { url: 'https://freecode.slack.com/api/users.admin.invite', method: 'POST', headers: headers, form: invite }; request(options, function (error, response, body) { if (!error && response.statusCode === 200) { req.flash('success', { msg: "We've successfully requested an invite for you. Please check your email and follow the instructions from Slack." }); req.user.sentSlackInvite = true; req.user.save(function(err, user) { if (err) { next(err); } return res.redirect('back'); }); } else { req.flash('errors', { msg: "The invitation email did not go through for some reason. Please try again or <a href='mailto:[email protected]?subject=slack%20invite%20failed%20to%20send>email us</a>." }); return res.redirect('back'); } }) } else { req.flash('notice', { msg: "Before we can send your Slack invite, we need your email address. Please update your profile information here." }); return res.redirect('/account'); } } else { req.flash('notice', { msg: "You need to sign in to Free Code Camp before we can send you a Slack invite." }); return res.redirect('/account'); } }); /** * Camper News routes. */ app.get( '/stories/hotStories', storyController.hotJSON ); app.get( '/stories/recentStories', storyController.recentJSON ); app.get( '/stories/', function(req, res) { res.redirect(302, '/stories/hot'); } ); app.get( '/stories/comments/:id', storyController.comments ); app.post( '/stories/comment/', storyController.commentSubmit ); app.post( '/stories/comment/:id/comment', storyController.commentOnCommentSubmit ); app.get( '/stories/submit', storyController.submitNew ); app.get( '/stories/submit/new-story', storyController.preSubmit ); app.post( '/stories/preliminary', storyController.newStory ); app.post( '/stories/', storyController.storySubmission ); app.get( '/stories/hot', storyController.hot ); app.get( '/stories/recent', storyController.recent ); app.get( '/stories/search', storyController.search ); app.post( '/stories/search', storyController.getStories ); app.get( '/stories/:storyName', storyController.returnIndividualStory ); app.post( '/stories/upvote/', storyController.upvote ); /** * Challenge related routes */ app.get( '/challenges/', challengesController.returnNextChallenge ); app.get( '/challenges/:challengeNumber', challengesController.returnChallenge ); app.all('/account', passportConf.isAuthenticated); app.get('/account/api', userController.getAccountAngular); /** * API routes */ app.get('/api/github', resourcesController.githubCalls); app.get('/api/blogger', resourcesController.bloggerCalls); app.get('/api/trello', resourcesController.trelloCalls); /** * Bonfire related routes */ app.get('/field-guide/getFieldGuideList', fieldGuideController.showAllFieldGuides); app.get('/playground', bonfireController.index); app.get('/bonfires', bonfireController.returnNextBonfire); app.get('/bonfire-json-generator', bonfireController.returnGenerator); app.post('/bonfire-json-generator', bonfireController.generateChallenge); app.get('/bonfire-challenge-generator', bonfireController.publicGenerator); app.post('/bonfire-challenge-generator', bonfireController.testBonfire); app.get( '/bonfires/:bonfireName', bonfireController.returnIndividualBonfire ); app.get('/bonfire', function(req, res) { res.redirect(301, '/playground'); }); app.post('/completed-bonfire/', bonfireController.completedBonfire); /** * Field Guide related routes */ app.get('/field-guide/:fieldGuideName', fieldGuideController.returnIndividualFieldGuide); app.get('/field-guide', fieldGuideController.returnNextFieldGuide); app.post('/completed-field-guide/', fieldGuideController.completedFieldGuide); /** * Courseware related routes */ app.get('/challenges/', coursewareController.returnNextCourseware); app.get( '/challenges/:coursewareName', coursewareController.returnIndividualCourseware ); app.post('/completed-courseware/', coursewareController.completedCourseware); app.post('/completed-zipline-or-basejump', coursewareController.completedZiplineOrBasejump); // Unique Check API route app.get('/api/checkUniqueUsername/:username', userController.checkUniqueUsername); app.get('/api/checkExistingUsername/:username', userController.checkExistingUsername); app.get('/api/checkUniqueEmail/:email', userController.checkUniqueEmail); app.get('/account', userController.getAccount); app.post('/account/profile', userController.postUpdateProfile); app.post('/account/password', userController.postUpdatePassword); app.post('/account/delete', userController.postDeleteAccount); app.get('/account/unlink/:provider', userController.getOauthUnlink); app.get('/sitemap.xml', resourcesController.sitemap); /** * OAuth sign-in routes. */ var passportOptions = { successRedirect: '/', failureRedirect: '/login' }; app.get('/auth/twitter', passport.authenticate('twitter')); app.get( '/auth/twitter/callback', passport.authenticate('twitter', { successRedirect: '/', failureRedirect: '/login' }) ); app.get( '/auth/linkedin', passport.authenticate('linkedin', { state: 'SOME STATE' }) ); app.get( '/auth/linkedin/callback', passport.authenticate('linkedin', passportOptions) ); app.get( '/auth/facebook', passport.authenticate('facebook', {scope: ['email', 'user_location']}) ); app.get( '/auth/facebook/callback', passport.authenticate('facebook', passportOptions), function (req, res) { res.redirect(req.session.returnTo || '/'); } ); app.get('/auth/github', passport.authenticate('github')); app.get( '/auth/github/callback', passport.authenticate('github', passportOptions), function (req, res) { res.redirect(req.session.returnTo || '/'); } ); app.get( '/auth/google', passport.authenticate('google', {scope: 'profile email'}) ); app.get( '/auth/google/callback', passport.authenticate('google', passportOptions), function (req, res) { res.redirect(req.session.returnTo || '/'); } ); app.get('/induce-vomiting', function(req, res, next) { next(new Error('vomiting induced')); }); // put this route last app.get( '/:username', userController.returnUser ); /** * 500 Error Handler. */ if (process.env.NODE_ENV === 'development') { app.use(errorHandler({ log: true })); } else { // error handling in production app.use(function(err, req, res, next) { // respect err.status if (err.status) { res.statusCode = err.status; } // default status code to 500 if (res.statusCode < 400) { res.statusCode = 500; } // parse res type var accept = accepts(req); var type = accept.type('html', 'json', 'text'); var message = 'opps! Something went wrong. Please try again later'; if (type === 'html') { req.flash('errors', { msg: message }); return res.redirect('/'); // json } else if (type === 'json') { res.setHeader('Content-Type', 'application/json'); return res.send({ message: message }); // plain text } else { res.setHeader('Content-Type', 'text/plain'); return res.send(message); } }); } /** * Start Express server. */ app.listen(app.get('port'), function () { console.log( 'FreeCodeCamp server listening on port %d in %s mode', app.get('port'), app.get('env') ); }); module.exports = app;
app.js
1
https://github.com/freeCodeCamp/freeCodeCamp/commit/b9372b9af6809b7cdd3bd118d0d0be9eebab231a
[ 0.000178980510099791, 0.00017320741608273238, 0.0001624691067263484, 0.0001734403776936233, 0.0000032432865282316925 ]
{ "id": 4, "code_window": [ " return gulp.src(['public/js/lib/**/*'])\n", " .pipe(eslint())\n", " .pipe(eslint.format());\n", "});\n", "\n", "gulp.task('default', ['lint', 'serve', 'sync']);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace" ], "after_edit": [ "gulp.task('default', ['serve', 'sync']);" ], "file_path": "gulpfile.js", "type": "replace", "edit_start_line_idx": 70 }
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; var HINT_ELEMENT_CLASS = "CodeMirror-hint"; var ACTIVE_HINT_ELEMENT_CLASS = "CodeMirror-hint-active"; // This is the old interface, kept around for now to stay // backwards-compatible. CodeMirror.showHint = function(cm, getHints, options) { if (!getHints) return cm.showHint(options); if (options && options.async) getHints.async = true; var newOpts = {hint: getHints}; if (options) for (var prop in options) newOpts[prop] = options[prop]; return cm.showHint(newOpts); }; CodeMirror.defineExtension("showHint", function(options) { // We want a single cursor position. if (this.listSelections().length > 1 || this.somethingSelected()) return; if (this.state.completionActive) this.state.completionActive.close(); var completion = this.state.completionActive = new Completion(this, options); var getHints = completion.options.hint; if (!getHints) return; CodeMirror.signal(this, "startCompletion", this); if (getHints.async) getHints(this, function(hints) { completion.showHints(hints); }, completion.options); else return completion.showHints(getHints(this, completion.options)); }); function Completion(cm, options) { this.cm = cm; this.options = this.buildOptions(options); this.widget = this.onClose = null; } Completion.prototype = { close: function() { if (!this.active()) return; this.cm.state.completionActive = null; if (this.widget) this.widget.close(); if (this.onClose) this.onClose(); CodeMirror.signal(this.cm, "endCompletion", this.cm); }, active: function() { return this.cm.state.completionActive == this; }, pick: function(data, i) { var completion = data.list[i]; if (completion.hint) completion.hint(this.cm, data, completion); else this.cm.replaceRange(getText(completion), completion.from || data.from, completion.to || data.to, "complete"); CodeMirror.signal(data, "pick", completion); this.close(); }, showHints: function(data) { if (!data || !data.list.length || !this.active()) return this.close(); if (this.options.completeSingle && data.list.length == 1) this.pick(data, 0); else this.showWidget(data); }, showWidget: function(data) { this.widget = new Widget(this, data); CodeMirror.signal(data, "shown"); var debounce = 0, completion = this, finished; var closeOn = this.options.closeCharacters; var startPos = this.cm.getCursor(), startLen = this.cm.getLine(startPos.line).length; var requestAnimationFrame = window.requestAnimationFrame || function(fn) { return setTimeout(fn, 1000/60); }; var cancelAnimationFrame = window.cancelAnimationFrame || clearTimeout; function done() { if (finished) return; finished = true; completion.close(); completion.cm.off("cursorActivity", activity); if (data) CodeMirror.signal(data, "close"); } function update() { if (finished) return; CodeMirror.signal(data, "update"); var getHints = completion.options.hint; if (getHints.async) getHints(completion.cm, finishUpdate, completion.options); else finishUpdate(getHints(completion.cm, completion.options)); } function finishUpdate(data_) { data = data_; if (finished) return; if (!data || !data.list.length) return done(); if (completion.widget) completion.widget.close(); completion.widget = new Widget(completion, data); } function clearDebounce() { if (debounce) { cancelAnimationFrame(debounce); debounce = 0; } } function activity() { clearDebounce(); var pos = completion.cm.getCursor(), line = completion.cm.getLine(pos.line); if (pos.line != startPos.line || line.length - pos.ch != startLen - startPos.ch || pos.ch < startPos.ch || completion.cm.somethingSelected() || (pos.ch && closeOn.test(line.charAt(pos.ch - 1)))) { completion.close(); } else { debounce = requestAnimationFrame(update); if (completion.widget) completion.widget.close(); } } this.cm.on("cursorActivity", activity); this.onClose = done; }, buildOptions: function(options) { var editor = this.cm.options.hintOptions; var out = {}; for (var prop in defaultOptions) out[prop] = defaultOptions[prop]; if (editor) for (var prop in editor) if (editor[prop] !== undefined) out[prop] = editor[prop]; if (options) for (var prop in options) if (options[prop] !== undefined) out[prop] = options[prop]; return out; } }; function getText(completion) { if (typeof completion == "string") return completion; else return completion.text; } function buildKeyMap(completion, handle) { var baseMap = { Up: function() {handle.moveFocus(-1);}, Down: function() {handle.moveFocus(1);}, PageUp: function() {handle.moveFocus(-handle.menuSize() + 1, true);}, PageDown: function() {handle.moveFocus(handle.menuSize() - 1, true);}, Home: function() {handle.setFocus(0);}, End: function() {handle.setFocus(handle.length - 1);}, Enter: handle.pick, Tab: handle.pick, Esc: handle.close }; var custom = completion.options.customKeys; var ourMap = custom ? {} : baseMap; function addBinding(key, val) { var bound; if (typeof val != "string") bound = function(cm) { return val(cm, handle); }; // This mechanism is deprecated else if (baseMap.hasOwnProperty(val)) bound = baseMap[val]; else bound = val; ourMap[key] = bound; } if (custom) for (var key in custom) if (custom.hasOwnProperty(key)) addBinding(key, custom[key]); var extra = completion.options.extraKeys; if (extra) for (var key in extra) if (extra.hasOwnProperty(key)) addBinding(key, extra[key]); return ourMap; } function getHintElement(hintsElement, el) { while (el && el != hintsElement) { if (el.nodeName.toUpperCase() === "LI" && el.parentNode == hintsElement) return el; el = el.parentNode; } } function Widget(completion, data) { this.completion = completion; this.data = data; var widget = this, cm = completion.cm; var hints = this.hints = document.createElement("ul"); hints.className = "CodeMirror-hints"; this.selectedHint = data.selectedHint || 0; var completions = data.list; for (var i = 0; i < completions.length; ++i) { var elt = hints.appendChild(document.createElement("li")), cur = completions[i]; var className = HINT_ELEMENT_CLASS + (i != this.selectedHint ? "" : " " + ACTIVE_HINT_ELEMENT_CLASS); if (cur.className != null) className = cur.className + " " + className; elt.className = className; if (cur.render) cur.render(elt, data, cur); else elt.appendChild(document.createTextNode(cur.displayText || getText(cur))); elt.hintId = i; } var pos = cm.cursorCoords(completion.options.alignWithWord ? data.from : null); var left = pos.left, top = pos.bottom, below = true; hints.style.left = left + "px"; hints.style.top = top + "px"; // If we're at the edge of the screen, then we want the menu to appear on the left of the cursor. var winW = window.innerWidth || Math.max(document.body.offsetWidth, document.documentElement.offsetWidth); var winH = window.innerHeight || Math.max(document.body.offsetHeight, document.documentElement.offsetHeight); (completion.options.container || document.body).appendChild(hints); var box = hints.getBoundingClientRect(), overlapY = box.bottom - winH; if (overlapY > 0) { var height = box.bottom - box.top, curTop = pos.top - (pos.bottom - box.top); if (curTop - height > 0) { // Fits above cursor hints.style.top = (top = pos.top - height) + "px"; below = false; } else if (height > winH) { hints.style.height = (winH - 5) + "px"; hints.style.top = (top = pos.bottom - box.top) + "px"; var cursor = cm.getCursor(); if (data.from.ch != cursor.ch) { pos = cm.cursorCoords(cursor); hints.style.left = (left = pos.left) + "px"; box = hints.getBoundingClientRect(); } } } var overlapX = box.right - winW; if (overlapX > 0) { if (box.right - box.left > winW) { hints.style.width = (winW - 5) + "px"; overlapX -= (box.right - box.left) - winW; } hints.style.left = (left = pos.left - overlapX) + "px"; } cm.addKeyMap(this.keyMap = buildKeyMap(completion, { moveFocus: function(n, avoidWrap) { widget.changeActive(widget.selectedHint + n, avoidWrap); }, setFocus: function(n) { widget.changeActive(n); }, menuSize: function() { return widget.screenAmount(); }, length: completions.length, close: function() { completion.close(); }, pick: function() { widget.pick(); }, data: data })); if (completion.options.closeOnUnfocus) { var closingOnBlur; cm.on("blur", this.onBlur = function() { closingOnBlur = setTimeout(function() { completion.close(); }, 100); }); cm.on("focus", this.onFocus = function() { clearTimeout(closingOnBlur); }); } var startScroll = cm.getScrollInfo(); cm.on("scroll", this.onScroll = function() { var curScroll = cm.getScrollInfo(), editor = cm.getWrapperElement().getBoundingClientRect(); var newTop = top + startScroll.top - curScroll.top; var point = newTop - (window.pageYOffset || (document.documentElement || document.body).scrollTop); if (!below) point += hints.offsetHeight; if (point <= editor.top || point >= editor.bottom) return completion.close(); hints.style.top = newTop + "px"; hints.style.left = (left + startScroll.left - curScroll.left) + "px"; }); CodeMirror.on(hints, "dblclick", function(e) { var t = getHintElement(hints, e.target || e.srcElement); if (t && t.hintId != null) {widget.changeActive(t.hintId); widget.pick();} }); CodeMirror.on(hints, "click", function(e) { var t = getHintElement(hints, e.target || e.srcElement); if (t && t.hintId != null) { widget.changeActive(t.hintId); if (completion.options.completeOnSingleClick) widget.pick(); } }); CodeMirror.on(hints, "mousedown", function() { setTimeout(function(){cm.focus();}, 20); }); CodeMirror.signal(data, "select", completions[0], hints.firstChild); return true; } Widget.prototype = { close: function() { if (this.completion.widget != this) return; this.completion.widget = null; this.hints.parentNode.removeChild(this.hints); this.completion.cm.removeKeyMap(this.keyMap); var cm = this.completion.cm; if (this.completion.options.closeOnUnfocus) { cm.off("blur", this.onBlur); cm.off("focus", this.onFocus); } cm.off("scroll", this.onScroll); }, pick: function() { this.completion.pick(this.data, this.selectedHint); }, changeActive: function(i, avoidWrap) { if (i >= this.data.list.length) i = avoidWrap ? this.data.list.length - 1 : 0; else if (i < 0) i = avoidWrap ? 0 : this.data.list.length - 1; if (this.selectedHint == i) return; var node = this.hints.childNodes[this.selectedHint]; node.className = node.className.replace(" " + ACTIVE_HINT_ELEMENT_CLASS, ""); node = this.hints.childNodes[this.selectedHint = i]; node.className += " " + ACTIVE_HINT_ELEMENT_CLASS; if (node.offsetTop < this.hints.scrollTop) this.hints.scrollTop = node.offsetTop - 3; else if (node.offsetTop + node.offsetHeight > this.hints.scrollTop + this.hints.clientHeight) this.hints.scrollTop = node.offsetTop + node.offsetHeight - this.hints.clientHeight + 3; CodeMirror.signal(this.data, "select", this.data.list[this.selectedHint], node); }, screenAmount: function() { return Math.floor(this.hints.clientHeight / this.hints.firstChild.offsetHeight) || 1; } }; CodeMirror.registerHelper("hint", "auto", function(cm, options) { var helpers = cm.getHelpers(cm.getCursor(), "hint"), words; if (helpers.length) { for (var i = 0; i < helpers.length; i++) { var cur = helpers[i](cm, options); if (cur && cur.list.length) return cur; } } else if (words = cm.getHelper(cm.getCursor(), "hintWords")) { if (words) return CodeMirror.hint.fromList(cm, {words: words}); } else if (CodeMirror.hint.anyword) { return CodeMirror.hint.anyword(cm, options); } }); CodeMirror.registerHelper("hint", "fromList", function(cm, options) { var cur = cm.getCursor(), token = cm.getTokenAt(cur); var found = []; for (var i = 0; i < options.words.length; i++) { var word = options.words[i]; if (word.slice(0, token.string.length) == token.string) found.push(word); } if (found.length) return { list: found, from: CodeMirror.Pos(cur.line, token.start), to: CodeMirror.Pos(cur.line, token.end) }; }); CodeMirror.commands.autocomplete = CodeMirror.showHint; var defaultOptions = { hint: CodeMirror.hint.auto, completeSingle: true, alignWithWord: true, closeCharacters: /[\s()\[\]{};:>,]/, closeOnUnfocus: true, completeOnSingleClick: false, container: null, customKeys: null, extraKeys: null }; CodeMirror.defineOption("hintOptions", null); });
public/js/lib/codemirror/addon/hint/show-hint.js
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/b9372b9af6809b7cdd3bd118d0d0be9eebab231a
[ 0.00017724772624205798, 0.0001729649375192821, 0.0001643376745050773, 0.00017357920296490192, 0.0000029091133910696954 ]
{ "id": 4, "code_window": [ " return gulp.src(['public/js/lib/**/*'])\n", " .pipe(eslint())\n", " .pipe(eslint.format());\n", "});\n", "\n", "gulp.task('default', ['lint', 'serve', 'sync']);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace" ], "after_edit": [ "gulp.task('default', ['serve', 'sync']);" ], "file_path": "gulpfile.js", "type": "replace", "edit_start_line_idx": 70 }
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function() { var mode = CodeMirror.getMode({}, "shell"); function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } MT("var", "text [def $var] text"); MT("varBraces", "text[def ${var}]text"); MT("varVar", "text [def $a$b] text"); MT("varBracesVarBraces", "text[def ${a}${b}]text"); MT("singleQuotedVar", "[string 'text $var text']"); MT("singleQuotedVarBraces", "[string 'text ${var} text']"); MT("doubleQuotedVar", '[string "text ][def $var][string text"]'); MT("doubleQuotedVarBraces", '[string "text][def ${var}][string text"]'); MT("doubleQuotedVarPunct", '[string "text ][def $@][string text"]'); MT("doubleQuotedVarVar", '[string "][def $a$b][string "]'); MT("doubleQuotedVarBracesVarBraces", '[string "][def ${a}${b}][string "]'); MT("notAString", "text\\'text"); MT("escapes", "outside\\'\\\"\\`\\\\[string \"inside\\`\\'\\\"\\\\`\\$notAVar\"]outside\\$\\(notASubShell\\)"); MT("subshell", "[builtin echo] [quote $(whoami)] s log, stardate [quote `date`]."); MT("doubleQuotedSubshell", "[builtin echo] [string \"][quote $(whoami)][string 's log, stardate `date`.\"]"); MT("hashbang", "[meta #!/bin/bash]"); MT("comment", "text [comment # Blurb]"); MT("numbers", "[number 0] [number 1] [number 2]"); MT("keywords", "[keyword while] [atom true]; [keyword do]", " [builtin sleep] [number 3]", "[keyword done]"); MT("options", "[builtin ls] [attribute -l] [attribute --human-readable]"); MT("operator", "[def var][operator =]value"); })();
public/js/lib/codemirror/mode/shell/test.js
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/b9372b9af6809b7cdd3bd118d0d0be9eebab231a
[ 0.00017756946908775717, 0.0001733588142087683, 0.000167438032804057, 0.00017392882728017867, 0.000003457392494965461 ]
{ "id": 4, "code_window": [ " return gulp.src(['public/js/lib/**/*'])\n", " .pipe(eslint())\n", " .pipe(eslint.format());\n", "});\n", "\n", "gulp.task('default', ['lint', 'serve', 'sync']);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace" ], "after_edit": [ "gulp.task('default', ['serve', 'sync']);" ], "file_path": "gulpfile.js", "type": "replace", "edit_start_line_idx": 70 }
{ "name": "angular", "version": "1.2.28", "main": "./angular.js", "ignore": [], "dependencies": {}, "homepage": "https://github.com/angular/bower-angular", "_release": "1.2.28", "_resolution": { "type": "version", "tag": "v1.2.28", "commit": "d1369fe05d3a7d85961a2223292b67ee82b9f80a" }, "_source": "git://github.com/angular/bower-angular.git", "_target": ">=1 <1.3.0", "_originalSource": "angular" }
bower_components/angular/.bower.json
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/b9372b9af6809b7cdd3bd118d0d0be9eebab231a
[ 0.00017137500981334597, 0.0001708325871732086, 0.000170290149981156, 0.0001708325871732086, 5.424299160949886e-7 ]
{ "id": 0, "code_window": [ " */\n", "\n", ".superset-legacy-chart-horizon {\n", " overflow: auto;\n", "}\n", "\n", ".superset-legacy-chart-horizon .horizon-row {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " position: relative;\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/superset-ui-plugins/packages/superset-ui-legacy-plugin-chart-horizon/src/HorizonChart.css", "type": "add", "edit_start_line_idx": 21 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* eslint-disable sort-keys */ import React from 'react'; import PropTypes from 'prop-types'; import { extent as d3Extent } from 'd3-array'; import HorizonRow, { DEFAULT_COLORS } from './HorizonRow'; import './HorizonChart.css'; const propTypes = { className: PropTypes.string, width: PropTypes.number, seriesHeight: PropTypes.number, data: PropTypes.arrayOf( PropTypes.shape({ key: PropTypes.arrayOf(PropTypes.string), values: PropTypes.arrayOf( PropTypes.shape({ y: PropTypes.number, }), ), }), ).isRequired, // number of bands in each direction (positive / negative) bands: PropTypes.number, colors: PropTypes.arrayOf(PropTypes.string), colorScale: PropTypes.string, mode: PropTypes.string, offsetX: PropTypes.number, }; const defaultProps = { className: '', width: 800, seriesHeight: 20, bands: Math.floor(DEFAULT_COLORS.length / 2), colors: DEFAULT_COLORS, colorScale: 'series', mode: 'offset', offsetX: 0, }; class HorizonChart extends React.PureComponent { render() { const { className, width, data, seriesHeight, bands, colors, colorScale, mode, offsetX, } = this.props; let yDomain; if (colorScale === 'overall') { const allValues = data.reduce((acc, current) => acc.concat(current.values), []); yDomain = d3Extent(allValues, d => d.y); } return ( <div className={`superset-legacy-chart-horizon ${className}`}> {data.map(row => ( <HorizonRow key={row.key} width={width} height={seriesHeight} title={row.key.join(', ')} data={row.values} bands={bands} colors={colors} colorScale={colorScale} mode={mode} offsetX={offsetX} yDomain={yDomain} /> ))} </div> ); } } HorizonChart.propTypes = propTypes; HorizonChart.defaultProps = defaultProps; export default HorizonChart;
superset-frontend/temporary_superset_ui/superset-ui/plugins/superset-ui-plugins/packages/superset-ui-legacy-plugin-chart-horizon/src/HorizonChart.jsx
1
https://github.com/apache/superset/commit/7019442a55adce54a3994ddf81b3bcdf6fe3c88f
[ 0.007891058921813965, 0.0016659717075526714, 0.00016329457866959274, 0.00017584649322088808, 0.0028592452872544527 ]
{ "id": 0, "code_window": [ " */\n", "\n", ".superset-legacy-chart-horizon {\n", " overflow: auto;\n", "}\n", "\n", ".superset-legacy-chart-horizon .horizon-row {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " position: relative;\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/superset-ui-plugins/packages/superset-ui-legacy-plugin-chart-horizon/src/HorizonChart.css", "type": "add", "edit_start_line_idx": 21 }
import { QueryFormData } from '@superset-ui/query'; import { FormDataProps } from './Line'; type CombinedFormData = QueryFormData & FormDataProps; export default CombinedFormData;
superset-frontend/temporary_superset_ui/superset-ui/plugins/superset-ui-plugins/packages/superset-ui-preset-chart-xy/src/Line/ChartFormData.ts
0
https://github.com/apache/superset/commit/7019442a55adce54a3994ddf81b3bcdf6fe3c88f
[ 0.00016818159201648086, 0.00016818159201648086, 0.00016818159201648086, 0.00016818159201648086, 0 ]
{ "id": 0, "code_window": [ " */\n", "\n", ".superset-legacy-chart-horizon {\n", " overflow: auto;\n", "}\n", "\n", ".superset-legacy-chart-horizon .horizon-row {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " position: relative;\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/superset-ui-plugins/packages/superset-ui-legacy-plugin-chart-horizon/src/HorizonChart.css", "type": "add", "edit_start_line_idx": 21 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React from 'react'; import { t, supersetTheme } from '@superset-ui/core'; import Icons, { IconType } from 'src/components/Icons'; import { Tooltip } from 'src/components/Tooltip'; export interface CertifiedIconProps { certifiedBy?: string; details?: string; size?: IconType['iconSize']; } function CertifiedIcon({ certifiedBy, details, size = 'l', }: CertifiedIconProps) { return ( <Tooltip id="certified-details-tooltip" title={ <> {certifiedBy && ( <div> <strong>{t('Certified by %s', certifiedBy)}</strong> </div> )} <div>{details}</div> </> } > <Icons.Certified iconColor={supersetTheme.colors.primary.base} iconSize={size} /> </Tooltip> ); } export default CertifiedIcon;
superset-frontend/src/components/CertifiedIcon/index.tsx
0
https://github.com/apache/superset/commit/7019442a55adce54a3994ddf81b3bcdf6fe3c88f
[ 0.0001741176238283515, 0.00017181069415528327, 0.0001691515208221972, 0.00017222444876097143, 0.0000016864772760527558 ]
{ "id": 0, "code_window": [ " */\n", "\n", ".superset-legacy-chart-horizon {\n", " overflow: auto;\n", "}\n", "\n", ".superset-legacy-chart-horizon .horizon-row {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " position: relative;\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/superset-ui-plugins/packages/superset-ui-legacy-plugin-chart-horizon/src/HorizonChart.css", "type": "add", "edit_start_line_idx": 21 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { t } from '@superset-ui/translation'; import { ChartMetadata, ChartPlugin } from '@superset-ui/chart'; import thumbnail from './images/thumbnail.png'; const metadata = new ChartMetadata({ credits: ['https://www.mapbox.com/mapbox-gl-js/api/'], description: '', name: t('MapBox'), thumbnail, useLegacyApi: true, }); export default class MapBoxChartPlugin extends ChartPlugin { constructor() { super({ loadChart: () => import('./MapBox'), loadTransformProps: () => import('./transformProps.js'), metadata, }); } }
superset-frontend/temporary_superset_ui/superset-ui/plugins/superset-ui-plugins/packages/superset-ui-legacy-plugin-chart-map-box/src/index.js
0
https://github.com/apache/superset/commit/7019442a55adce54a3994ddf81b3bcdf6fe3c88f
[ 0.00017507186566945165, 0.00017168720660265535, 0.00016838248120620847, 0.00017164723249152303, 0.000002940492777270265 ]
{ "id": 1, "code_window": [ "const propTypes = {\n", " className: PropTypes.string,\n", " width: PropTypes.number,\n", " seriesHeight: PropTypes.number,\n", " data: PropTypes.arrayOf(\n", " PropTypes.shape({\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " height: PropTypes.number,\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/superset-ui-plugins/packages/superset-ui-legacy-plugin-chart-horizon/src/HorizonChart.jsx", "type": "add", "edit_start_line_idx": 28 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* eslint-disable sort-keys */ import React from 'react'; import PropTypes from 'prop-types'; import { extent as d3Extent } from 'd3-array'; import HorizonRow, { DEFAULT_COLORS } from './HorizonRow'; import './HorizonChart.css'; const propTypes = { className: PropTypes.string, width: PropTypes.number, seriesHeight: PropTypes.number, data: PropTypes.arrayOf( PropTypes.shape({ key: PropTypes.arrayOf(PropTypes.string), values: PropTypes.arrayOf( PropTypes.shape({ y: PropTypes.number, }), ), }), ).isRequired, // number of bands in each direction (positive / negative) bands: PropTypes.number, colors: PropTypes.arrayOf(PropTypes.string), colorScale: PropTypes.string, mode: PropTypes.string, offsetX: PropTypes.number, }; const defaultProps = { className: '', width: 800, seriesHeight: 20, bands: Math.floor(DEFAULT_COLORS.length / 2), colors: DEFAULT_COLORS, colorScale: 'series', mode: 'offset', offsetX: 0, }; class HorizonChart extends React.PureComponent { render() { const { className, width, data, seriesHeight, bands, colors, colorScale, mode, offsetX, } = this.props; let yDomain; if (colorScale === 'overall') { const allValues = data.reduce((acc, current) => acc.concat(current.values), []); yDomain = d3Extent(allValues, d => d.y); } return ( <div className={`superset-legacy-chart-horizon ${className}`}> {data.map(row => ( <HorizonRow key={row.key} width={width} height={seriesHeight} title={row.key.join(', ')} data={row.values} bands={bands} colors={colors} colorScale={colorScale} mode={mode} offsetX={offsetX} yDomain={yDomain} /> ))} </div> ); } } HorizonChart.propTypes = propTypes; HorizonChart.defaultProps = defaultProps; export default HorizonChart;
superset-frontend/temporary_superset_ui/superset-ui/plugins/superset-ui-plugins/packages/superset-ui-legacy-plugin-chart-horizon/src/HorizonChart.jsx
1
https://github.com/apache/superset/commit/7019442a55adce54a3994ddf81b3bcdf6fe3c88f
[ 0.9982671737670898, 0.4504374563694, 0.00017160509014502168, 0.011049940250813961, 0.49057403206825256 ]
{ "id": 1, "code_window": [ "const propTypes = {\n", " className: PropTypes.string,\n", " width: PropTypes.number,\n", " seriesHeight: PropTypes.number,\n", " data: PropTypes.arrayOf(\n", " PropTypes.shape({\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " height: PropTypes.number,\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/superset-ui-plugins/packages/superset-ui-legacy-plugin-chart-horizon/src/HorizonChart.jsx", "type": "add", "edit_start_line_idx": 28 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. openapi_spec_methods_override = { "get": {"get": {"description": "Get query detail information."}}, "get_list": { "get": { "description": "Get a list of queries, use Rison or JSON query " "parameters for filtering, sorting, pagination and " " for selecting specific columns and metadata.", } }, }
superset/queries/schemas.py
0
https://github.com/apache/superset/commit/7019442a55adce54a3994ddf81b3bcdf6fe3c88f
[ 0.00017609010683372617, 0.00017283127817790955, 0.00016798701835796237, 0.00017441672389395535, 0.000003492871428534272 ]
{ "id": 1, "code_window": [ "const propTypes = {\n", " className: PropTypes.string,\n", " width: PropTypes.number,\n", " seriesHeight: PropTypes.number,\n", " data: PropTypes.arrayOf(\n", " PropTypes.shape({\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " height: PropTypes.number,\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/superset-ui-plugins/packages/superset-ui-legacy-plugin-chart-horizon/src/HorizonChart.jsx", "type": "add", "edit_start_line_idx": 28 }
--- name: Installing Database Drivers menu: Connecting to Databases route: /docs/databases/installing-database-drivers index: 0 version: 1 --- ## Install Database Drivers Superset requires a Python DB-API database driver and a SQLAlchemy dialect to be installed for each datastore you want to connect to. You can read more [here](/docs/databases/dockeradddrivers) about how to install new database drivers into your Superset configuration. ### Supported Databases and Dependencies Superset does not ship bundled with connectivity to databases, except for SQLite, which is part of the Python standard library. You’ll need to install the required packages for the database you want to use as your metadata database as well as the packages needed to connect to the databases you want to access through Superset. A list of some of the recommended packages. | Database | PyPI package | Connection String | | --- | --- | --- | |[Amazon Athena](/docs/databases/athena)|```pip install "PyAthenaJDBC>1.0.9``` , ```pip install "PyAthena>1.2.0``` | ```awsathena+rest://{aws_access_key_id}:{aws_secret_access_key}@athena.{region_name}.amazonaws.com/{ ```| |[Amazon Redshift](/docs/databases/redshift)|```pip install sqlalchemy-redshift```| ``` redshift+psycopg2://<userName>:<DBPassword>@<AWS End Point>:5439/<Database Name>``` | |[Apache Drill](/docs/databases/drill)|```pip install sqlalchemy-drill```| ```drill+sadrill:// For JDBC drill+jdbc://``` | |[Apache Druid](/docs/databases/druid)|```pip install pydruid```| ```druid://<User>:<password>@<Host>:<Port-default-9088>/druid/v2/sql``` | |[Apache Hive](/docs/databases/hive)|```pip install pyhive```|```hive://hive@{hostname}:{port}/{database}```| |[Apache Impala](/docs/databases/impala)|```pip install impyla```|```impala://{hostname}:{port}/{database}```| |[Apache Kylin](/docs/databases/kylin)|```pip install kylinpy```|```kylin://<username>:<password>@<hostname>:<port>/<project>?<param1>=<value1>&<param2>=<value2>```| |[Apache Pinot](/docs/databases/pinot)|```pip install pinotdb```|```pinot://BROKER:5436/query?server=http://CONTROLLER:5983/```| |[Apache Solr](/docs/databases/solr)|```pip install sqlalchemy-solr```|```solr://{username}:{password}@{hostname}:{port}/{server_path}/{collection}``` |[Apache Spark SQL](/docs/databases/spark-sql)|```pip install pyhive```|```hive://hive@{hostname}:{port}/{database}``` |[Ascend.io](/docs/databases/ascend)|```pip install impyla```|```ascend://{username}:{password}@{hostname}:{port}/{database}?auth_mechanism=PLAIN;use_ssl=true```| |[Azure MS SQL](/docs/databases/sql-server)|```pip install pymssql``` |```mssql+pymssql://UserName@presetSQL:[email protected]:1433/TestSchema``` |[Big Query](/docs/databases/bigquery)|```pip install pybigquery```|```bigquery://{project_id}```| |[ClickHouse](/docs/databases/clickhouse)|```pip install clickhouse-driver==0.2.0 && pip install clickhouse-sqlalchemy==0.1.6```|```clickhouse+native://{username}:{password}@{hostname}:{port}/{database}```| |[CockroachDB](/docs/databases/cockroachdb)|```pip install cockroachdb```|```cockroachdb://root@{hostname}:{port}/{database}?sslmode=disable```| |[Dremio](/docs/databases/dremio)|```pip install sqlalchemy_dremio```|```dremio://user:pwd@host:31010/```| |[Elasticsearch](/docs/databases/elasticsearch)|```pip install elasticsearch-dbapi```|```elasticsearch+http://{user}:{password}@{host}:9200/```| |[Exasol](/docs/databases/exasol)|```pip install sqlalchemy-exasol```|```exa+pyodbc://{username}:{password}@{hostname}:{port}/my_schema?CONNECTIONLCALL=en_US.UTF-8&driver=EXAODBC```| |[Google Sheets](/docs/databases/google-sheets)|```pip install shillelagh[gsheetsapi]```|```gsheets://```| |[Firebolt](/docs/databases/firebolt)|```pip install firebolt-sqlalchemy```|```firebolt://{username}:{password}@{database} or firebolt://{username}:{password}@{database}/{engine_name}```| |[Hologres](/docs/databases/hologres)|```pip install psycopg2```|```postgresql+psycopg2://<UserName>:<DBPassword>@<Database Host>/<Database Name>```| |[IBM Db2](/docs/databases/ibm-db2)|```pip install ibm_db_sa```|```db2+ibm_db://```| |[IBM Netezza Performance Server](/docs/databases/netezza)|```pip install nzalchemy```|```netezza+nzpy://<UserName>:<DBPassword>@<Database Host>/<Database Name>```| |[MySQL](/docs/databases/mysql)|```pip install mysqlclient```|```mysql://<UserName>:<DBPassword>@<Database Host>/<Database Name>```| |[Oracle](/docs/databases/oracle)|```pip install cx_Oracle```|```oracle://```| |[PostgreSQL](/docs/databases/postgres)|```pip install psycopg2```|```postgresql://<UserName>:<DBPassword>@<Database Host>/<Database Name>```| |[Trino](/docs/databases/trino)|```pip install sqlalchemy-trino```|```trino://{username}:{password}@{hostname}:{port}/{catalog}```| |[Presto](/docs/databases/presto)|```pip install pyhive```|```presto://```| |[SAP Hana](/docs/databases/hana)|```pip install hdbcli sqlalchemy-hana or pip install apache-superset[hana]```|```hana://{username}:{password}@{host}:{port}```| |[Snowflake](/docs/databases/snowflake)|```pip install snowflake-sqlalchemy```|```snowflake://{user}:{password}@{account}.{region}/{database}?role={role}&warehouse={warehouse}```| |SQLite||```sqlite://```| |[SQL Server](/docs/databases/sql-server)|```pip install pymssql```|```mssql://```| |[Teradata](/docs/databases/teradata)|```pip install sqlalchemy-teradata```|```teradata://{user}:{password}@{host}```| |[Vertica](/docs/databases/vertica)|```pip install sqlalchemy-vertica-python```|```vertica+vertica_python://<UserName>:<DBPassword>@<Database Host>/<Database Name>```| *** Note that many other databases are supported, the main criteria being the existence of a functional SQLAlchemy dialect and Python driver. Searching for the keyword "sqlalchemy + (database name)" should help get you to the right place. If your database or data engine isn't on the list but a SQL interface exists, please file an issue on the [Superset GitHub repo](https://github.com/apache/superset/issues), so we can work on documenting and supporting it. [StackOverflow](https://stackoverflow.com/questions/tagged/apache-superset+superset) and the [Superset community Slack](https://join.slack.com/t/apache-superset/shared_invite/zt-uxbh5g36-AISUtHbzOXcu0BIj7kgUaw) are great places to get help with connecting to databases in Superset.
docs/src/pages/docs/Connecting to Databases/index.mdx
0
https://github.com/apache/superset/commit/7019442a55adce54a3994ddf81b3bcdf6fe3c88f
[ 0.0001906194956973195, 0.0001687424664851278, 0.0001623455318622291, 0.0001655883388593793, 0.000008659937520860694 ]
{ "id": 1, "code_window": [ "const propTypes = {\n", " className: PropTypes.string,\n", " width: PropTypes.number,\n", " seriesHeight: PropTypes.number,\n", " data: PropTypes.arrayOf(\n", " PropTypes.shape({\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " height: PropTypes.number,\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/superset-ui-plugins/packages/superset-ui-legacy-plugin-chart-horizon/src/HorizonChart.jsx", "type": "add", "edit_start_line_idx": 28 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React from 'react'; import thunk from 'redux-thunk'; import configureStore from 'redux-mock-store'; import { Provider } from 'react-redux'; import fetchMock from 'fetch-mock'; import { styledMount as mount } from 'spec/helpers/theming'; import { render, screen, cleanup, waitFor } from 'spec/helpers/testing-library'; import userEvent from '@testing-library/user-event'; import { QueryParamProvider } from 'use-query-params'; import { act } from 'react-dom/test-utils'; import * as featureFlags from 'src/featureFlags'; import SavedQueryList from 'src/views/CRUD/data/savedquery/SavedQueryList'; import SubMenu from 'src/components/Menu/SubMenu'; import ListView from 'src/components/ListView'; import Filters from 'src/components/ListView/Filters'; import ActionsBar from 'src/components/ListView/ActionsBar'; import DeleteModal from 'src/components/DeleteModal'; import Button from 'src/components/Button'; import IndeterminateCheckbox from 'src/components/IndeterminateCheckbox'; import waitForComponentToPaint from 'spec/helpers/waitForComponentToPaint'; // store needed for withToasts(DatabaseList) const mockStore = configureStore([thunk]); const store = mockStore({}); const queriesInfoEndpoint = 'glob:*/api/v1/saved_query/_info*'; const queriesEndpoint = 'glob:*/api/v1/saved_query/?*'; const queryEndpoint = 'glob:*/api/v1/saved_query/*'; const queriesRelatedEndpoint = 'glob:*/api/v1/saved_query/related/database?*'; const queriesDistinctEndpoint = 'glob:*/api/v1/saved_query/distinct/schema?*'; const mockqueries = [...new Array(3)].map((_, i) => ({ created_by: { id: i, first_name: `user`, last_name: `${i}`, }, created_on: `${i}-2020`, database: { database_name: `db ${i}`, id: i, }, changed_on_delta_humanized: '1 day ago', db_id: i, description: `SQL for ${i}`, id: i, label: `query ${i}`, schema: 'public', sql: `SELECT ${i} FROM table`, sql_tables: [ { catalog: null, schema: null, table: `${i}`, }, ], })); // ---------- For import testing ---------- // Create an one more mocked query than the original mocked query array const mockOneMoreQuery = [...new Array(mockqueries.length + 1)].map((_, i) => ({ created_by: { id: i, first_name: `user`, last_name: `${i}`, }, created_on: `${i}-2020`, database: { database_name: `db ${i}`, id: i, }, changed_on_delta_humanized: '1 day ago', db_id: i, description: `SQL for ${i}`, id: i, label: `query ${i}`, schema: 'public', sql: `SELECT ${i} FROM table`, sql_tables: [ { catalog: null, schema: null, table: `${i}`, }, ], })); // Grab the last mocked query, to mock import const mockNewImportQuery = mockOneMoreQuery.pop(); // Create a new file out of mocked import query to mock upload const mockImportFile = new File( [mockNewImportQuery], 'saved_query_import_mock.json', ); fetchMock.get(queriesInfoEndpoint, { permissions: ['can_write', 'can_read'], }); fetchMock.get(queriesEndpoint, { result: mockqueries, count: 3, }); fetchMock.delete(queryEndpoint, {}); fetchMock.delete(queriesEndpoint, {}); fetchMock.get(queriesRelatedEndpoint, { count: 0, result: [], }); fetchMock.get(queriesDistinctEndpoint, { count: 0, result: [], }); // Mock utils module jest.mock('src/views/CRUD/utils'); describe('SavedQueryList', () => { const wrapper = mount( <Provider store={store}> <SavedQueryList /> </Provider>, ); beforeAll(async () => { await waitForComponentToPaint(wrapper); }); it('renders', () => { expect(wrapper.find(SavedQueryList)).toExist(); }); it('renders a SubMenu', () => { expect(wrapper.find(SubMenu)).toExist(); }); it('renders a ListView', () => { expect(wrapper.find(ListView)).toExist(); }); it('fetches saved queries', () => { const callsQ = fetchMock.calls(/saved_query\/\?q/); expect(callsQ).toHaveLength(1); expect(callsQ[0][0]).toMatchInlineSnapshot( `"http://localhost/api/v1/saved_query/?q=(order_column:changed_on_delta_humanized,order_direction:desc,page:0,page_size:25)"`, ); }); it('renders ActionsBar in table', () => { expect(wrapper.find(ActionsBar)).toExist(); expect(wrapper.find(ActionsBar)).toHaveLength(3); }); it('deletes', async () => { act(() => { wrapper.find('span[data-test="delete-action"]').first().props().onClick(); }); await waitForComponentToPaint(wrapper); expect( wrapper.find(DeleteModal).first().props().description, ).toMatchInlineSnapshot( `"This action will permanently delete the saved query."`, ); act(() => { wrapper .find('#delete') .first() .props() .onChange({ target: { value: 'DELETE' } }); }); await waitForComponentToPaint(wrapper); act(() => { wrapper.find('button').last().props().onClick(); }); await waitForComponentToPaint(wrapper); expect(fetchMock.calls(/saved_query\/0/, 'DELETE')).toHaveLength(1); }); it('shows/hides bulk actions when bulk actions is clicked', async () => { const button = wrapper.find(Button).at(0); act(() => { button.props().onClick(); }); await waitForComponentToPaint(wrapper); expect(wrapper.find(IndeterminateCheckbox)).toHaveLength( mockqueries.length + 1, // 1 for each row and 1 for select all ); }); it('searches', async () => { const filtersWrapper = wrapper.find(Filters); act(() => { filtersWrapper.find('[name="label"]').first().props().onSubmit('fooo'); }); await waitForComponentToPaint(wrapper); expect(fetchMock.lastCall()[0]).toMatchInlineSnapshot( `"http://localhost/api/v1/saved_query/?q=(filters:!((col:label,opr:all_text,value:fooo)),order_column:changed_on_delta_humanized,order_direction:desc,page:0,page_size:25)"`, ); }); }); describe('RTL', () => { async function renderAndWait() { const mounted = act(async () => { render( <QueryParamProvider> <SavedQueryList /> </QueryParamProvider>, { useRedux: true }, ); }); return mounted; } let isFeatureEnabledMock; beforeEach(async () => { isFeatureEnabledMock = jest .spyOn(featureFlags, 'isFeatureEnabled') .mockImplementation(() => true); await renderAndWait(); }); afterEach(() => { cleanup(); isFeatureEnabledMock.mockRestore(); }); it('renders an export button in the bulk actions', () => { // Grab and click the "Bulk Select" button to expose checkboxes const bulkSelectButton = screen.getByRole('button', { name: /bulk select/i, }); userEvent.click(bulkSelectButton); // Grab and click the "toggle all" checkbox to expose export button const selectAllCheckbox = screen.getByRole('checkbox', { name: /toggle all rows selected/i, }); userEvent.click(selectAllCheckbox); // Grab and assert that export button is visible const exportButton = screen.getByRole('button', { name: /export/i, }); expect(exportButton).toBeVisible(); }); it('renders an export button in the actions bar', async () => { // Grab Export action button and mock mouse hovering over it const exportActionButton = screen.getAllByTestId('export-action')[0]; userEvent.hover(exportActionButton); // Wait for the tooltip to pop up await screen.findByRole('tooltip'); // Grab and assert that "Export Query" tooltip is in the document const exportTooltip = screen.getByRole('tooltip', { name: /export query/i, }); expect(exportTooltip).toBeInTheDocument(); }); it('renders an import button in the submenu', async () => { // Grab and assert that import saved query button is visible const importButton = await screen.findByTestId('import-button'); expect(importButton).toBeVisible(); }); it('renders an "Import Saved Query" tooltip under import button', async () => { const importButton = await screen.findByTestId('import-button'); userEvent.hover(importButton); waitFor(() => { expect(importButton).toHaveClass('ant-tooltip-open'); screen.findByTestId('import-tooltip-test'); const importTooltip = screen.getByRole('tooltip', { name: 'Import queries', }); expect(importTooltip).toBeInTheDocument(); }); }); it('renders an import modal when import button is clicked', async () => { // Grab and click import saved query button to reveal modal const importButton = await screen.findByTestId('import-button'); userEvent.click(importButton); // Grab and assert that saved query import modal's heading is visible const importSavedQueryModalHeading = screen.getByRole('heading', { name: 'Import queries', }); expect(importSavedQueryModalHeading).toBeVisible(); }); it('imports a saved query', async () => { // Grab and click import saved query button to reveal modal const importButton = await screen.findByTestId('import-button'); userEvent.click(importButton); // Grab "Choose File" input from import modal const chooseFileInput = screen.getByTestId('model-file-input'); // Upload mocked import file userEvent.upload(chooseFileInput, mockImportFile); expect(chooseFileInput.files[0]).toStrictEqual(mockImportFile); expect(chooseFileInput.files.item(0)).toStrictEqual(mockImportFile); expect(chooseFileInput.files).toHaveLength(1); }); });
superset-frontend/src/views/CRUD/data/savedquery/SavedQueryList.test.jsx
0
https://github.com/apache/superset/commit/7019442a55adce54a3994ddf81b3bcdf6fe3c88f
[ 0.00022155934129841626, 0.0001739165891194716, 0.00016739795682951808, 0.00017252420366276056, 0.000008725005500309635 ]
{ "id": 2, "code_window": [ "const defaultProps = {\n", " className: '',\n", " width: 800,\n", " seriesHeight: 20,\n", " bands: Math.floor(DEFAULT_COLORS.length / 2),\n", " colors: DEFAULT_COLORS,\n", " colorScale: 'series',\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " height: 600,\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/superset-ui-plugins/packages/superset-ui-legacy-plugin-chart-horizon/src/HorizonChart.jsx", "type": "add", "edit_start_line_idx": 49 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ .superset-legacy-chart-horizon { overflow: auto; } .superset-legacy-chart-horizon .horizon-row { border-bottom: solid 1px #ddd; border-top: 0px; padding: 0px; margin: 0px; } .superset-legacy-chart-horizon .horizon-row span.title { position: absolute; color: #333; font-size: 0.8em; margin: 0; text-shadow: 1px 1px rgba(255, 255, 255, 0.75); }
superset-frontend/temporary_superset_ui/superset-ui/plugins/superset-ui-plugins/packages/superset-ui-legacy-plugin-chart-horizon/src/HorizonChart.css
1
https://github.com/apache/superset/commit/7019442a55adce54a3994ddf81b3bcdf6fe3c88f
[ 0.0001767026842571795, 0.0001738649298204109, 0.00016981619410216808, 0.00017447042046114802, 0.000002645585482241586 ]
{ "id": 2, "code_window": [ "const defaultProps = {\n", " className: '',\n", " width: 800,\n", " seriesHeight: 20,\n", " bands: Math.floor(DEFAULT_COLORS.length / 2),\n", " colors: DEFAULT_COLORS,\n", " colorScale: 'series',\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " height: 600,\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/superset-ui-plugins/packages/superset-ui-legacy-plugin-chart-horizon/src/HorizonChart.jsx", "type": "add", "edit_start_line_idx": 49 }
import { t } from '@superset-ui/translation'; import { ChartMetadata } from '@superset-ui/chart'; import thumbnail from './images/thumbnail.png'; export default function createMetadata(useLegacyApi = false) { return new ChartMetadata({ description: '', name: t('Scatter Plot'), thumbnail, useLegacyApi, }); }
superset-frontend/temporary_superset_ui/superset-ui/plugins/superset-ui-plugins/packages/superset-ui-preset-chart-xy/src/ScatterPlot/createMetadata.ts
0
https://github.com/apache/superset/commit/7019442a55adce54a3994ddf81b3bcdf6fe3c88f
[ 0.00017592162475921214, 0.00017548806499689817, 0.00017505451978649944, 0.00017548806499689817, 4.335524863563478e-7 ]
{ "id": 2, "code_window": [ "const defaultProps = {\n", " className: '',\n", " width: 800,\n", " seriesHeight: 20,\n", " bands: Math.floor(DEFAULT_COLORS.length / 2),\n", " colors: DEFAULT_COLORS,\n", " colorScale: 'series',\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " height: 600,\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/superset-ui-plugins/packages/superset-ui-legacy-plugin-chart-horizon/src/HorizonChart.jsx", "type": "add", "edit_start_line_idx": 49 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React, { CSSProperties } from 'react'; import { Tag } from 'src/common/components'; import { useTheme } from '@superset-ui/core'; export type OnClickHandler = React.MouseEventHandler<HTMLElement>; export type Type = | 'success' | 'warning' | 'danger' | 'info' | 'default' | 'primary' | 'secondary'; export interface LabelProps extends React.HTMLAttributes<HTMLSpanElement> { key?: string; className?: string; onClick?: OnClickHandler; type?: Type; style?: CSSProperties; children?: React.ReactNode; role?: string; } export default function Label(props: LabelProps) { const theme = useTheme(); const { colors, transitionTiming } = theme; const { type, onClick, children, ...rest } = props; const { primary, secondary, grayscale, success, warning, error, info } = colors; let backgroundColor = grayscale.light3; let backgroundColorHover = onClick ? primary.light2 : grayscale.light3; let borderColor = onClick ? grayscale.light2 : 'transparent'; let borderColorHover = onClick ? primary.light1 : 'transparent'; let color = grayscale.dark1; if (type && type !== 'default') { color = grayscale.light4; let baseColor; if (type === 'success') { baseColor = success; } else if (type === 'warning') { baseColor = warning; } else if (type === 'danger') { baseColor = error; } else if (type === 'info') { baseColor = info; } else if (type === 'secondary') { baseColor = secondary; } else { baseColor = primary; } backgroundColor = baseColor.base; backgroundColorHover = onClick ? baseColor.dark1 : baseColor.base; borderColor = onClick ? baseColor.dark1 : 'transparent'; borderColorHover = onClick ? baseColor.dark2 : 'transparent'; } return ( <Tag onClick={onClick} {...rest} css={{ transition: `background-color ${transitionTiming}s`, whiteSpace: 'nowrap', cursor: onClick ? 'pointer' : 'default', overflow: 'hidden', textOverflow: 'ellipsis', backgroundColor, borderColor, borderRadius: 21, padding: '0.35em 0.8em', lineHeight: 1, color, maxWidth: '100%', '&:hover': { backgroundColor: backgroundColorHover, borderColor: borderColorHover, opacity: 1, }, }} > {children} </Tag> ); }
superset-frontend/src/components/Label/index.tsx
0
https://github.com/apache/superset/commit/7019442a55adce54a3994ddf81b3bcdf6fe3c88f
[ 0.00043265169369988143, 0.00019893507123924792, 0.0001713028032099828, 0.00017516205844003707, 0.00007402966730296612 ]
{ "id": 2, "code_window": [ "const defaultProps = {\n", " className: '',\n", " width: 800,\n", " seriesHeight: 20,\n", " bands: Math.floor(DEFAULT_COLORS.length / 2),\n", " colors: DEFAULT_COLORS,\n", " colorScale: 'series',\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " height: 600,\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/superset-ui-plugins/packages/superset-ui-legacy-plugin-chart-horizon/src/HorizonChart.jsx", "type": "add", "edit_start_line_idx": 49 }
/* eslint-disable sort-keys, no-magic-numbers, complexity */ import React, { PureComponent } from 'react'; import { kebabCase, groupBy, flatMap, uniqueId, values } from 'lodash'; import { AreaSeries, LinearGradient, LineSeries, XYChart, CrossHair, WithTooltip, } from '@data-ui/xy-chart'; import { chartTheme } from '@data-ui/theme'; import { Margin, Dimension } from '@superset-ui/dimension'; import { WithLegend } from '@superset-ui/chart-composition'; import { createSelector } from 'reselect'; import Encoder, { Encoding, ChannelOutput } from './Encoder'; import { Dataset, PlainObject } from '../encodeable/types/Data'; import { PartialSpec } from '../encodeable/types/Specification'; import DefaultTooltipRenderer from './DefaultTooltipRenderer'; import createMarginSelector, { DEFAULT_MARGIN } from '../utils/selectors/createMarginSelector'; import convertScaleToDataUIScale from '../utils/convertScaleToDataUIScaleShape'; import createXYChartLayoutWithTheme from '../utils/createXYChartLayoutWithTheme'; import createEncoderSelector from '../encodeable/createEncoderSelector'; import createRenderLegend from '../components/legend/createRenderLegend'; import { LegendHooks } from '../components/legend/types'; export interface TooltipProps { encoder: Encoder; allSeries: Series[]; datum: SeriesValue; series: { [key: string]: SeriesValue; }; theme: typeof chartTheme; } const defaultProps = { className: '', margin: DEFAULT_MARGIN, theme: chartTheme, TooltipRenderer: DefaultTooltipRenderer, }; /** Part of formData that is needed for rendering logic in this file */ export type FormDataProps = { margin?: Margin; theme?: typeof chartTheme; } & PartialSpec<Encoding>; export type HookProps = { TooltipRenderer?: React.ComponentType<TooltipProps>; } & LegendHooks<Encoder>; type Props = { className?: string; width: string | number; height: string | number; data: Dataset; } & HookProps & FormDataProps & Readonly<typeof defaultProps>; export interface Series { key: string; fill: ChannelOutput<'fill'>; stroke: ChannelOutput<'stroke'>; strokeDasharray: ChannelOutput<'strokeDasharray'>; strokeWidth: ChannelOutput<'strokeWidth'>; values: SeriesValue[]; } export interface SeriesValue { x: number | Date; y: number; data: PlainObject; parent: Series; } const CIRCLE_STYLE = { strokeWidth: 1.5 }; export default class LineChart extends PureComponent<Props> { private createEncoder = createEncoderSelector(Encoder); private createAllSeries = createSelector( (input: { encoder: Encoder; data: Dataset }) => input.encoder, input => input.data, (encoder, data) => { const { channels } = encoder; const fieldNames = encoder.getGroupBys(); const groups = groupBy(data, row => fieldNames.map(f => `${f}=${row[f]}`).join(',')); const allSeries = values(groups).map(seriesData => { const firstDatum = seriesData[0]; const key = fieldNames.map(f => firstDatum[f]).join(','); const series: Series = { key: key.length === 0 ? channels.y.getTitle() : key, fill: channels.fill.encode(firstDatum, false), stroke: channels.stroke.encode(firstDatum, '#222'), strokeDasharray: channels.strokeDasharray.encode(firstDatum, ''), strokeWidth: channels.strokeWidth.encode(firstDatum, 1), values: [], }; series.values = seriesData .map(v => ({ x: channels.x.get<number | Date>(v), y: channels.y.get<number>(v), data: v, parent: series, })) .sort((a: SeriesValue, b: SeriesValue) => { const aTime = a.x instanceof Date ? a.x.getTime() : a.x; const bTime = b.x instanceof Date ? b.x.getTime() : b.x; return aTime - bTime; }); return series; }); return allSeries; }, ); private createMargin = createMarginSelector(); static defaultProps = defaultProps; constructor(props: Props) { super(props); this.renderChart = this.renderChart.bind(this); } renderSeries(allSeries: Series[]) { const filledSeries = flatMap( allSeries .filter(({ fill }) => fill) .map(series => { const gradientId = uniqueId(kebabCase(`gradient-${series.key}`)); return [ <LinearGradient key={`${series.key}-gradient`} id={gradientId} from={series.stroke} to="#fff" />, <AreaSeries key={`${series.key}-fill`} seriesKey={series.key} data={series.values} interpolation="linear" fill={`url(#${gradientId})`} stroke={series.stroke} strokeWidth={series.strokeWidth} />, ]; }), ); const unfilledSeries = allSeries .filter(({ fill }) => !fill) .map(series => ( <LineSeries key={series.key} seriesKey={series.key} interpolation="linear" data={series.values} stroke={series.stroke} strokeDasharray={series.strokeDasharray} strokeWidth={series.strokeWidth} /> )); return filledSeries.concat(unfilledSeries); } renderChart(dim: Dimension) { const { width, height } = dim; const { data, margin, theme, TooltipRenderer } = this.props; const encoder = this.createEncoder(this.props); const { channels } = encoder; if (typeof channels.x.scale !== 'undefined') { const xDomain = channels.x.getDomain(data); channels.x.scale.setDomain(xDomain); } if (typeof channels.y.scale !== 'undefined') { const yDomain = channels.y.getDomain(data); channels.y.scale.setDomain(yDomain); } const allSeries = this.createAllSeries({ encoder, data }); const layout = createXYChartLayoutWithTheme({ width, height, margin: this.createMargin(margin), theme, xEncoder: channels.x, yEncoder: channels.y, }); return layout.renderChartWithFrame((chartDim: Dimension) => ( <WithTooltip renderTooltip={({ datum, series, }: { datum: SeriesValue; series: { [key: string]: SeriesValue; }; }) => ( <TooltipRenderer encoder={encoder} allSeries={allSeries} datum={datum} series={series} theme={theme} /> )} > {({ onMouseLeave, onMouseMove, tooltipData, }: { onMouseLeave: (...args: any[]) => void; onMouseMove: (...args: any[]) => void; tooltipData: any; }) => ( <XYChart width={chartDim.width} height={chartDim.height} ariaLabel="LineChart" eventTrigger="container" margin={layout.margin} onMouseMove={onMouseMove} onMouseLeave={onMouseLeave} renderTooltip={null} showYGrid snapTooltipToDataX theme={theme} tooltipData={tooltipData} xScale={convertScaleToDataUIScale(channels.x.scale!.config)} yScale={convertScaleToDataUIScale(channels.y.scale!.config)} > {layout.renderXAxis()} {layout.renderYAxis()} {this.renderSeries(allSeries)} <CrossHair fullHeight strokeDasharray="" showHorizontalLine={false} circleFill={(d: SeriesValue) => d.y === tooltipData.datum.y ? d.parent.stroke : '#fff' } circleSize={(d: SeriesValue) => (d.y === tooltipData.datum.y ? 6 : 4)} circleStroke={(d: SeriesValue) => d.y === tooltipData.datum.y ? '#fff' : d.parent.stroke } circleStyles={CIRCLE_STYLE} stroke="#ccc" showCircle showMultipleCircles /> </XYChart> )} </WithTooltip> )); } render() { const { className, data, width, height } = this.props; const encoder = this.createEncoder(this.props); return ( <WithLegend className={`superset-chart-line ${className}`} width={width} height={height} position="top" renderLegend={createRenderLegend(encoder, data, this.props)} renderChart={this.renderChart} /> ); } }
superset-frontend/temporary_superset_ui/superset-ui/plugins/superset-ui-plugins/packages/superset-ui-preset-chart-xy/src/Line/Line.tsx
0
https://github.com/apache/superset/commit/7019442a55adce54a3994ddf81b3bcdf6fe3c88f
[ 0.9965343475341797, 0.08967746049165726, 0.00016619368398096412, 0.00021457622642628849, 0.27036893367767334 ]
{ "id": 3, "code_window": [ "class HorizonChart extends React.PureComponent {\n", " render() {\n", " const {\n", " className,\n", " width,\n", " data,\n", " seriesHeight,\n", " bands,\n", " colors,\n", " colorScale,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " height,\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/superset-ui-plugins/packages/superset-ui-legacy-plugin-chart-horizon/src/HorizonChart.jsx", "type": "add", "edit_start_line_idx": 62 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* eslint-disable sort-keys */ import React from 'react'; import PropTypes from 'prop-types'; import { extent as d3Extent } from 'd3-array'; import HorizonRow, { DEFAULT_COLORS } from './HorizonRow'; import './HorizonChart.css'; const propTypes = { className: PropTypes.string, width: PropTypes.number, seriesHeight: PropTypes.number, data: PropTypes.arrayOf( PropTypes.shape({ key: PropTypes.arrayOf(PropTypes.string), values: PropTypes.arrayOf( PropTypes.shape({ y: PropTypes.number, }), ), }), ).isRequired, // number of bands in each direction (positive / negative) bands: PropTypes.number, colors: PropTypes.arrayOf(PropTypes.string), colorScale: PropTypes.string, mode: PropTypes.string, offsetX: PropTypes.number, }; const defaultProps = { className: '', width: 800, seriesHeight: 20, bands: Math.floor(DEFAULT_COLORS.length / 2), colors: DEFAULT_COLORS, colorScale: 'series', mode: 'offset', offsetX: 0, }; class HorizonChart extends React.PureComponent { render() { const { className, width, data, seriesHeight, bands, colors, colorScale, mode, offsetX, } = this.props; let yDomain; if (colorScale === 'overall') { const allValues = data.reduce((acc, current) => acc.concat(current.values), []); yDomain = d3Extent(allValues, d => d.y); } return ( <div className={`superset-legacy-chart-horizon ${className}`}> {data.map(row => ( <HorizonRow key={row.key} width={width} height={seriesHeight} title={row.key.join(', ')} data={row.values} bands={bands} colors={colors} colorScale={colorScale} mode={mode} offsetX={offsetX} yDomain={yDomain} /> ))} </div> ); } } HorizonChart.propTypes = propTypes; HorizonChart.defaultProps = defaultProps; export default HorizonChart;
superset-frontend/temporary_superset_ui/superset-ui/plugins/superset-ui-plugins/packages/superset-ui-legacy-plugin-chart-horizon/src/HorizonChart.jsx
1
https://github.com/apache/superset/commit/7019442a55adce54a3994ddf81b3bcdf6fe3c88f
[ 0.9984633922576904, 0.6166417598724365, 0.00016661670815665275, 0.9586709141731262, 0.46687573194503784 ]
{ "id": 3, "code_window": [ "class HorizonChart extends React.PureComponent {\n", " render() {\n", " const {\n", " className,\n", " width,\n", " data,\n", " seriesHeight,\n", " bands,\n", " colors,\n", " colorScale,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " height,\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/superset-ui-plugins/packages/superset-ui-legacy-plugin-chart-horizon/src/HorizonChart.jsx", "type": "add", "edit_start_line_idx": 62 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React from 'react'; import PropTypes from 'prop-types'; import { Select } from 'src/components'; import { styled, t } from '@superset-ui/core'; import { SQLEditor } from 'src/components/AsyncAceEditor'; import sqlKeywords from 'src/SqlLab/utils/sqlKeywords'; import adhocMetricType from 'src/explore/components/controls/MetricControl/adhocMetricType'; import columnType from 'src/explore/components/controls/FilterControl/columnType'; import AdhocFilter, { EXPRESSION_TYPES, CLAUSES, } from 'src/explore/components/controls/FilterControl/AdhocFilter'; const propTypes = { adhocFilter: PropTypes.instanceOf(AdhocFilter).isRequired, onChange: PropTypes.func.isRequired, options: PropTypes.arrayOf( PropTypes.oneOfType([ columnType, PropTypes.shape({ saved_metric_name: PropTypes.string.isRequired }), adhocMetricType, ]), ).isRequired, height: PropTypes.number.isRequired, activeKey: PropTypes.string.isRequired, }; const StyledSelect = styled(Select)` ${({ theme }) => ` width: ${theme.gridUnit * 30}px; marginRight: ${theme.gridUnit}px; `} `; export default class AdhocFilterEditPopoverSqlTabContent extends React.Component { constructor(props) { super(props); this.onSqlExpressionChange = this.onSqlExpressionChange.bind(this); this.onSqlExpressionClauseChange = this.onSqlExpressionClauseChange.bind(this); this.handleAceEditorRef = this.handleAceEditorRef.bind(this); this.selectProps = { ariaLabel: t('Select column'), }; } componentDidUpdate() { if (this.aceEditorRef) { this.aceEditorRef.editor.resize(); } } onSqlExpressionClauseChange(clause) { this.props.onChange( this.props.adhocFilter.duplicateWith({ clause, expressionType: EXPRESSION_TYPES.SQL, }), ); } onSqlExpressionChange(sqlExpression) { this.props.onChange( this.props.adhocFilter.duplicateWith({ sqlExpression, expressionType: EXPRESSION_TYPES.SQL, }), ); } handleAceEditorRef(ref) { if (ref) { this.aceEditorRef = ref; } } render() { const { adhocFilter, height, options } = this.props; const clauseSelectProps = { placeholder: t('choose WHERE or HAVING...'), value: adhocFilter.clause, onChange: this.onSqlExpressionClauseChange, }; const keywords = sqlKeywords.concat( options .map(option => { if (option.column_name) { return { name: option.column_name, value: option.column_name, score: 50, meta: 'option', }; } return null; }) .filter(Boolean), ); const selectOptions = Object.keys(CLAUSES).map(clause => ({ label: clause, value: clause, })); return ( <span> <div className="filter-edit-clause-section"> <StyledSelect options={selectOptions} {...this.selectProps} {...clauseSelectProps} /> <span className="filter-edit-clause-info"> <strong>WHERE</strong> {t('Filters by columns')} <br /> <strong>HAVING</strong> {t('Filters by metrics')} </span> </div> <div css={theme => ({ marginTop: theme.gridUnit * 4 })}> <SQLEditor ref={this.handleAceEditorRef} keywords={keywords} height={`${height - 130}px`} onChange={this.onSqlExpressionChange} width="100%" showGutter={false} value={adhocFilter.sqlExpression || adhocFilter.translateToSql()} editorProps={{ $blockScrolling: true }} enableLiveAutocompletion className="filter-sql-editor" wrapEnabled /> </div> </span> ); } } AdhocFilterEditPopoverSqlTabContent.propTypes = propTypes;
superset-frontend/src/explore/components/controls/FilterControl/AdhocFilterEditPopoverSqlTabContent/index.jsx
0
https://github.com/apache/superset/commit/7019442a55adce54a3994ddf81b3bcdf6fe3c88f
[ 0.0003461219312157482, 0.00018362756236456335, 0.0001672685466473922, 0.00017336083692498505, 0.00004203573553240858 ]
{ "id": 3, "code_window": [ "class HorizonChart extends React.PureComponent {\n", " render() {\n", " const {\n", " className,\n", " width,\n", " data,\n", " seriesHeight,\n", " bands,\n", " colors,\n", " colorScale,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " height,\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/superset-ui-plugins/packages/superset-ui-legacy-plugin-chart-horizon/src/HorizonChart.jsx", "type": "add", "edit_start_line_idx": 62 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React, { RefObject } from 'react'; import Select, { propertyComparator } from 'src/components/Select/Select'; import { t, styled } from '@superset-ui/core'; import Alert from 'src/components/Alert'; import Button from 'src/components/Button'; import ModalTrigger from 'src/components/ModalTrigger'; import { FormLabel } from 'src/components/Form'; export const options = [ [0, t("Don't refresh")], [10, t('10 seconds')], [30, t('30 seconds')], [60, t('1 minute')], [300, t('5 minutes')], [1800, t('30 minutes')], [3600, t('1 hour')], [21600, t('6 hours')], [43200, t('12 hours')], [86400, t('24 hours')], ].map(o => ({ value: o[0] as number, label: o[1] })); const StyledModalTrigger = styled(ModalTrigger)` .ant-modal-body { overflow: visible; } `; const RefreshWarningContainer = styled.div` margin-top: ${({ theme }) => theme.gridUnit * 6}px; `; type RefreshIntervalModalProps = { triggerNode: JSX.Element; refreshFrequency: number; onChange: (refreshLimit: number, editMode: boolean) => void; editMode: boolean; refreshLimit?: number; refreshWarning: string | null; }; type RefreshIntervalModalState = { refreshFrequency: number; }; class RefreshIntervalModal extends React.PureComponent< RefreshIntervalModalProps, RefreshIntervalModalState > { static defaultProps = { refreshLimit: 0, refreshWarning: null, }; modalRef: RefObject<ModalTrigger>; constructor(props: RefreshIntervalModalProps) { super(props); this.modalRef = React.createRef(); this.state = { refreshFrequency: props.refreshFrequency, }; this.handleFrequencyChange = this.handleFrequencyChange.bind(this); this.onSave = this.onSave.bind(this); this.onCancel = this.onCancel.bind(this); } onSave() { this.props.onChange(this.state.refreshFrequency, this.props.editMode); this.modalRef.current?.close(); } onCancel() { this.setState({ refreshFrequency: this.props.refreshFrequency, }); this.modalRef.current?.close(); } handleFrequencyChange(value: number) { this.setState({ refreshFrequency: value || options[0].value, }); } render() { const { refreshLimit = 0, refreshWarning, editMode } = this.props; const { refreshFrequency = 0 } = this.state; const showRefreshWarning = !!refreshFrequency && !!refreshWarning && refreshFrequency < refreshLimit; return ( <StyledModalTrigger ref={this.modalRef} triggerNode={this.props.triggerNode} modalTitle={t('Refresh interval')} modalBody={ <div> <FormLabel>{t('Refresh frequency')}</FormLabel> <Select ariaLabel={t('Refresh interval')} options={options} value={refreshFrequency} onChange={this.handleFrequencyChange} sortComparator={propertyComparator('value')} /> {showRefreshWarning && ( <RefreshWarningContainer> <Alert type="warning" message={ <> <div>{refreshWarning}</div> <br /> <strong>{t('Are you sure you want to proceed?')}</strong> </> } /> </RefreshWarningContainer> )} </div> } modalFooter={ <> <Button buttonStyle="primary" buttonSize="small" onClick={this.onSave} > {editMode ? t('Save') : t('Save for this session')} </Button> <Button onClick={this.onCancel} buttonSize="small"> {t('Cancel')} </Button> </> } /> ); } } export default RefreshIntervalModal;
superset-frontend/src/dashboard/components/RefreshIntervalModal.tsx
0
https://github.com/apache/superset/commit/7019442a55adce54a3994ddf81b3bcdf6fe3c88f
[ 0.00043443660251796246, 0.000189163678442128, 0.00016841683827806264, 0.0001749030197970569, 0.00006138264870969579 ]
{ "id": 3, "code_window": [ "class HorizonChart extends React.PureComponent {\n", " render() {\n", " const {\n", " className,\n", " width,\n", " data,\n", " seriesHeight,\n", " bands,\n", " colors,\n", " colorScale,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " height,\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/superset-ui-plugins/packages/superset-ui-legacy-plugin-chart-horizon/src/HorizonChart.jsx", "type": "add", "edit_start_line_idx": 62 }
import '@babel/polyfill'; import { setAddon, storiesOf } from '@storybook/react'; import { withKnobs } from '@storybook/addon-knobs'; import JSXAddon from 'storybook-addon-jsx'; import categoricalD3 from '@superset-ui/color/esm/colorSchemes/categorical/d3'; import sequentialCommon from '@superset-ui/color/esm/colorSchemes/sequential/common'; import sequentialD3 from '@superset-ui/color/esm/colorSchemes/sequential/d3'; import { configure } from '@superset-ui/translation'; import { getCategoricalSchemeRegistry, getSequentialSchemeRegistry } from '@superset-ui/color'; import { getTimeFormatterRegistry, smartDateFormatter } from '@superset-ui/time-format'; setAddon(JSXAddon); configure(); // Register color schemes const categoricalSchemeRegistry = getCategoricalSchemeRegistry(); [categoricalD3].forEach(group => { group.forEach(scheme => { categoricalSchemeRegistry.registerValue(scheme.id, scheme); }); }); categoricalSchemeRegistry.setDefaultKey('d3Category10'); const sequentialSchemeRegistry = getSequentialSchemeRegistry(); [sequentialCommon, sequentialD3].forEach(group => { group.forEach(scheme => { sequentialSchemeRegistry.registerValue(scheme.id, scheme); }); }); getTimeFormatterRegistry() .registerValue('smart_date', smartDateFormatter) .setDefaultKey('smart_date'); const EMPTY_EXAMPLES = [ { renderStory: () => 'Does your default export have an `examples` key?', storyName: 'No examples found', }, ]; /* * Below we crawl the dir + subdirs looking for index files of stories * Each index is expected to have a default export with examples key containing * an array of examples. Each example should have the shape: * { storyPath: string, storyName: string, renderStory: fn() => node } * */ const requireContext = require.context('./', /* subdirs= */ true, /index\.jsx?$/); requireContext.keys().forEach(packageName => { const packageExport = requireContext(packageName); if (packageExport && packageExport.default && !Array.isArray(packageExport.default)) { const { examples = EMPTY_EXAMPLES } = packageExport.default; examples.forEach(example => { const { storyPath = 'Missing story path', storyName = 'Missing name', renderStory = () => 'Missing `renderStory`', options = {}, } = example; storiesOf(storyPath, module) .addParameters({ options }) .addDecorator(withKnobs) .addWithJSX(storyName, renderStory); }); } });
superset-frontend/temporary_superset_ui/superset-ui/plugins/superset-ui-plugins/packages/superset-ui-plugins-demo/storybook/stories/index.js
0
https://github.com/apache/superset/commit/7019442a55adce54a3994ddf81b3bcdf6fe3c88f
[ 0.00017801056674215943, 0.0001728671632008627, 0.00016752745432313532, 0.00017341638158541173, 0.0000039789811125956476 ]
{ "id": 4, "code_window": [ " yDomain = d3Extent(allValues, d => d.y);\n", " }\n", "\n", " return (\n", " <div className={`superset-legacy-chart-horizon ${className}`}>\n", " {data.map(row => (\n", " <HorizonRow\n", " key={row.key}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <div className={`superset-legacy-chart-horizon ${className}`} style={{ height }}>\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/superset-ui-plugins/packages/superset-ui-legacy-plugin-chart-horizon/src/HorizonChart.jsx", "type": "replace", "edit_start_line_idx": 78 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* eslint-disable sort-keys */ import React from 'react'; import PropTypes from 'prop-types'; import { extent as d3Extent } from 'd3-array'; import HorizonRow, { DEFAULT_COLORS } from './HorizonRow'; import './HorizonChart.css'; const propTypes = { className: PropTypes.string, width: PropTypes.number, seriesHeight: PropTypes.number, data: PropTypes.arrayOf( PropTypes.shape({ key: PropTypes.arrayOf(PropTypes.string), values: PropTypes.arrayOf( PropTypes.shape({ y: PropTypes.number, }), ), }), ).isRequired, // number of bands in each direction (positive / negative) bands: PropTypes.number, colors: PropTypes.arrayOf(PropTypes.string), colorScale: PropTypes.string, mode: PropTypes.string, offsetX: PropTypes.number, }; const defaultProps = { className: '', width: 800, seriesHeight: 20, bands: Math.floor(DEFAULT_COLORS.length / 2), colors: DEFAULT_COLORS, colorScale: 'series', mode: 'offset', offsetX: 0, }; class HorizonChart extends React.PureComponent { render() { const { className, width, data, seriesHeight, bands, colors, colorScale, mode, offsetX, } = this.props; let yDomain; if (colorScale === 'overall') { const allValues = data.reduce((acc, current) => acc.concat(current.values), []); yDomain = d3Extent(allValues, d => d.y); } return ( <div className={`superset-legacy-chart-horizon ${className}`}> {data.map(row => ( <HorizonRow key={row.key} width={width} height={seriesHeight} title={row.key.join(', ')} data={row.values} bands={bands} colors={colors} colorScale={colorScale} mode={mode} offsetX={offsetX} yDomain={yDomain} /> ))} </div> ); } } HorizonChart.propTypes = propTypes; HorizonChart.defaultProps = defaultProps; export default HorizonChart;
superset-frontend/temporary_superset_ui/superset-ui/plugins/superset-ui-plugins/packages/superset-ui-legacy-plugin-chart-horizon/src/HorizonChart.jsx
1
https://github.com/apache/superset/commit/7019442a55adce54a3994ddf81b3bcdf6fe3c88f
[ 0.9940425753593445, 0.11798035353422165, 0.00017146165191661566, 0.0035103103145956993, 0.2874053120613098 ]
{ "id": 4, "code_window": [ " yDomain = d3Extent(allValues, d => d.y);\n", " }\n", "\n", " return (\n", " <div className={`superset-legacy-chart-horizon ${className}`}>\n", " {data.map(row => (\n", " <HorizonRow\n", " key={row.key}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <div className={`superset-legacy-chart-horizon ${className}`} style={{ height }}>\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/superset-ui-plugins/packages/superset-ui-legacy-plugin-chart-horizon/src/HorizonChart.jsx", "type": "replace", "edit_start_line_idx": 78 }
{ "name": "superset", "version": "0.0.0dev", "description": "Superset is a data exploration platform designed to be visual, intuitive, and interactive.", "keywords": [ "big", "data", "exploratory", "analysis", "react", "d3", "airbnb", "nerds", "database", "flask" ], "homepage": "https://superset.apache.org/", "bugs": { "url": "https://github.com/apache/superset/issues" }, "repository": { "type": "git", "url": "git+https://github.com/apache/superset.git" }, "license": "Apache-2.0", "author": "Apache", "directories": { "doc": "docs", "test": "spec" }, "scripts": { "build": "cross-env NODE_OPTIONS=--max_old_space_size=8192 NODE_ENV=production BABEL_ENV=\"${BABEL_ENV:=production}\" webpack --mode=production --color", "build-dev": "cross-env NODE_OPTIONS=--max_old_space_size=8192 NODE_ENV=development webpack --mode=development --color", "build-instrumented": "cross-env NODE_ENV=production BABEL_ENV=instrumented webpack --mode=production --color", "build-storybook": "build-storybook", "check-translation": "prettier --check ../superset/translations/**/LC_MESSAGES/*.json", "clean-css": "prettier --write 'src/**/*.{css,less,sass,scss}'", "clean-translation": "prettier --write ../superset/translations/**/LC_MESSAGES/*.json", "cover": "cross-env NODE_ENV=test jest --coverage", "dev": "webpack --mode=development --color --watch", "dev-server": "cross-env NODE_ENV=development BABEL_ENV=development node --max_old_space_size=4096 ./node_modules/webpack-dev-server/bin/webpack-dev-server.js --mode=development", "format": "prettier --write './{src,spec,cypress-base,plugins,packages}/**/*{.js,.jsx,.ts,.tsx,.css,.less,.scss,.sass}'", "lint": "eslint --ignore-path=.eslintignore --ext .js,.jsx,.ts,.tsx . && npm run type", "lint-fix": "eslint --fix --ignore-path=.eslintignore --ext .js,.jsx,.ts,tsx . && npm run clean-css && npm run type", "prettier": "npm run format", "prettier-check": "prettier --check 'src/**/*.{css,less,sass,scss}'", "prod": "npm run build", "prune": "rm -rf ./{packages,plugins}/*/{lib,esm,tsconfig.tsbuildinfo,package-lock.json}", "storybook": "cross-env NODE_ENV=development BABEL_ENV=development start-storybook -s ./src/assets/images -p 6006", "tdd": "cross-env NODE_ENV=test jest --watch", "test": "cross-env NODE_ENV=test jest", "type": "tsc --noEmit" }, "browserslist": [ "last 3 chrome versions", "last 3 firefox versions", "last 3 safari versions", "last 3 edge versions" ], "stylelint": { "rules": { "block-opening-brace-space-before": "always", "no-missing-end-of-source-newline": "never", "rule-empty-line-before": [ "always", { "except": [ "first-nested" ], "ignore": [ "after-comment" ] } ] } }, "dependencies": { "@ant-design/icons": "^4.2.2", "@babel/runtime-corejs3": "^7.12.5", "@data-ui/sparkline": "^0.0.84", "@emotion/babel-preset-css-prop": "^11.2.0", "@emotion/cache": "^11.4.0", "@emotion/react": "^11.4.1", "@emotion/styled": "^11.3.0", "@superset-ui/chart-controls": "^0.18.25", "@superset-ui/core": "^0.18.25", "@superset-ui/legacy-plugin-chart-calendar": "^0.18.25", "@superset-ui/legacy-plugin-chart-chord": "^0.18.25", "@superset-ui/legacy-plugin-chart-country-map": "^0.18.25", "@superset-ui/legacy-plugin-chart-event-flow": "^0.18.25", "@superset-ui/legacy-plugin-chart-force-directed": "^0.18.25", "@superset-ui/legacy-plugin-chart-heatmap": "^0.18.25", "@superset-ui/legacy-plugin-chart-histogram": "^0.18.25", "@superset-ui/legacy-plugin-chart-horizon": "^0.18.25", "@superset-ui/legacy-plugin-chart-map-box": "^0.18.25", "@superset-ui/legacy-plugin-chart-paired-t-test": "^0.18.25", "@superset-ui/legacy-plugin-chart-parallel-coordinates": "^0.18.25", "@superset-ui/legacy-plugin-chart-partition": "^0.18.25", "@superset-ui/legacy-plugin-chart-pivot-table": "^0.18.25", "@superset-ui/legacy-plugin-chart-rose": "^0.18.25", "@superset-ui/legacy-plugin-chart-sankey": "^0.18.25", "@superset-ui/legacy-plugin-chart-sankey-loop": "^0.18.25", "@superset-ui/legacy-plugin-chart-sunburst": "^0.18.25", "@superset-ui/legacy-plugin-chart-treemap": "^0.18.25", "@superset-ui/legacy-plugin-chart-world-map": "^0.18.25", "@superset-ui/legacy-preset-chart-big-number": "^0.18.25", "@superset-ui/legacy-preset-chart-deckgl": "^0.4.13", "@superset-ui/legacy-preset-chart-nvd3": "^0.18.25", "@superset-ui/plugin-chart-echarts": "^0.18.25", "@superset-ui/plugin-chart-pivot-table": "^0.18.25", "@superset-ui/plugin-chart-table": "^0.18.25", "@superset-ui/plugin-chart-word-cloud": "^0.18.25", "@superset-ui/preset-chart-xy": "^0.18.25", "@vx/responsive": "^0.0.195", "abortcontroller-polyfill": "^1.1.9", "antd": "^4.9.4", "array-move": "^2.2.1", "bootstrap": "^3.4.1", "bootstrap-slider": "^10.0.0", "brace": "^0.11.1", "chrono-node": "^2.2.6", "classnames": "^2.2.5", "core-js": "^3.6.5", "d3-array": "^1.2.4", "d3-color": "^1.2.0", "d3-scale": "^2.1.2", "dom-to-image": "^2.6.0", "emotion-rgba": "0.0.9", "fontsource-fira-code": "^3.0.5", "fontsource-inter": "^3.0.5", "fuse.js": "^6.4.6", "geolib": "^2.0.24", "global-box": "^1.2.0", "html-webpack-plugin": "^5.3.2", "immer": "^9.0.6", "interweave": "^11.2.0", "jquery": "^3.5.1", "js-levenshtein": "^1.1.6", "js-yaml-loader": "^1.2.2", "json-bigint": "^1.0.0", "json-stringify-pretty-compact": "^2.0.0", "lodash": "^4.17.21", "lodash-es": "^4.17.21", "match-sorter": "^6.1.0", "memoize-one": "^5.1.1", "moment": "^2.26.0", "moment-timezone": "^0.5.33", "mousetrap": "^1.6.1", "mustache": "^2.2.1", "omnibar": "^2.1.1", "polished": "^3.6.5", "prop-types": "^15.7.2", "query-string": "^6.13.7", "re-resizable": "^6.6.1", "react": "^16.13.1", "react-ace": "^9.4.4", "react-checkbox-tree": "^1.5.1", "react-color": "^2.13.8", "react-datetime": "^3.0.4", "react-dnd": "^11.1.3", "react-dnd-html5-backend": "^11.1.3", "react-dom": "^16.13.0", "react-draggable": "^4.4.3", "react-gravatar": "^2.6.1", "react-hot-loader": "^4.12.20", "react-js-cron": "^1.2.0", "react-json-tree": "^0.11.2", "react-jsonschema-form": "^1.2.0", "react-lines-ellipsis": "^0.15.0", "react-loadable": "^5.5.0", "react-markdown": "^4.3.1", "react-redux": "^7.2.0", "react-resize-detector": "^6.0.1-rc.1", "react-reverse-portal": "^2.0.1", "react-router-dom": "^5.1.2", "react-search-input": "^0.11.3", "react-select": "^3.1.0", "react-sortable-hoc": "^1.11.0", "react-split": "^2.0.9", "react-sticky": "^6.0.3", "react-syntax-highlighter": "^15.4.5", "react-table": "^7.6.3", "react-transition-group": "^2.5.3", "react-ultimate-pagination": "^1.2.0", "react-virtualized": "9.19.1", "react-virtualized-auto-sizer": "^1.0.2", "react-virtualized-select": "^3.1.3", "react-window": "^1.8.5", "redux": "^4.0.5", "redux-localstorage": "^0.4.1", "redux-thunk": "^2.1.0", "redux-undo": "^1.0.0-beta9-9-7", "regenerator-runtime": "^0.13.5", "rimraf": "^3.0.2", "rison": "^0.1.1", "scroll-into-view-if-needed": "^2.2.28", "shortid": "^2.2.6", "src": "file:./src", "urijs": "^1.19.6", "use-immer": "^0.6.0", "use-query-params": "^1.1.9", "yargs": "^15.4.1" }, "devDependencies": { "@babel/cli": "^7.16.0", "@babel/compat-data": "^7.15.0", "@babel/core": "^7.15.5", "@babel/eslint-parser": "^7.15.7", "@babel/node": "^7.15.4", "@babel/plugin-proposal-class-properties": "^7.14.5", "@babel/plugin-proposal-optional-chaining": "^7.14.5", "@babel/plugin-syntax-dynamic-import": "^7.8.3", "@babel/plugin-transform-runtime": "^7.15.0", "@babel/preset-env": "^7.15.6", "@babel/preset-react": "^7.14.5", "@babel/register": "^7.15.3", "@cypress/react": "^5.10.0", "@emotion/jest": "^11.3.0", "@hot-loader/react-dom": "^16.13.0", "@istanbuljs/nyc-config-typescript": "^1.0.1", "@storybook/addon-actions": "^6.3.12", "@storybook/addon-essentials": "^6.3.12", "@storybook/addon-knobs": "^6.3.1", "@storybook/addon-links": "^6.3.12", "@storybook/addons": "^6.3.12", "@storybook/builder-webpack5": "^6.3.12", "@storybook/client-api": "^6.3.12", "@storybook/manager-webpack5": "^6.3.12", "@storybook/react": "^6.3.12", "@svgr/webpack": "^5.5.0", "@testing-library/dom": "^7.29.4", "@testing-library/jest-dom": "^5.11.6", "@testing-library/react": "^11.2.0", "@testing-library/react-hooks": "^5.0.3", "@testing-library/user-event": "^12.7.0", "@types/classnames": "^2.2.10", "@types/dom-to-image": "^2.6.0", "@types/enzyme": "^3.10.5", "@types/enzyme-adapter-react-16": "^1.0.6", "@types/fetch-mock": "^7.3.2", "@types/jest": "^26.0.3", "@types/jquery": "^3.5.8", "@types/js-levenshtein": "^1.1.0", "@types/json-bigint": "^1.0.0", "@types/react": "^16.9.43", "@types/react-dom": "^16.9.8", "@types/react-gravatar": "^2.6.8", "@types/react-json-tree": "^0.6.11", "@types/react-jsonschema-form": "^1.7.4", "@types/react-loadable": "^5.5.6", "@types/react-redux": "^7.1.10", "@types/react-router-dom": "^5.1.5", "@types/react-select": "^3.0.19", "@types/react-sticky": "^6.0.3", "@types/react-table": "^7.0.19", "@types/react-ultimate-pagination": "^1.2.0", "@types/react-virtualized": "^9.21.10", "@types/react-window": "^1.8.2", "@types/redux-localstorage": "^1.0.8", "@types/redux-mock-store": "^1.0.2", "@types/rison": "0.0.6", "@types/sinon": "^9.0.5", "@types/yargs": "12 - 15", "@typescript-eslint/eslint-plugin": "^5.3.0", "@typescript-eslint/parser": "^5.3.0", "babel-jest": "^26.6.3", "babel-loader": "^8.2.2", "babel-plugin-dynamic-import-node": "^2.3.3", "babel-plugin-jsx-remove-data-test-id": "^2.1.3", "babel-plugin-lodash": "^3.3.4", "copy-webpack-plugin": "^9.0.1", "cross-env": "^5.2.0", "css-loader": "^6.2.0", "css-minimizer-webpack-plugin": "^3.0.2", "enzyme": "^3.10.0", "enzyme-adapter-react-16": "^1.14.0", "eslint": "^7.32.0", "eslint-config-airbnb": "^18.2.1", "eslint-config-prettier": "^7.1.0", "eslint-import-resolver-typescript": "^2.5.0", "eslint-import-resolver-webpack": "^0.13.2", "eslint-plugin-cypress": "^2.11.2", "eslint-plugin-file-progress": "^1.2.0", "eslint-plugin-import": "^2.24.2", "eslint-plugin-jest": "^24.1.3", "eslint-plugin-jest-dom": "^3.6.5", "eslint-plugin-jsx-a11y": "^6.4.1", "eslint-plugin-no-only-tests": "^2.4.0", "eslint-plugin-prettier": "^3.3.1", "eslint-plugin-react": "^7.22.0", "eslint-plugin-react-hooks": "^4.2.0", "eslint-plugin-testing-library": "^3.10.1", "exports-loader": "^0.7.0", "fetch-mock": "^7.7.3", "file-loader": "^6.0.0", "fork-ts-checker-webpack-plugin": "^6.3.3", "ignore-styles": "^5.0.1", "imports-loader": "^3.0.0", "jest": "^26.6.3", "jest-environment-enzyme": "^7.1.2", "jest-enzyme": "^7.1.2", "jest-websocket-mock": "^2.2.0", "jsdom": "^16.4.0", "lerna": "^3.22.1", "less": "^3.12.2", "less-loader": "^5.0.0", "mini-css-extract-plugin": "^2.3.0", "mock-socket": "^9.0.3", "node-fetch": "^2.6.1", "prettier": "^2.4.1", "prettier-plugin-packagejson": "^2.2.15", "process": "^0.11.10", "react-resizable": "^3.0.4", "react-test-renderer": "^16.9.0", "redux-mock-store": "^1.5.4", "sinon": "^9.0.2", "source-map-support": "^0.5.16", "speed-measure-webpack-plugin": "^1.5.0", "storybook-addon-jsx": "^7.3.14", "storybook-addon-paddings": "^4.2.1", "style-loader": "^3.2.1", "thread-loader": "^3.0.4", "transform-loader": "^0.2.4", "ts-jest": "^26.4.2", "ts-loader": "^9.2.5", "typescript": "^4.1.6", "webpack": "^5.52.1", "webpack-bundle-analyzer": "^4.4.2", "webpack-cli": "^4.8.0", "webpack-dev-server": "^4.2.0", "webpack-manifest-plugin": "^4.0.2", "webpack-sources": "^3.2.0" }, "engines": { "node": "^16.9.1", "npm": "^7.5.4" } }
superset-frontend/package.json
0
https://github.com/apache/superset/commit/7019442a55adce54a3994ddf81b3bcdf6fe3c88f
[ 0.00017607280460651964, 0.00017253313853871077, 0.00016414601122960448, 0.00017373505397699773, 0.0000032198515782511095 ]
{ "id": 4, "code_window": [ " yDomain = d3Extent(allValues, d => d.y);\n", " }\n", "\n", " return (\n", " <div className={`superset-legacy-chart-horizon ${className}`}>\n", " {data.map(row => (\n", " <HorizonRow\n", " key={row.key}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <div className={`superset-legacy-chart-horizon ${className}`} style={{ height }}>\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/superset-ui-plugins/packages/superset-ui-legacy-plugin-chart-horizon/src/HorizonChart.jsx", "type": "replace", "edit_start_line_idx": 78 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from typing import List, Optional from superset import ConnectorRegistry, db, security_manager from superset.models.slice import Slice class InsertChartMixin: """ Implements shared logic for tests to insert charts (slices) in the DB """ def insert_chart( self, slice_name: str, owners: List[int], datasource_id: int, created_by=None, datasource_type: str = "table", description: Optional[str] = None, viz_type: Optional[str] = None, params: Optional[str] = None, cache_timeout: Optional[int] = None, certified_by: Optional[str] = None, certification_details: Optional[str] = None, ) -> Slice: obj_owners = list() for owner in owners: user = db.session.query(security_manager.user_model).get(owner) obj_owners.append(user) datasource = ConnectorRegistry.get_datasource( datasource_type, datasource_id, db.session ) slice = Slice( cache_timeout=cache_timeout, certified_by=certified_by, certification_details=certification_details, created_by=created_by, datasource_id=datasource.id, datasource_name=datasource.name, datasource_type=datasource.type, description=description, owners=obj_owners, params=params, slice_name=slice_name, viz_type=viz_type, ) db.session.add(slice) db.session.commit() return slice
tests/integration_tests/insert_chart_mixin.py
0
https://github.com/apache/superset/commit/7019442a55adce54a3994ddf81b3bcdf6fe3c88f
[ 0.011613490991294384, 0.0018100672168657184, 0.00017129200568888336, 0.00017772852152120322, 0.004002231638878584 ]
{ "id": 4, "code_window": [ " yDomain = d3Extent(allValues, d => d.y);\n", " }\n", "\n", " return (\n", " <div className={`superset-legacy-chart-horizon ${className}`}>\n", " {data.map(row => (\n", " <HorizonRow\n", " key={row.key}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <div className={`superset-legacy-chart-horizon ${className}`} style={{ height }}>\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/superset-ui-plugins/packages/superset-ui-legacy-plugin-chart-horizon/src/HorizonChart.jsx", "type": "replace", "edit_start_line_idx": 78 }
<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" clip-rule="evenodd" d="M22.6705 17.47L14.6205 3.47C14.0906 2.52009 13.0881 1.93137 12.0005 1.93137C10.9128 1.93137 9.91029 2.52009 9.38046 3.47L1.38046 17.47C0.832506 18.3941 0.820562 19.5407 1.34914 20.476C1.87772 21.4114 2.86612 21.9927 3.94046 22H20.0605C21.1437 22.0107 22.1486 21.4365 22.6894 20.4978C23.2303 19.5591 23.223 18.4018 22.6705 17.47Z" fill="currentColor"/> <path fill-rule="evenodd" clip-rule="evenodd" d="M11 9C11 8.44772 11.4477 8 12 8C12.5523 8 13 8.44772 13 9V13C13 13.5523 12.5523 14 12 14C11.4477 14 11 13.5523 11 13V9ZM11 17C11 16.4477 11.4477 16 12 16C12.5523 16 13 16.4477 13 17C13 17.5523 12.5523 18 12 18C11.4477 18 11 17.5523 11 17Z" fill="white"/> </svg>
superset-frontend/src/assets/images/icons/alert_solid.svg
0
https://github.com/apache/superset/commit/7019442a55adce54a3994ddf81b3bcdf6fe3c88f
[ 0.00017895372002385557, 0.00017679629672784358, 0.00017555950034875423, 0.00017587566981092095, 0.0000015309794889617478 ]
{ "id": 5, "code_window": [ " * under the License.\n", " */\n", "export default function transformProps(chartProps) {\n", " const { width, formData, queryData } = chartProps;\n", " const { horizonColorScale, seriesHeight } = formData;\n", "\n", " return {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const { height, width, formData, queryData } = chartProps;\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/superset-ui-plugins/packages/superset-ui-legacy-plugin-chart-horizon/src/transformProps.js", "type": "replace", "edit_start_line_idx": 19 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* eslint-disable sort-keys */ import React from 'react'; import PropTypes from 'prop-types'; import { extent as d3Extent } from 'd3-array'; import HorizonRow, { DEFAULT_COLORS } from './HorizonRow'; import './HorizonChart.css'; const propTypes = { className: PropTypes.string, width: PropTypes.number, seriesHeight: PropTypes.number, data: PropTypes.arrayOf( PropTypes.shape({ key: PropTypes.arrayOf(PropTypes.string), values: PropTypes.arrayOf( PropTypes.shape({ y: PropTypes.number, }), ), }), ).isRequired, // number of bands in each direction (positive / negative) bands: PropTypes.number, colors: PropTypes.arrayOf(PropTypes.string), colorScale: PropTypes.string, mode: PropTypes.string, offsetX: PropTypes.number, }; const defaultProps = { className: '', width: 800, seriesHeight: 20, bands: Math.floor(DEFAULT_COLORS.length / 2), colors: DEFAULT_COLORS, colorScale: 'series', mode: 'offset', offsetX: 0, }; class HorizonChart extends React.PureComponent { render() { const { className, width, data, seriesHeight, bands, colors, colorScale, mode, offsetX, } = this.props; let yDomain; if (colorScale === 'overall') { const allValues = data.reduce((acc, current) => acc.concat(current.values), []); yDomain = d3Extent(allValues, d => d.y); } return ( <div className={`superset-legacy-chart-horizon ${className}`}> {data.map(row => ( <HorizonRow key={row.key} width={width} height={seriesHeight} title={row.key.join(', ')} data={row.values} bands={bands} colors={colors} colorScale={colorScale} mode={mode} offsetX={offsetX} yDomain={yDomain} /> ))} </div> ); } } HorizonChart.propTypes = propTypes; HorizonChart.defaultProps = defaultProps; export default HorizonChart;
superset-frontend/temporary_superset_ui/superset-ui/plugins/superset-ui-plugins/packages/superset-ui-legacy-plugin-chart-horizon/src/HorizonChart.jsx
1
https://github.com/apache/superset/commit/7019442a55adce54a3994ddf81b3bcdf6fe3c88f
[ 0.9980820417404175, 0.17910028994083405, 0.00016730907373130322, 0.00021079157886561006, 0.3786788880825043 ]
{ "id": 5, "code_window": [ " * under the License.\n", " */\n", "export default function transformProps(chartProps) {\n", " const { width, formData, queryData } = chartProps;\n", " const { horizonColorScale, seriesHeight } = formData;\n", "\n", " return {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const { height, width, formData, queryData } = chartProps;\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/superset-ui-plugins/packages/superset-ui-legacy-plugin-chart-horizon/src/transformProps.js", "type": "replace", "edit_start_line_idx": 19 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { ReactWrapper } from 'enzyme'; import { act } from 'react-dom/test-utils'; // taken from: https://github.com/enzymejs/enzyme/issues/2073 // There is currently and issue with enzyme and react-16's hooks // that results in a race condition between tests and react hook updates. // This function ensures tests run after all react updates are done. export default async function waitForComponentToPaint<P = {}>( wrapper: ReactWrapper<P>, amount = 0, ) { await act(async () => { await new Promise(resolve => setTimeout(resolve, amount)); wrapper.update(); }); }
superset-frontend/spec/helpers/waitForComponentToPaint.ts
0
https://github.com/apache/superset/commit/7019442a55adce54a3994ddf81b3bcdf6fe3c88f
[ 0.00017779327754396945, 0.00017628422938287258, 0.00017440358351450413, 0.00017647002823650837, 0.0000013323506209417246 ]
{ "id": 5, "code_window": [ " * under the License.\n", " */\n", "export default function transformProps(chartProps) {\n", " const { width, formData, queryData } = chartProps;\n", " const { horizonColorScale, seriesHeight } = formData;\n", "\n", " return {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const { height, width, formData, queryData } = chartProps;\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/superset-ui-plugins/packages/superset-ui-legacy-plugin-chart-horizon/src/transformProps.js", "type": "replace", "edit_start_line_idx": 19 }
/* eslint-disable sort-keys */ import { ChartProps } from '@superset-ui/chart'; import { flatMap } from 'lodash'; interface DataRow { key: string[]; values: { [key: string]: any; }[]; } export default function transformProps(chartProps: ChartProps) { const { width, height, formData, queryData } = chartProps; const { colorScheme, entity, maxBubbleSize, series, showLegend, size, x, xAxisFormat, xAxisLabel, // TODO: These fields are not supported yet // xAxisShowminmax, // xLogScale, y, yAxisLabel, yAxisFormat, // TODO: These fields are not supported yet // yAxisShowminmax, // yLogScale, } = formData; const data = queryData.data as DataRow[]; return { data: flatMap( data.map((row: DataRow) => row.values.map(v => ({ [x]: v[x], [y]: v[y], [series]: v[series], [size]: v[size], [entity]: v[entity], })), ), ), width, height, encoding: { x: { field: x, type: 'quantitive', format: xAxisFormat, scale: { type: 'linear', }, axis: { orient: 'bottom', title: xAxisLabel, }, }, y: { field: y, type: 'quantitative', format: yAxisFormat, scale: { type: 'linear', }, axis: { orient: 'left', title: yAxisLabel, }, }, size: { field: size, type: 'quantitative', scale: { type: 'linear', range: [0, maxBubbleSize], }, }, fill: { field: series, type: 'nominal', scale: { scheme: colorScheme, }, legend: showLegend, }, group: [{ field: entity }], }, }; }
superset-frontend/temporary_superset_ui/superset-ui/plugins/superset-ui-plugins/packages/superset-ui-preset-chart-xy/src/ScatterPlot/legacy/transformProps.ts
0
https://github.com/apache/superset/commit/7019442a55adce54a3994ddf81b3bcdf6fe3c88f
[ 0.9987590312957764, 0.20035076141357422, 0.0001689038035692647, 0.00017680530436336994, 0.39719486236572266 ]
{ "id": 5, "code_window": [ " * under the License.\n", " */\n", "export default function transformProps(chartProps) {\n", " const { width, formData, queryData } = chartProps;\n", " const { horizonColorScale, seriesHeight } = formData;\n", "\n", " return {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const { height, width, formData, queryData } = chartProps;\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/superset-ui-plugins/packages/superset-ui-legacy-plugin-chart-horizon/src/transformProps.js", "type": "replace", "edit_start_line_idx": 19 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ .dashboard { position: relative; color: @almost-black; flex-grow: 1; display: flex; flex-direction: column; } /* only top-level tabs have popover, give it more padding to match header + tabs */ .dashboard > .with-popover-menu > .popover-menu { left: 24px; } /* drop shadow for top-level tabs only */ .dashboard .dashboard-component-tabs { box-shadow: 0 4px 4px 0 fade(@darkest, @opacity-light); padding-left: 8px; /* note this is added to tab-level padding, to match header */ } .dropdown-toggle.btn.btn-primary .caret { color: @lightest; } .background--transparent { background-color: transparent; } .background--white { background-color: @lightest; }
superset-frontend/src/dashboard/stylesheets/builder.less
0
https://github.com/apache/superset/commit/7019442a55adce54a3994ddf81b3bcdf6fe3c88f
[ 0.0001793626870494336, 0.000176000758074224, 0.0001733344397507608, 0.00017568962357472628, 0.0000022122524114820408 ]
{ "id": 6, "code_window": [ " return {\n", " colorScale: horizonColorScale,\n", " data: queryData.data,\n", " seriesHeight: parseInt(seriesHeight, 10),\n", " width,\n", " };\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " height,\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/superset-ui-plugins/packages/superset-ui-legacy-plugin-chart-horizon/src/transformProps.js", "type": "add", "edit_start_line_idx": 25 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* eslint-disable sort-keys */ import React from 'react'; import PropTypes from 'prop-types'; import { extent as d3Extent } from 'd3-array'; import HorizonRow, { DEFAULT_COLORS } from './HorizonRow'; import './HorizonChart.css'; const propTypes = { className: PropTypes.string, width: PropTypes.number, seriesHeight: PropTypes.number, data: PropTypes.arrayOf( PropTypes.shape({ key: PropTypes.arrayOf(PropTypes.string), values: PropTypes.arrayOf( PropTypes.shape({ y: PropTypes.number, }), ), }), ).isRequired, // number of bands in each direction (positive / negative) bands: PropTypes.number, colors: PropTypes.arrayOf(PropTypes.string), colorScale: PropTypes.string, mode: PropTypes.string, offsetX: PropTypes.number, }; const defaultProps = { className: '', width: 800, seriesHeight: 20, bands: Math.floor(DEFAULT_COLORS.length / 2), colors: DEFAULT_COLORS, colorScale: 'series', mode: 'offset', offsetX: 0, }; class HorizonChart extends React.PureComponent { render() { const { className, width, data, seriesHeight, bands, colors, colorScale, mode, offsetX, } = this.props; let yDomain; if (colorScale === 'overall') { const allValues = data.reduce((acc, current) => acc.concat(current.values), []); yDomain = d3Extent(allValues, d => d.y); } return ( <div className={`superset-legacy-chart-horizon ${className}`}> {data.map(row => ( <HorizonRow key={row.key} width={width} height={seriesHeight} title={row.key.join(', ')} data={row.values} bands={bands} colors={colors} colorScale={colorScale} mode={mode} offsetX={offsetX} yDomain={yDomain} /> ))} </div> ); } } HorizonChart.propTypes = propTypes; HorizonChart.defaultProps = defaultProps; export default HorizonChart;
superset-frontend/temporary_superset_ui/superset-ui/plugins/superset-ui-plugins/packages/superset-ui-legacy-plugin-chart-horizon/src/HorizonChart.jsx
1
https://github.com/apache/superset/commit/7019442a55adce54a3994ddf81b3bcdf6fe3c88f
[ 0.9902023077011108, 0.16578485071659088, 0.00017561491404194385, 0.00034252129262313247, 0.3484286367893219 ]
{ "id": 6, "code_window": [ " return {\n", " colorScale: horizonColorScale,\n", " data: queryData.data,\n", " seriesHeight: parseInt(seriesHeight, 10),\n", " width,\n", " };\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " height,\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/superset-ui-plugins/packages/superset-ui-legacy-plugin-chart-horizon/src/transformProps.js", "type": "add", "edit_start_line_idx": 25 }
/* eslint-disable no-magic-numbers */ import React from 'react'; import { SuperChart } from '@superset-ui/chart'; import data from './data'; export default [ { renderStory: () => ( <SuperChart chartType="<%= packageName %>" chartProps={{ formData: {}, height: 400, payload: { data }, width: 400, }} /> ), storyName: 'Basic', storyPath: 'plugin-chart-<%= packageName %>|<%= packageLabel %>ChartPlugin', }, ];
superset-frontend/temporary_superset_ui/superset-ui/packages/generator-superset/generators/legacy-plugin-chart-demo/templates/Stories.jsx
0
https://github.com/apache/superset/commit/7019442a55adce54a3994ddf81b3bcdf6fe3c88f
[ 0.00017837603809311986, 0.00017311143164988607, 0.00016671539924573153, 0.00017424285761080682, 0.000004827194970857818 ]
{ "id": 6, "code_window": [ " return {\n", " colorScale: horizonColorScale,\n", " data: queryData.data,\n", " seriesHeight: parseInt(seriesHeight, 10),\n", " width,\n", " };\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " height,\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/superset-ui-plugins/packages/superset-ui-legacy-plugin-chart-horizon/src/transformProps.js", "type": "add", "edit_start_line_idx": 25 }
export type AnnotationLayerMetadata = { name: string; sourceType?: string; };
superset-frontend/temporary_superset_ui/superset-ui/packages/superset-ui-chart/src/types/Annotation.ts
0
https://github.com/apache/superset/commit/7019442a55adce54a3994ddf81b3bcdf6fe3c88f
[ 0.0001680328423390165, 0.0001680328423390165, 0.0001680328423390165, 0.0001680328423390165, 0 ]
{ "id": 6, "code_window": [ " return {\n", " colorScale: horizonColorScale,\n", " data: queryData.data,\n", " seriesHeight: parseInt(seriesHeight, 10),\n", " width,\n", " };\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " height,\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/superset-ui-plugins/packages/superset-ui-legacy-plugin-chart-horizon/src/transformProps.js", "type": "add", "edit_start_line_idx": 25 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. [ignore: superset-frontend/node_modules/**] [python: superset/**.py] [jinja2: superset/**/templates/**.html] [javascript: superset-frontend/src/**.js] [javascript: superset-frontend/src/**.jsx] [javascript: superset-frontend/src/**.tsx] encoding = utf-8
superset/translations/babel.cfg
0
https://github.com/apache/superset/commit/7019442a55adce54a3994ddf81b3bcdf6fe3c88f
[ 0.00017724416102282703, 0.0001765540655469522, 0.00017552250938024372, 0.00017689552623778582, 7.431768267451844e-7 ]
{ "id": 0, "code_window": [ "\tprivate async getTsConfigForActiveFile(token: vscode.CancellationToken): Promise<TSConfig[]> {\n", "\t\tconst editor = vscode.window.activeTextEditor;\n", "\t\tif (editor) {\n", "\t\t\tif (path.basename(editor.document.fileName).match(/^tsconfig\\.(.\\.)?json$/)) {\n", "\t\t\t\tconst path = editor.document.uri;\n", "\t\t\t\tconst folder = vscode.workspace.getWorkspaceFolder(path);\n", "\t\t\t\treturn [{\n", "\t\t\t\t\tpath: path.fsPath,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [], "file_path": "extensions/typescript/src/features/taskProvider.ts", "type": "replace", "edit_start_line_idx": 85 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as vscode from 'vscode'; export interface TSConfig { path: string; workspaceFolder?: vscode.WorkspaceFolder; } export default class TsConfigProvider extends vscode.Disposable { private readonly tsconfigs = new Map<string, TSConfig>(); private activated: boolean = false; private disposables: vscode.Disposable[] = []; constructor() { super(() => this.dispose()); } dispose(): void { this.disposables.forEach(d => d.dispose()); } public async getConfigsForWorkspace(): Promise<Iterable<TSConfig>> { if (!vscode.workspace.workspaceFolders) { return []; } await this.ensureActivated(); return this.tsconfigs.values(); } private async ensureActivated(): Promise<this> { if (this.activated) { return this; } this.activated = true; this.reloadWorkspaceConfigs(); const configFileWatcher = vscode.workspace.createFileSystemWatcher('**/tsconfig*.json'); this.disposables.push(configFileWatcher); configFileWatcher.onDidCreate(this.handleProjectCreate, this, this.disposables); configFileWatcher.onDidDelete(this.handleProjectDelete, this, this.disposables); vscode.workspace.onDidChangeWorkspaceFolders(() => { this.reloadWorkspaceConfigs(); }, this, this.disposables); return this; } private async reloadWorkspaceConfigs(): Promise<this> { this.tsconfigs.clear(); for (const config of await vscode.workspace.findFiles('**/tsconfig*.json', '**/node_modules/**')) { this.handleProjectCreate(config); } return this; } private handleProjectCreate(config: vscode.Uri) { const root = vscode.workspace.getWorkspaceFolder(config); if (root) { this.tsconfigs.set(config.fsPath, { path: config.fsPath, workspaceFolder: root }); } } private handleProjectDelete(e: vscode.Uri) { this.tsconfigs.delete(e.fsPath); } }
extensions/typescript/src/utils/tsconfigProvider.ts
1
https://github.com/microsoft/vscode/commit/20519a8fe1fe565cd3a7618089beba6d66266b5b
[ 0.023206369951367378, 0.005815567448735237, 0.0003931128594558686, 0.001385855837725103, 0.007606751751154661 ]
{ "id": 0, "code_window": [ "\tprivate async getTsConfigForActiveFile(token: vscode.CancellationToken): Promise<TSConfig[]> {\n", "\t\tconst editor = vscode.window.activeTextEditor;\n", "\t\tif (editor) {\n", "\t\t\tif (path.basename(editor.document.fileName).match(/^tsconfig\\.(.\\.)?json$/)) {\n", "\t\t\t\tconst path = editor.document.uri;\n", "\t\t\t\tconst folder = vscode.workspace.getWorkspaceFolder(path);\n", "\t\t\t\treturn [{\n", "\t\t\t\t\tpath: path.fsPath,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [], "file_path": "extensions/typescript/src/features/taskProvider.ts", "type": "replace", "edit_start_line_idx": 85 }
/*--------------------------------------------------------------------------------------------- * 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. { "entryAriaLabel": "{0}, Auswahlhilfe", "globalCommands": "Globale Befehle", "editorCommands": "Editor-Befehle" }
i18n/deu/src/vs/workbench/parts/quickopen/browser/helpHandler.i18n.json
0
https://github.com/microsoft/vscode/commit/20519a8fe1fe565cd3a7618089beba6d66266b5b
[ 0.00017400992510374635, 0.0001709428324829787, 0.00016787572531029582, 0.0001709428324829787, 0.000003067099896725267 ]
{ "id": 0, "code_window": [ "\tprivate async getTsConfigForActiveFile(token: vscode.CancellationToken): Promise<TSConfig[]> {\n", "\t\tconst editor = vscode.window.activeTextEditor;\n", "\t\tif (editor) {\n", "\t\t\tif (path.basename(editor.document.fileName).match(/^tsconfig\\.(.\\.)?json$/)) {\n", "\t\t\t\tconst path = editor.document.uri;\n", "\t\t\t\tconst folder = vscode.workspace.getWorkspaceFolder(path);\n", "\t\t\t\treturn [{\n", "\t\t\t\t\tpath: path.fsPath,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [], "file_path": "extensions/typescript/src/features/taskProvider.ts", "type": "replace", "edit_start_line_idx": 85 }
/*--------------------------------------------------------------------------------------------- * 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 { TPromise } from 'vs/base/common/winjs.base'; import { ICredentialsService } from 'vs/platform/credentials/common/credentials'; import * as keytarType from 'keytar'; export class CredentialsService implements ICredentialsService { _serviceBrand: any; private keytarPromise: TPromise<typeof keytarType>; readSecret(service: string, account: string): TPromise<string | undefined> { return this.getKeytar() .then(keytar => TPromise.wrap(keytar.getPassword(service, account))) .then(result => result === null ? undefined : result); } writeSecret(service: string, account: string, secret: string): TPromise<void> { return this.getKeytar() .then(keytar => TPromise.wrap(keytar.setPassword(service, account, secret))); } deleteSecret(service: string, account: string): TPromise<boolean> { return this.getKeytar() .then(keytar => TPromise.wrap(keytar.deletePassword(service, account))); } private getKeytar(): TPromise<typeof keytarType> { if (!this.keytarPromise) { this.keytarPromise = new TPromise<typeof keytarType>((c, e) => { require(['keytar'], c, e); }); } return this.keytarPromise; } }
src/vs/platform/credentials/node/credentialsService.ts
0
https://github.com/microsoft/vscode/commit/20519a8fe1fe565cd3a7618089beba6d66266b5b
[ 0.00017397590272594243, 0.0001699694839771837, 0.00016696406237315387, 0.00016934533778112382, 0.0000024554915398766752 ]
{ "id": 0, "code_window": [ "\tprivate async getTsConfigForActiveFile(token: vscode.CancellationToken): Promise<TSConfig[]> {\n", "\t\tconst editor = vscode.window.activeTextEditor;\n", "\t\tif (editor) {\n", "\t\t\tif (path.basename(editor.document.fileName).match(/^tsconfig\\.(.\\.)?json$/)) {\n", "\t\t\t\tconst path = editor.document.uri;\n", "\t\t\t\tconst folder = vscode.workspace.getWorkspaceFolder(path);\n", "\t\t\t\treturn [{\n", "\t\t\t\t\tpath: path.fsPath,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [], "file_path": "extensions/typescript/src/features/taskProvider.ts", "type": "replace", "edit_start_line_idx": 85 }
/*--------------------------------------------------------------------------------------------- * 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. { "defineKeybinding.start": "Definisci tasto di scelta rapida", "defineKeybinding.kbLayoutErrorMessage": "Non sarà possibile produrre questa combinazione di tasti con il layout di tastiera corrente.", "defineKeybinding.kbLayoutLocalAndUSMessage": "**{0}** per il layout di tastiera corrente (**{1}** per quello standard US).", "defineKeybinding.kbLayoutLocalMessage": "**{0}** per il layout di tastiera corrente." }
i18n/ita/src/vs/workbench/parts/preferences/browser/keybindingsEditorContribution.i18n.json
0
https://github.com/microsoft/vscode/commit/20519a8fe1fe565cd3a7618089beba6d66266b5b
[ 0.00017321431369055063, 0.00017008910072036088, 0.00016696388775017112, 0.00017008910072036088, 0.00000312521297018975 ]
{ "id": 1, "code_window": [ "\t\t\t\treturn [{\n", "\t\t\t\t\tpath: path.fsPath,\n", "\t\t\t\t\tworkspaceFolder: folder\n", "\t\t\t\t}];\n", "\t\t\t}\n", "\t\t}\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\tworkspaceFolder: vscode.workspace.getWorkspaceFolder(path)\n" ], "file_path": "extensions/typescript/src/features/taskProvider.ts", "type": "replace", "edit_start_line_idx": 88 }
/*--------------------------------------------------------------------------------------------- * 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 fs from 'fs'; import * as path from 'path'; import * as vscode from 'vscode'; import * as Proto from '../protocol'; import TypeScriptServiceClient from '../typescriptServiceClient'; import TsConfigProvider, { TSConfig } from '../utils/tsconfigProvider'; import { isImplicitProjectConfigFile } from '../utils/tsconfig'; import * as nls from 'vscode-nls'; const localize = nls.loadMessageBundle(); const exists = (file: string): Promise<boolean> => new Promise<boolean>((resolve, _reject) => { fs.exists(file, (value: boolean) => { resolve(value); }); }); interface TypeScriptTaskDefinition extends vscode.TaskDefinition { tsconfig: string; } /** * Provides tasks for building `tsconfig.json` files in a project. */ class TscTaskProvider implements vscode.TaskProvider { private readonly tsconfigProvider: TsConfigProvider; public constructor( private readonly lazyClient: () => TypeScriptServiceClient ) { this.tsconfigProvider = new TsConfigProvider(); } dispose() { this.tsconfigProvider.dispose(); } public async provideTasks(token: vscode.CancellationToken): Promise<vscode.Task[]> { const folders = vscode.workspace.workspaceFolders; if (!folders || !folders.length) { return []; } const configPaths: Set<string> = new Set(); const tasks: vscode.Task[] = []; for (const project of await this.getAllTsConfigs(token)) { if (!configPaths.has(project.path)) { configPaths.add(project.path); tasks.push(await this.getBuildTaskForProject(project)); } } return tasks; } public resolveTask(_task: vscode.Task): vscode.Task | undefined { return undefined; } private async getAllTsConfigs(token: vscode.CancellationToken): Promise<TSConfig[]> { const out = new Set<TSConfig>(); const configs = (await this.getTsConfigForActiveFile(token)).concat(await this.getTsConfigsInWorkspace()); for (const config of configs) { if (await exists(config.path)) { out.add(config); } } return Array.from(out); } private async getTsConfigForActiveFile(token: vscode.CancellationToken): Promise<TSConfig[]> { const editor = vscode.window.activeTextEditor; if (editor) { if (path.basename(editor.document.fileName).match(/^tsconfig\.(.\.)?json$/)) { const path = editor.document.uri; const folder = vscode.workspace.getWorkspaceFolder(path); return [{ path: path.fsPath, workspaceFolder: folder }]; } } const file = this.getActiveTypeScriptFile(); if (!file) { return []; } const res: Proto.ProjectInfoResponse = await this.lazyClient().execute( 'projectInfo', { file, needFileNameList: false } as protocol.ProjectInfoRequestArgs, token); if (!res || !res.body) { return []; } const { configFileName } = res.body; if (configFileName && !isImplicitProjectConfigFile(configFileName)) { const path = vscode.Uri.file(configFileName); const folder = vscode.workspace.getWorkspaceFolder(path); return [{ path: configFileName, workspaceFolder: folder }]; } return []; } private async getTsConfigsInWorkspace(): Promise<TSConfig[]> { return Array.from(await this.tsconfigProvider.getConfigsForWorkspace()); } private async getCommand(project: TSConfig): Promise<string> { if (project.workspaceFolder) { const platform = process.platform; const bin = path.join(project.workspaceFolder.uri.fsPath, 'node_modules', '.bin'); if (platform === 'win32' && await exists(path.join(bin, 'tsc.cmd'))) { return path.join(bin, 'tsc.cmd'); } else if ((platform === 'linux' || platform === 'darwin') && await exists(path.join(bin, 'tsc'))) { return path.join(bin, 'tsc'); } } return 'tsc'; } private shouldUseWatchForBuild(configFile: TSConfig): boolean { try { const config = JSON.parse(fs.readFileSync(configFile.path, 'utf-8')); if (config) { return !!config.compileOnSave; } } catch (e) { // noop } return false; } private getActiveTypeScriptFile(): string | null { const editor = vscode.window.activeTextEditor; if (editor) { const document = editor.document; if (document && (document.languageId === 'typescript' || document.languageId === 'typescriptreact')) { return this.lazyClient().normalizePath(document.uri); } } return null; } private async getBuildTaskForProject(project: TSConfig): Promise<vscode.Task> { const command = await this.getCommand(project); let label: string = project.path; if (project.workspaceFolder) { const relativePath = path.relative(project.workspaceFolder.uri.fsPath, project.path); if (vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders.length > 1) { label = path.join(project.workspaceFolder.name, relativePath); } else { label = relativePath; } } const watch = this.shouldUseWatchForBuild(project); const identifier: TypeScriptTaskDefinition = { type: 'typescript', tsconfig: label, watch: watch }; const buildTask = new vscode.Task( identifier, watch ? localize('buildAndWatchTscLabel', 'watch - {0}', label) : localize('buildTscLabel', 'build - {0}', label), 'tsc', new vscode.ShellExecution(`${command} ${watch ? '--watch' : ''} -p "${project.path}"`), '$tsc'); buildTask.group = vscode.TaskGroup.Build; return buildTask; } } type AutoDetect = 'on' | 'off'; /** * Manages registrations of TypeScript task provides with VScode. */ export default class TypeScriptTaskProviderManager { private taskProviderSub: vscode.Disposable | undefined = undefined; private readonly disposables: vscode.Disposable[] = []; constructor( private readonly lazyClient: () => TypeScriptServiceClient ) { vscode.workspace.onDidChangeConfiguration(this.onConfigurationChanged, this, this.disposables); this.onConfigurationChanged(); } dispose() { if (this.taskProviderSub) { this.taskProviderSub.dispose(); this.taskProviderSub = undefined; } this.disposables.forEach(x => x.dispose()); } private onConfigurationChanged() { let autoDetect = vscode.workspace.getConfiguration('typescript.tsc').get<AutoDetect>('autoDetect'); if (this.taskProviderSub && autoDetect === 'off') { this.taskProviderSub.dispose(); this.taskProviderSub = undefined; } else if (!this.taskProviderSub && autoDetect === 'on') { this.taskProviderSub = vscode.workspace.registerTaskProvider('typescript', new TscTaskProvider(this.lazyClient)); } } }
extensions/typescript/src/features/taskProvider.ts
1
https://github.com/microsoft/vscode/commit/20519a8fe1fe565cd3a7618089beba6d66266b5b
[ 0.3695117235183716, 0.017133010551333427, 0.00016500249330420047, 0.00017201906302943826, 0.07516272366046906 ]
{ "id": 1, "code_window": [ "\t\t\t\treturn [{\n", "\t\t\t\t\tpath: path.fsPath,\n", "\t\t\t\t\tworkspaceFolder: folder\n", "\t\t\t\t}];\n", "\t\t\t}\n", "\t\t}\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\tworkspaceFolder: vscode.workspace.getWorkspaceFolder(path)\n" ], "file_path": "extensions/typescript/src/features/taskProvider.ts", "type": "replace", "edit_start_line_idx": 88 }
/*--------------------------------------------------------------------------------------------- * 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. { "updateNow": "立即更新", "later": "稍後", "unassigned": "未指派", "releaseNotes": "版本資訊", "showReleaseNotes": "顯示版本資訊", "downloadNow": "立即下載", "read the release notes": "歡迎使用 {0} v{1}! 您要閱讀版本資訊嗎?", "licenseChanged": "授權條款已有所變更,請仔細閱讀。", "license": "閱讀授權", "neveragain": "不要再顯示", "learn more": "深入了解", "thereIsUpdateAvailable": "已有更新可用。", "updateAvailable": "{0} 重新啟動後將會更新。", "noUpdatesAvailable": "目前沒有可用的更新。", "commandPalette": "命令選擇區...", "settings": "設定", "keyboardShortcuts": "鍵盤快速鍵(&&K)", "selectTheme.label": "色彩佈景主題", "themes.selectIconTheme.label": "檔案圖示佈景主題", "not available": "無可用更新", "checkingForUpdates": "正在查看是否有更新...", "DownloadUpdate": "下載可用更新", "DownloadingUpdate": "正在下載更新...", "InstallingUpdate": "正在安裝更新...", "restartToUpdate": "請重新啟動以更新...", "checkForUpdates": "查看是否有更新..." }
i18n/cht/src/vs/workbench/parts/update/electron-browser/update.i18n.json
0
https://github.com/microsoft/vscode/commit/20519a8fe1fe565cd3a7618089beba6d66266b5b
[ 0.00017368765838909894, 0.00016950596182141453, 0.0001659950939938426, 0.00016917054017540067, 0.000002749749683061964 ]
{ "id": 1, "code_window": [ "\t\t\t\treturn [{\n", "\t\t\t\t\tpath: path.fsPath,\n", "\t\t\t\t\tworkspaceFolder: folder\n", "\t\t\t\t}];\n", "\t\t\t}\n", "\t\t}\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\tworkspaceFolder: vscode.workspace.getWorkspaceFolder(path)\n" ], "file_path": "extensions/typescript/src/features/taskProvider.ts", "type": "replace", "edit_start_line_idx": 88 }
/*--------------------------------------------------------------------------------------------- * 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. { "textFileEditor": "Éditeur de fichier texte", "createFile": "Créer un fichier", "fileEditorWithInputAriaLabel": "{0}. Éditeur de fichier texte.", "fileEditorAriaLabel": "Éditeur de fichier texte." }
i18n/fra/src/vs/workbench/parts/files/browser/editors/textFileEditor.i18n.json
0
https://github.com/microsoft/vscode/commit/20519a8fe1fe565cd3a7618089beba6d66266b5b
[ 0.00017654302064329386, 0.0001746768393786624, 0.00017281065811403096, 0.0001746768393786624, 0.0000018661812646314502 ]
{ "id": 1, "code_window": [ "\t\t\t\treturn [{\n", "\t\t\t\t\tpath: path.fsPath,\n", "\t\t\t\t\tworkspaceFolder: folder\n", "\t\t\t\t}];\n", "\t\t\t}\n", "\t\t}\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\tworkspaceFolder: vscode.workspace.getWorkspaceFolder(path)\n" ], "file_path": "extensions/typescript/src/features/taskProvider.ts", "type": "replace", "edit_start_line_idx": 88 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .monaco-keybinding { display: flex; align-items: center; line-height: 10px; } .monaco-keybinding > .monaco-keybinding-key { display: inline-block; border: solid 1px rgba(204, 204, 204, 0.4); border-bottom-color: rgba(187, 187, 187, 0.4); border-radius: 3px; box-shadow: inset 0 -1px 0 rgba(187, 187, 187, 0.4); background-color: rgba(221, 221, 221, 0.4); vertical-align: middle; color: #555; font-size: 11px; padding: 3px 5px; } .hc-black .monaco-keybinding > .monaco-keybinding-key, .vs-dark .monaco-keybinding > .monaco-keybinding-key { background-color: rgba(128, 128, 128, 0.17); color: #ccc; border: solid 1px rgba(51, 51, 51, 0.6); border-bottom-color: rgba(68, 68, 68, 0.6); box-shadow: inset 0 -1px 0 rgba(68, 68, 68, 0.6); } .monaco-keybinding > .monaco-keybinding-key-separator { display: inline-block; } .monaco-keybinding > .monaco-keybinding-key-chord-separator { width: 2px; }
src/vs/base/browser/ui/keybindingLabel/keybindingLabel.css
0
https://github.com/microsoft/vscode/commit/20519a8fe1fe565cd3a7618089beba6d66266b5b
[ 0.00017684190243016928, 0.00016855067224241793, 0.00016176945064216852, 0.0001671958452789113, 0.000005741392214986263 ]
{ "id": 2, "code_window": [ "\t\tif (!file) {\n", "\t\t\treturn [];\n", "\t\t}\n", "\n", "\t\tconst res: Proto.ProjectInfoResponse = await this.lazyClient().execute(\n", "\t\t\t'projectInfo',\n", "\t\t\t{ file, needFileNameList: false } as protocol.ProjectInfoRequestArgs,\n", "\t\t\ttoken);\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\ttry {\n", "\t\t\tconst res: Proto.ProjectInfoResponse = await this.lazyClient().execute(\n", "\t\t\t\t'projectInfo',\n", "\t\t\t\t{ file, needFileNameList: false } as protocol.ProjectInfoRequestArgs,\n", "\t\t\t\ttoken);\n" ], "file_path": "extensions/typescript/src/features/taskProvider.ts", "type": "replace", "edit_start_line_idx": 98 }
/*--------------------------------------------------------------------------------------------- * 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 fs from 'fs'; import * as path from 'path'; import * as vscode from 'vscode'; import * as Proto from '../protocol'; import TypeScriptServiceClient from '../typescriptServiceClient'; import TsConfigProvider, { TSConfig } from '../utils/tsconfigProvider'; import { isImplicitProjectConfigFile } from '../utils/tsconfig'; import * as nls from 'vscode-nls'; const localize = nls.loadMessageBundle(); const exists = (file: string): Promise<boolean> => new Promise<boolean>((resolve, _reject) => { fs.exists(file, (value: boolean) => { resolve(value); }); }); interface TypeScriptTaskDefinition extends vscode.TaskDefinition { tsconfig: string; } /** * Provides tasks for building `tsconfig.json` files in a project. */ class TscTaskProvider implements vscode.TaskProvider { private readonly tsconfigProvider: TsConfigProvider; public constructor( private readonly lazyClient: () => TypeScriptServiceClient ) { this.tsconfigProvider = new TsConfigProvider(); } dispose() { this.tsconfigProvider.dispose(); } public async provideTasks(token: vscode.CancellationToken): Promise<vscode.Task[]> { const folders = vscode.workspace.workspaceFolders; if (!folders || !folders.length) { return []; } const configPaths: Set<string> = new Set(); const tasks: vscode.Task[] = []; for (const project of await this.getAllTsConfigs(token)) { if (!configPaths.has(project.path)) { configPaths.add(project.path); tasks.push(await this.getBuildTaskForProject(project)); } } return tasks; } public resolveTask(_task: vscode.Task): vscode.Task | undefined { return undefined; } private async getAllTsConfigs(token: vscode.CancellationToken): Promise<TSConfig[]> { const out = new Set<TSConfig>(); const configs = (await this.getTsConfigForActiveFile(token)).concat(await this.getTsConfigsInWorkspace()); for (const config of configs) { if (await exists(config.path)) { out.add(config); } } return Array.from(out); } private async getTsConfigForActiveFile(token: vscode.CancellationToken): Promise<TSConfig[]> { const editor = vscode.window.activeTextEditor; if (editor) { if (path.basename(editor.document.fileName).match(/^tsconfig\.(.\.)?json$/)) { const path = editor.document.uri; const folder = vscode.workspace.getWorkspaceFolder(path); return [{ path: path.fsPath, workspaceFolder: folder }]; } } const file = this.getActiveTypeScriptFile(); if (!file) { return []; } const res: Proto.ProjectInfoResponse = await this.lazyClient().execute( 'projectInfo', { file, needFileNameList: false } as protocol.ProjectInfoRequestArgs, token); if (!res || !res.body) { return []; } const { configFileName } = res.body; if (configFileName && !isImplicitProjectConfigFile(configFileName)) { const path = vscode.Uri.file(configFileName); const folder = vscode.workspace.getWorkspaceFolder(path); return [{ path: configFileName, workspaceFolder: folder }]; } return []; } private async getTsConfigsInWorkspace(): Promise<TSConfig[]> { return Array.from(await this.tsconfigProvider.getConfigsForWorkspace()); } private async getCommand(project: TSConfig): Promise<string> { if (project.workspaceFolder) { const platform = process.platform; const bin = path.join(project.workspaceFolder.uri.fsPath, 'node_modules', '.bin'); if (platform === 'win32' && await exists(path.join(bin, 'tsc.cmd'))) { return path.join(bin, 'tsc.cmd'); } else if ((platform === 'linux' || platform === 'darwin') && await exists(path.join(bin, 'tsc'))) { return path.join(bin, 'tsc'); } } return 'tsc'; } private shouldUseWatchForBuild(configFile: TSConfig): boolean { try { const config = JSON.parse(fs.readFileSync(configFile.path, 'utf-8')); if (config) { return !!config.compileOnSave; } } catch (e) { // noop } return false; } private getActiveTypeScriptFile(): string | null { const editor = vscode.window.activeTextEditor; if (editor) { const document = editor.document; if (document && (document.languageId === 'typescript' || document.languageId === 'typescriptreact')) { return this.lazyClient().normalizePath(document.uri); } } return null; } private async getBuildTaskForProject(project: TSConfig): Promise<vscode.Task> { const command = await this.getCommand(project); let label: string = project.path; if (project.workspaceFolder) { const relativePath = path.relative(project.workspaceFolder.uri.fsPath, project.path); if (vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders.length > 1) { label = path.join(project.workspaceFolder.name, relativePath); } else { label = relativePath; } } const watch = this.shouldUseWatchForBuild(project); const identifier: TypeScriptTaskDefinition = { type: 'typescript', tsconfig: label, watch: watch }; const buildTask = new vscode.Task( identifier, watch ? localize('buildAndWatchTscLabel', 'watch - {0}', label) : localize('buildTscLabel', 'build - {0}', label), 'tsc', new vscode.ShellExecution(`${command} ${watch ? '--watch' : ''} -p "${project.path}"`), '$tsc'); buildTask.group = vscode.TaskGroup.Build; return buildTask; } } type AutoDetect = 'on' | 'off'; /** * Manages registrations of TypeScript task provides with VScode. */ export default class TypeScriptTaskProviderManager { private taskProviderSub: vscode.Disposable | undefined = undefined; private readonly disposables: vscode.Disposable[] = []; constructor( private readonly lazyClient: () => TypeScriptServiceClient ) { vscode.workspace.onDidChangeConfiguration(this.onConfigurationChanged, this, this.disposables); this.onConfigurationChanged(); } dispose() { if (this.taskProviderSub) { this.taskProviderSub.dispose(); this.taskProviderSub = undefined; } this.disposables.forEach(x => x.dispose()); } private onConfigurationChanged() { let autoDetect = vscode.workspace.getConfiguration('typescript.tsc').get<AutoDetect>('autoDetect'); if (this.taskProviderSub && autoDetect === 'off') { this.taskProviderSub.dispose(); this.taskProviderSub = undefined; } else if (!this.taskProviderSub && autoDetect === 'on') { this.taskProviderSub = vscode.workspace.registerTaskProvider('typescript', new TscTaskProvider(this.lazyClient)); } } }
extensions/typescript/src/features/taskProvider.ts
1
https://github.com/microsoft/vscode/commit/20519a8fe1fe565cd3a7618089beba6d66266b5b
[ 0.9969630837440491, 0.08679293841123581, 0.00016434176359325647, 0.00017474898777436465, 0.2806350290775299 ]
{ "id": 2, "code_window": [ "\t\tif (!file) {\n", "\t\t\treturn [];\n", "\t\t}\n", "\n", "\t\tconst res: Proto.ProjectInfoResponse = await this.lazyClient().execute(\n", "\t\t\t'projectInfo',\n", "\t\t\t{ file, needFileNameList: false } as protocol.ProjectInfoRequestArgs,\n", "\t\t\ttoken);\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\ttry {\n", "\t\t\tconst res: Proto.ProjectInfoResponse = await this.lazyClient().execute(\n", "\t\t\t\t'projectInfo',\n", "\t\t\t\t{ file, needFileNameList: false } as protocol.ProjectInfoRequestArgs,\n", "\t\t\t\ttoken);\n" ], "file_path": "extensions/typescript/src/features/taskProvider.ts", "type": "replace", "edit_start_line_idx": 98 }
/*--------------------------------------------------------------------------------------------- * 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. { "open": "設定を開く", "close": "閉じる", "saveAndRetry": "設定を保存して再試行", "errorInvalidConfiguration": "設定を書き込めません。**User Settings** を開いて、ファイル内のエラー/警告を修正してからもう一度お試しください。", "errorInvalidConfigurationWorkspace": "設定を書き込めません。**Workspace Settings** を開いて、ファイル内のエラー/警告を修正してからもう一度お試しください。", "errorConfigurationFileDirty": "ファイルが変更されているため、設定を書き込めません。**User Settings** ファイルを保存してから、もう一度お試しください。", "errorConfigurationFileDirtyWorkspace": "ファイルが変更されているため、設定を書き込めません。**Workspace Settings** ファイルを保存してから、もう一度お試しください。", "userTarget": "ユーザー設定", "workspaceTarget": "ワークスペースの設定" }
i18n/jpn/src/vs/workbench/services/configuration/node/configurationEditingService.i18n.json
0
https://github.com/microsoft/vscode/commit/20519a8fe1fe565cd3a7618089beba6d66266b5b
[ 0.00017095002112910151, 0.00016793591203168035, 0.00016492180293425918, 0.00016793591203168035, 0.0000030141090974211693 ]
{ "id": 2, "code_window": [ "\t\tif (!file) {\n", "\t\t\treturn [];\n", "\t\t}\n", "\n", "\t\tconst res: Proto.ProjectInfoResponse = await this.lazyClient().execute(\n", "\t\t\t'projectInfo',\n", "\t\t\t{ file, needFileNameList: false } as protocol.ProjectInfoRequestArgs,\n", "\t\t\ttoken);\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\ttry {\n", "\t\t\tconst res: Proto.ProjectInfoResponse = await this.lazyClient().execute(\n", "\t\t\t\t'projectInfo',\n", "\t\t\t\t{ file, needFileNameList: false } as protocol.ProjectInfoRequestArgs,\n", "\t\t\t\ttoken);\n" ], "file_path": "extensions/typescript/src/features/taskProvider.ts", "type": "replace", "edit_start_line_idx": 98 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; var path = require('path'); var fs = require('fs'); var plist = require('fast-plist'); var mappings = { "background": ["editor.background"], "foreground": ["editor.foreground"], "hoverHighlight": ["editor.hoverHighlightBackground"], "linkForeground": ["editorLink.foreground"], "selection": ["editor.selectionBackground"], "inactiveSelection": ["editor.inactiveSelectionBackground"], "selectionHighlightColor": ["editor.selectionHighlightBackground"], "wordHighlight": ["editor.wordHighlightBackground"], "wordHighlightStrong": ["editor.wordHighlightStrongBackground"], "findMatchHighlight": ["editor.findMatchHighlightBackground", "peekViewResult.matchHighlightBackground"], "currentFindMatchHighlight": ["editor.findMatchBackground"], "findRangeHighlight": ["editor.findRangeHighlightBackground"], "referenceHighlight": ["peekViewEditor.matchHighlightBackground"], "lineHighlight": ["editor.lineHighlightBackground"], "rangeHighlight": ["editor.rangeHighlightBackground"], "caret": ["editorCursor.foreground"], "invisibles": ["editorWhitespace.foreground"], "guide": ["editorIndentGuide.background"], "ansiBlack": ["terminal.ansiBlack"], "ansiRed": ["terminal.ansiRed"], "ansiGreen": ["terminal.ansiGreen"], "ansiYellow": ["terminal.ansiYellow"], "ansiBlue": ["terminal.ansiBlue"], "ansiMagenta": ["terminal.ansiMagenta"], "ansiCyan": ["terminal.ansiCyan"], "ansiWhite": ["terminal.ansiWhite"], "ansiBrightBlack": ["terminal.ansiBrightBlack"], "ansiBrightRed": ["terminal.ansiBrightRed"], "ansiBrightGreen": ["terminal.ansiBrightGreen"], "ansiBrightYellow": ["terminal.ansiBrightYellow"], "ansiBrightBlue": ["terminal.ansiBrightBlue"], "ansiBrightMagenta": ["terminal.ansiBrightMagenta"], "ansiBrightCyan": ["terminal.ansiBrightCyan"], "ansiBrightWhite": ["terminal.ansiBrightWhite"] }; exports.update = function (srcName, destName) { try { console.log('reading ', srcName); let result = {}; let plistContent = fs.readFileSync(srcName).toString(); let theme = plist.parse(plistContent); let settings = theme.settings; if (Array.isArray(settings)) { let colorMap = {}; for (let entry of settings) { let scope = entry.scope; if (scope) { let parts = scope.split(',').map(p => p.trim()); if (parts.length > 1) { entry.scope = parts; } } else { var entrySettings = entry.settings; for (let entry in entrySettings) { let mapping = mappings[entry]; if (mapping) { for (let newKey of mapping) { colorMap[newKey] = entrySettings[entry]; } if (entry !== 'foreground' && entry !== 'background') { delete entrySettings[entry]; } } } } } result.name = theme.name; result.tokenColors = settings; result.colors = colorMap; } fs.writeFileSync(destName, JSON.stringify(result, null, '\t')); } catch (e) { console.log(e); } }; if (path.basename(process.argv[1]) === 'update-theme.js') { exports.update(process.argv[2], process.argv[3]); }
build/npm/update-theme.js
0
https://github.com/microsoft/vscode/commit/20519a8fe1fe565cd3a7618089beba6d66266b5b
[ 0.00017544603906571865, 0.00017391215078532696, 0.00017067266162484884, 0.00017463705444242805, 0.0000016635320889690774 ]
{ "id": 2, "code_window": [ "\t\tif (!file) {\n", "\t\t\treturn [];\n", "\t\t}\n", "\n", "\t\tconst res: Proto.ProjectInfoResponse = await this.lazyClient().execute(\n", "\t\t\t'projectInfo',\n", "\t\t\t{ file, needFileNameList: false } as protocol.ProjectInfoRequestArgs,\n", "\t\t\ttoken);\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\ttry {\n", "\t\t\tconst res: Proto.ProjectInfoResponse = await this.lazyClient().execute(\n", "\t\t\t\t'projectInfo',\n", "\t\t\t\t{ file, needFileNameList: false } as protocol.ProjectInfoRequestArgs,\n", "\t\t\t\ttoken);\n" ], "file_path": "extensions/typescript/src/features/taskProvider.ts", "type": "replace", "edit_start_line_idx": 98 }
/*--------------------------------------------------------------------------------------------- * 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. { "TaskDefinition.description": "Der tatsächliche Aufgabentyp", "TaskDefinition.properties": "Zusätzliche Eigenschaften des Aufgabentyps", "TaskTypeConfiguration.noType": "In der Konfiguration des Aufgabentyps fehlt die erforderliche taskType-Eigenschaft.", "TaskDefinitionExtPoint": "Trägt Aufgabenarten bei" }
i18n/deu/src/vs/workbench/parts/tasks/common/taskDefinitionRegistry.i18n.json
0
https://github.com/microsoft/vscode/commit/20519a8fe1fe565cd3a7618089beba6d66266b5b
[ 0.00017772377759683877, 0.0001750946103129536, 0.00017246545758098364, 0.0001750946103129536, 0.0000026291600079275668 ]
{ "id": 3, "code_window": [ "\n", "\t\tif (!res || !res.body) {\n", "\t\t\treturn [];\n", "\t\t}\n", "\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\t\tif (!res || !res.body) {\n", "\t\t\t\treturn [];\n", "\t\t\t}\n" ], "file_path": "extensions/typescript/src/features/taskProvider.ts", "type": "replace", "edit_start_line_idx": 103 }
/*--------------------------------------------------------------------------------------------- * 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 fs from 'fs'; import * as path from 'path'; import * as vscode from 'vscode'; import * as Proto from '../protocol'; import TypeScriptServiceClient from '../typescriptServiceClient'; import TsConfigProvider, { TSConfig } from '../utils/tsconfigProvider'; import { isImplicitProjectConfigFile } from '../utils/tsconfig'; import * as nls from 'vscode-nls'; const localize = nls.loadMessageBundle(); const exists = (file: string): Promise<boolean> => new Promise<boolean>((resolve, _reject) => { fs.exists(file, (value: boolean) => { resolve(value); }); }); interface TypeScriptTaskDefinition extends vscode.TaskDefinition { tsconfig: string; } /** * Provides tasks for building `tsconfig.json` files in a project. */ class TscTaskProvider implements vscode.TaskProvider { private readonly tsconfigProvider: TsConfigProvider; public constructor( private readonly lazyClient: () => TypeScriptServiceClient ) { this.tsconfigProvider = new TsConfigProvider(); } dispose() { this.tsconfigProvider.dispose(); } public async provideTasks(token: vscode.CancellationToken): Promise<vscode.Task[]> { const folders = vscode.workspace.workspaceFolders; if (!folders || !folders.length) { return []; } const configPaths: Set<string> = new Set(); const tasks: vscode.Task[] = []; for (const project of await this.getAllTsConfigs(token)) { if (!configPaths.has(project.path)) { configPaths.add(project.path); tasks.push(await this.getBuildTaskForProject(project)); } } return tasks; } public resolveTask(_task: vscode.Task): vscode.Task | undefined { return undefined; } private async getAllTsConfigs(token: vscode.CancellationToken): Promise<TSConfig[]> { const out = new Set<TSConfig>(); const configs = (await this.getTsConfigForActiveFile(token)).concat(await this.getTsConfigsInWorkspace()); for (const config of configs) { if (await exists(config.path)) { out.add(config); } } return Array.from(out); } private async getTsConfigForActiveFile(token: vscode.CancellationToken): Promise<TSConfig[]> { const editor = vscode.window.activeTextEditor; if (editor) { if (path.basename(editor.document.fileName).match(/^tsconfig\.(.\.)?json$/)) { const path = editor.document.uri; const folder = vscode.workspace.getWorkspaceFolder(path); return [{ path: path.fsPath, workspaceFolder: folder }]; } } const file = this.getActiveTypeScriptFile(); if (!file) { return []; } const res: Proto.ProjectInfoResponse = await this.lazyClient().execute( 'projectInfo', { file, needFileNameList: false } as protocol.ProjectInfoRequestArgs, token); if (!res || !res.body) { return []; } const { configFileName } = res.body; if (configFileName && !isImplicitProjectConfigFile(configFileName)) { const path = vscode.Uri.file(configFileName); const folder = vscode.workspace.getWorkspaceFolder(path); return [{ path: configFileName, workspaceFolder: folder }]; } return []; } private async getTsConfigsInWorkspace(): Promise<TSConfig[]> { return Array.from(await this.tsconfigProvider.getConfigsForWorkspace()); } private async getCommand(project: TSConfig): Promise<string> { if (project.workspaceFolder) { const platform = process.platform; const bin = path.join(project.workspaceFolder.uri.fsPath, 'node_modules', '.bin'); if (platform === 'win32' && await exists(path.join(bin, 'tsc.cmd'))) { return path.join(bin, 'tsc.cmd'); } else if ((platform === 'linux' || platform === 'darwin') && await exists(path.join(bin, 'tsc'))) { return path.join(bin, 'tsc'); } } return 'tsc'; } private shouldUseWatchForBuild(configFile: TSConfig): boolean { try { const config = JSON.parse(fs.readFileSync(configFile.path, 'utf-8')); if (config) { return !!config.compileOnSave; } } catch (e) { // noop } return false; } private getActiveTypeScriptFile(): string | null { const editor = vscode.window.activeTextEditor; if (editor) { const document = editor.document; if (document && (document.languageId === 'typescript' || document.languageId === 'typescriptreact')) { return this.lazyClient().normalizePath(document.uri); } } return null; } private async getBuildTaskForProject(project: TSConfig): Promise<vscode.Task> { const command = await this.getCommand(project); let label: string = project.path; if (project.workspaceFolder) { const relativePath = path.relative(project.workspaceFolder.uri.fsPath, project.path); if (vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders.length > 1) { label = path.join(project.workspaceFolder.name, relativePath); } else { label = relativePath; } } const watch = this.shouldUseWatchForBuild(project); const identifier: TypeScriptTaskDefinition = { type: 'typescript', tsconfig: label, watch: watch }; const buildTask = new vscode.Task( identifier, watch ? localize('buildAndWatchTscLabel', 'watch - {0}', label) : localize('buildTscLabel', 'build - {0}', label), 'tsc', new vscode.ShellExecution(`${command} ${watch ? '--watch' : ''} -p "${project.path}"`), '$tsc'); buildTask.group = vscode.TaskGroup.Build; return buildTask; } } type AutoDetect = 'on' | 'off'; /** * Manages registrations of TypeScript task provides with VScode. */ export default class TypeScriptTaskProviderManager { private taskProviderSub: vscode.Disposable | undefined = undefined; private readonly disposables: vscode.Disposable[] = []; constructor( private readonly lazyClient: () => TypeScriptServiceClient ) { vscode.workspace.onDidChangeConfiguration(this.onConfigurationChanged, this, this.disposables); this.onConfigurationChanged(); } dispose() { if (this.taskProviderSub) { this.taskProviderSub.dispose(); this.taskProviderSub = undefined; } this.disposables.forEach(x => x.dispose()); } private onConfigurationChanged() { let autoDetect = vscode.workspace.getConfiguration('typescript.tsc').get<AutoDetect>('autoDetect'); if (this.taskProviderSub && autoDetect === 'off') { this.taskProviderSub.dispose(); this.taskProviderSub = undefined; } else if (!this.taskProviderSub && autoDetect === 'on') { this.taskProviderSub = vscode.workspace.registerTaskProvider('typescript', new TscTaskProvider(this.lazyClient)); } } }
extensions/typescript/src/features/taskProvider.ts
1
https://github.com/microsoft/vscode/commit/20519a8fe1fe565cd3a7618089beba6d66266b5b
[ 0.9312381148338318, 0.04079262539744377, 0.00016622872499283403, 0.00017110510088969022, 0.18984471261501312 ]
{ "id": 3, "code_window": [ "\n", "\t\tif (!res || !res.body) {\n", "\t\t\treturn [];\n", "\t\t}\n", "\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\t\tif (!res || !res.body) {\n", "\t\t\t\treturn [];\n", "\t\t\t}\n" ], "file_path": "extensions/typescript/src/features/taskProvider.ts", "type": "replace", "edit_start_line_idx": 103 }
/*--------------------------------------------------------------------------------------------- * 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. { "developer": "開發人員", "file": "檔案" }
i18n/cht/src/vs/workbench/electron-browser/workbench.i18n.json
0
https://github.com/microsoft/vscode/commit/20519a8fe1fe565cd3a7618089beba6d66266b5b
[ 0.0001777978613972664, 0.0001777978613972664, 0.0001777978613972664, 0.0001777978613972664, 0 ]
{ "id": 3, "code_window": [ "\n", "\t\tif (!res || !res.body) {\n", "\t\t\treturn [];\n", "\t\t}\n", "\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\t\tif (!res || !res.body) {\n", "\t\t\t\treturn [];\n", "\t\t\t}\n" ], "file_path": "extensions/typescript/src/features/taskProvider.ts", "type": "replace", "edit_start_line_idx": 103 }
/*--------------------------------------------------------------------------------------------- * 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. { "terminal.integrated.chooseWindowsShellInfo": "사용자 지정 단추를 선택하여 기본 터미널 셸을 변경할 수 있습니다.", "customize": "사용자 지정", "cancel": "취소", "never again": "다시 표시 안 함", "terminal.integrated.chooseWindowsShell": "기본으로 설정할 터미널 셸을 선택하세요. 나중에 설정에서 이 셸을 변경할 수 있습니다.", "terminalService.terminalCloseConfirmationSingular": "활성 터미널 세션이 있습니다. 종료할까요?", "terminalService.terminalCloseConfirmationPlural": "{0}개의 활성 터미널 세션이 있습니다. 종료할까요?", "yes": "예" }
i18n/kor/src/vs/workbench/parts/terminal/electron-browser/terminalService.i18n.json
0
https://github.com/microsoft/vscode/commit/20519a8fe1fe565cd3a7618089beba6d66266b5b
[ 0.0001721229200484231, 0.00016875186702236533, 0.00016538082854822278, 0.00016875186702236533, 0.0000033710457501001656 ]
{ "id": 3, "code_window": [ "\n", "\t\tif (!res || !res.body) {\n", "\t\t\treturn [];\n", "\t\t}\n", "\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\t\tif (!res || !res.body) {\n", "\t\t\t\treturn [];\n", "\t\t\t}\n" ], "file_path": "extensions/typescript/src/features/taskProvider.ts", "type": "replace", "edit_start_line_idx": 103 }
/*--------------------------------------------------------------------------------------------- * 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. { "ariaCompositeToolbarLabel": "{0} acciones", "titleTooltip": "{0} ({1})" }
i18n/esn/src/vs/workbench/browser/parts/compositePart.i18n.json
0
https://github.com/microsoft/vscode/commit/20519a8fe1fe565cd3a7618089beba6d66266b5b
[ 0.00017738688620738685, 0.00017738688620738685, 0.00017738688620738685, 0.00017738688620738685, 0 ]
{ "id": 4, "code_window": [ "\n", "\t\tconst { configFileName } = res.body;\n", "\t\tif (configFileName && !isImplicitProjectConfigFile(configFileName)) {\n", "\t\t\tconst path = vscode.Uri.file(configFileName);\n", "\t\t\tconst folder = vscode.workspace.getWorkspaceFolder(path);\n", "\t\t\treturn [{\n", "\t\t\t\tpath: configFileName,\n", "\t\t\t\tworkspaceFolder: folder\n", "\t\t\t}];\n", "\t\t}\n", "\t\treturn [];\n", "\t}\n", "\n", "\tprivate async getTsConfigsInWorkspace(): Promise<TSConfig[]> {\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tconst { configFileName } = res.body;\n", "\t\t\tif (configFileName && !isImplicitProjectConfigFile(configFileName)) {\n", "\t\t\t\tconst path = vscode.Uri.file(configFileName);\n", "\t\t\t\tconst folder = vscode.workspace.getWorkspaceFolder(path);\n", "\t\t\t\treturn [{\n", "\t\t\t\t\tpath: configFileName,\n", "\t\t\t\t\tworkspaceFolder: folder\n", "\t\t\t\t}];\n", "\t\t\t}\n", "\t\t}\n", "\t\tcatch (e) {\n", "\t\t\t// noop\n" ], "file_path": "extensions/typescript/src/features/taskProvider.ts", "type": "replace", "edit_start_line_idx": 107 }
/*--------------------------------------------------------------------------------------------- * 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 fs from 'fs'; import * as path from 'path'; import * as vscode from 'vscode'; import * as Proto from '../protocol'; import TypeScriptServiceClient from '../typescriptServiceClient'; import TsConfigProvider, { TSConfig } from '../utils/tsconfigProvider'; import { isImplicitProjectConfigFile } from '../utils/tsconfig'; import * as nls from 'vscode-nls'; const localize = nls.loadMessageBundle(); const exists = (file: string): Promise<boolean> => new Promise<boolean>((resolve, _reject) => { fs.exists(file, (value: boolean) => { resolve(value); }); }); interface TypeScriptTaskDefinition extends vscode.TaskDefinition { tsconfig: string; } /** * Provides tasks for building `tsconfig.json` files in a project. */ class TscTaskProvider implements vscode.TaskProvider { private readonly tsconfigProvider: TsConfigProvider; public constructor( private readonly lazyClient: () => TypeScriptServiceClient ) { this.tsconfigProvider = new TsConfigProvider(); } dispose() { this.tsconfigProvider.dispose(); } public async provideTasks(token: vscode.CancellationToken): Promise<vscode.Task[]> { const folders = vscode.workspace.workspaceFolders; if (!folders || !folders.length) { return []; } const configPaths: Set<string> = new Set(); const tasks: vscode.Task[] = []; for (const project of await this.getAllTsConfigs(token)) { if (!configPaths.has(project.path)) { configPaths.add(project.path); tasks.push(await this.getBuildTaskForProject(project)); } } return tasks; } public resolveTask(_task: vscode.Task): vscode.Task | undefined { return undefined; } private async getAllTsConfigs(token: vscode.CancellationToken): Promise<TSConfig[]> { const out = new Set<TSConfig>(); const configs = (await this.getTsConfigForActiveFile(token)).concat(await this.getTsConfigsInWorkspace()); for (const config of configs) { if (await exists(config.path)) { out.add(config); } } return Array.from(out); } private async getTsConfigForActiveFile(token: vscode.CancellationToken): Promise<TSConfig[]> { const editor = vscode.window.activeTextEditor; if (editor) { if (path.basename(editor.document.fileName).match(/^tsconfig\.(.\.)?json$/)) { const path = editor.document.uri; const folder = vscode.workspace.getWorkspaceFolder(path); return [{ path: path.fsPath, workspaceFolder: folder }]; } } const file = this.getActiveTypeScriptFile(); if (!file) { return []; } const res: Proto.ProjectInfoResponse = await this.lazyClient().execute( 'projectInfo', { file, needFileNameList: false } as protocol.ProjectInfoRequestArgs, token); if (!res || !res.body) { return []; } const { configFileName } = res.body; if (configFileName && !isImplicitProjectConfigFile(configFileName)) { const path = vscode.Uri.file(configFileName); const folder = vscode.workspace.getWorkspaceFolder(path); return [{ path: configFileName, workspaceFolder: folder }]; } return []; } private async getTsConfigsInWorkspace(): Promise<TSConfig[]> { return Array.from(await this.tsconfigProvider.getConfigsForWorkspace()); } private async getCommand(project: TSConfig): Promise<string> { if (project.workspaceFolder) { const platform = process.platform; const bin = path.join(project.workspaceFolder.uri.fsPath, 'node_modules', '.bin'); if (platform === 'win32' && await exists(path.join(bin, 'tsc.cmd'))) { return path.join(bin, 'tsc.cmd'); } else if ((platform === 'linux' || platform === 'darwin') && await exists(path.join(bin, 'tsc'))) { return path.join(bin, 'tsc'); } } return 'tsc'; } private shouldUseWatchForBuild(configFile: TSConfig): boolean { try { const config = JSON.parse(fs.readFileSync(configFile.path, 'utf-8')); if (config) { return !!config.compileOnSave; } } catch (e) { // noop } return false; } private getActiveTypeScriptFile(): string | null { const editor = vscode.window.activeTextEditor; if (editor) { const document = editor.document; if (document && (document.languageId === 'typescript' || document.languageId === 'typescriptreact')) { return this.lazyClient().normalizePath(document.uri); } } return null; } private async getBuildTaskForProject(project: TSConfig): Promise<vscode.Task> { const command = await this.getCommand(project); let label: string = project.path; if (project.workspaceFolder) { const relativePath = path.relative(project.workspaceFolder.uri.fsPath, project.path); if (vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders.length > 1) { label = path.join(project.workspaceFolder.name, relativePath); } else { label = relativePath; } } const watch = this.shouldUseWatchForBuild(project); const identifier: TypeScriptTaskDefinition = { type: 'typescript', tsconfig: label, watch: watch }; const buildTask = new vscode.Task( identifier, watch ? localize('buildAndWatchTscLabel', 'watch - {0}', label) : localize('buildTscLabel', 'build - {0}', label), 'tsc', new vscode.ShellExecution(`${command} ${watch ? '--watch' : ''} -p "${project.path}"`), '$tsc'); buildTask.group = vscode.TaskGroup.Build; return buildTask; } } type AutoDetect = 'on' | 'off'; /** * Manages registrations of TypeScript task provides with VScode. */ export default class TypeScriptTaskProviderManager { private taskProviderSub: vscode.Disposable | undefined = undefined; private readonly disposables: vscode.Disposable[] = []; constructor( private readonly lazyClient: () => TypeScriptServiceClient ) { vscode.workspace.onDidChangeConfiguration(this.onConfigurationChanged, this, this.disposables); this.onConfigurationChanged(); } dispose() { if (this.taskProviderSub) { this.taskProviderSub.dispose(); this.taskProviderSub = undefined; } this.disposables.forEach(x => x.dispose()); } private onConfigurationChanged() { let autoDetect = vscode.workspace.getConfiguration('typescript.tsc').get<AutoDetect>('autoDetect'); if (this.taskProviderSub && autoDetect === 'off') { this.taskProviderSub.dispose(); this.taskProviderSub = undefined; } else if (!this.taskProviderSub && autoDetect === 'on') { this.taskProviderSub = vscode.workspace.registerTaskProvider('typescript', new TscTaskProvider(this.lazyClient)); } } }
extensions/typescript/src/features/taskProvider.ts
1
https://github.com/microsoft/vscode/commit/20519a8fe1fe565cd3a7618089beba6d66266b5b
[ 0.9989486336708069, 0.15635858476161957, 0.0001691695797489956, 0.0006369632901623845, 0.33536556363105774 ]
{ "id": 4, "code_window": [ "\n", "\t\tconst { configFileName } = res.body;\n", "\t\tif (configFileName && !isImplicitProjectConfigFile(configFileName)) {\n", "\t\t\tconst path = vscode.Uri.file(configFileName);\n", "\t\t\tconst folder = vscode.workspace.getWorkspaceFolder(path);\n", "\t\t\treturn [{\n", "\t\t\t\tpath: configFileName,\n", "\t\t\t\tworkspaceFolder: folder\n", "\t\t\t}];\n", "\t\t}\n", "\t\treturn [];\n", "\t}\n", "\n", "\tprivate async getTsConfigsInWorkspace(): Promise<TSConfig[]> {\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tconst { configFileName } = res.body;\n", "\t\t\tif (configFileName && !isImplicitProjectConfigFile(configFileName)) {\n", "\t\t\t\tconst path = vscode.Uri.file(configFileName);\n", "\t\t\t\tconst folder = vscode.workspace.getWorkspaceFolder(path);\n", "\t\t\t\treturn [{\n", "\t\t\t\t\tpath: configFileName,\n", "\t\t\t\t\tworkspaceFolder: folder\n", "\t\t\t\t}];\n", "\t\t\t}\n", "\t\t}\n", "\t\tcatch (e) {\n", "\t\t\t// noop\n" ], "file_path": "extensions/typescript/src/features/taskProvider.ts", "type": "replace", "edit_start_line_idx": 107 }
/*--------------------------------------------------------------------------------------------- * 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. { "openLaunchJson": "Abrir {0}", "launchJsonNeedsConfigurtion": "Configurar ou corrigir 'launch.json'", "noFolderDebugConfig": "Primeiro abra uma pasta para fazer uma configuração de depuração avançada.", "startDebug": "Iniciar Depuração", "startWithoutDebugging": "Iniciar Sem Depuração", "selectAndStartDebugging": "Selecionar e Iniciar a Depuração", "restartDebug": "Reiniciar", "reconnectDebug": "Reconectar", "stepOverDebug": "Pular Sobre", "stepIntoDebug": "Pular Dentro", "stepOutDebug": "Pular Fora", "stopDebug": "Parar", "disconnectDebug": "Desconectar", "continueDebug": "Continuar", "pauseDebug": "Pausa", "restartFrame": "Reiniciar o Frame", "removeBreakpoint": "Remover Ponto de Parada", "removeAllBreakpoints": "Remover Todos os Pontos de Parada", "enableBreakpoint": "Habilitar ponto de Parada", "disableBreakpoint": "Desativar Ponto de Parada", "enableAllBreakpoints": "Habilitar Todos os Pontos de Parada", "disableAllBreakpoints": "Desabilitar Todos Pontos de Parada", "activateBreakpoints": "Ativar Pontos de Parada", "deactivateBreakpoints": "Desativar Pontos de Parada", "reapplyAllBreakpoints": "Reaplicar Todos os Pontos de Parada", "addFunctionBreakpoint": "Adicionar Ponto de Parada de Função", "renameFunctionBreakpoint": "Renomeie o Ponto de Parada de Função", "addConditionalBreakpoint": "Adicionar Ponto de Parada Condicional...", "editConditionalBreakpoint": "Editar o Ponto de Parada...", "setValue": "Definir Valor", "addWatchExpression": "Adicionar Expressão", "editWatchExpression": "Editar expressão", "addToWatchExpressions": "Adicionar ao monitoramento", "removeWatchExpression": "Remover Expressão", "removeAllWatchExpressions": "Remover Todas as Expressões", "clearRepl": "Limpar console", "debugConsoleAction": "Console do Depurador", "unreadOutput": "Nova Saída no Console de Depuração", "debugFocusConsole": "Foco no Console de Depuração", "focusProcess": "Foco no Processo", "stepBackDebug": "Passo para trás", "reverseContinue": "Reverter" }
i18n/ptb/src/vs/workbench/parts/debug/browser/debugActions.i18n.json
0
https://github.com/microsoft/vscode/commit/20519a8fe1fe565cd3a7618089beba6d66266b5b
[ 0.00017998834664467722, 0.00017601062427274883, 0.0001727691269479692, 0.0001744464971125126, 0.000002787940275084111 ]
{ "id": 4, "code_window": [ "\n", "\t\tconst { configFileName } = res.body;\n", "\t\tif (configFileName && !isImplicitProjectConfigFile(configFileName)) {\n", "\t\t\tconst path = vscode.Uri.file(configFileName);\n", "\t\t\tconst folder = vscode.workspace.getWorkspaceFolder(path);\n", "\t\t\treturn [{\n", "\t\t\t\tpath: configFileName,\n", "\t\t\t\tworkspaceFolder: folder\n", "\t\t\t}];\n", "\t\t}\n", "\t\treturn [];\n", "\t}\n", "\n", "\tprivate async getTsConfigsInWorkspace(): Promise<TSConfig[]> {\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tconst { configFileName } = res.body;\n", "\t\t\tif (configFileName && !isImplicitProjectConfigFile(configFileName)) {\n", "\t\t\t\tconst path = vscode.Uri.file(configFileName);\n", "\t\t\t\tconst folder = vscode.workspace.getWorkspaceFolder(path);\n", "\t\t\t\treturn [{\n", "\t\t\t\t\tpath: configFileName,\n", "\t\t\t\t\tworkspaceFolder: folder\n", "\t\t\t\t}];\n", "\t\t\t}\n", "\t\t}\n", "\t\tcatch (e) {\n", "\t\t\t// noop\n" ], "file_path": "extensions/typescript/src/features/taskProvider.ts", "type": "replace", "edit_start_line_idx": 107 }
/*--------------------------------------------------------------------------------------------- * 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. { "switchToChangesView": "Zur Änderungsansicht wechseln", "openInEditor": "Zur Editor-Ansicht wechseln", "workbenchStage": "Phase", "workbenchUnstage": "Bereitstellung aufheben", "stageSelectedLines": "Ausgewählte Zeilen bereitstellen", "unstageSelectedLines": "Bereitstellung ausgewählter Zeilen aufheben", "revertSelectedLines": "Gewählte Zeilen zurücksetzen", "confirmRevertMessage": "Möchten Sie die ausgewählten Änderungen wirklich zurücksetzen?", "irreversible": "Diese Aktion kann nicht rückgängig gemacht werden.", "revertChangesLabel": "&&Änderungen zurücksetzen", "openChange": "Änderung öffnen", "openFile": "Datei öffnen", "git": "Git" }
i18n/deu/src/vs/workbench/parts/git/browser/gitActions.contribution.i18n.json
0
https://github.com/microsoft/vscode/commit/20519a8fe1fe565cd3a7618089beba6d66266b5b
[ 0.00017475582717452198, 0.00017394371388945729, 0.00017257056606467813, 0.0001745047338772565, 9.763548405317124e-7 ]
{ "id": 4, "code_window": [ "\n", "\t\tconst { configFileName } = res.body;\n", "\t\tif (configFileName && !isImplicitProjectConfigFile(configFileName)) {\n", "\t\t\tconst path = vscode.Uri.file(configFileName);\n", "\t\t\tconst folder = vscode.workspace.getWorkspaceFolder(path);\n", "\t\t\treturn [{\n", "\t\t\t\tpath: configFileName,\n", "\t\t\t\tworkspaceFolder: folder\n", "\t\t\t}];\n", "\t\t}\n", "\t\treturn [];\n", "\t}\n", "\n", "\tprivate async getTsConfigsInWorkspace(): Promise<TSConfig[]> {\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tconst { configFileName } = res.body;\n", "\t\t\tif (configFileName && !isImplicitProjectConfigFile(configFileName)) {\n", "\t\t\t\tconst path = vscode.Uri.file(configFileName);\n", "\t\t\t\tconst folder = vscode.workspace.getWorkspaceFolder(path);\n", "\t\t\t\treturn [{\n", "\t\t\t\t\tpath: configFileName,\n", "\t\t\t\t\tworkspaceFolder: folder\n", "\t\t\t\t}];\n", "\t\t\t}\n", "\t\t}\n", "\t\tcatch (e) {\n", "\t\t\t// noop\n" ], "file_path": "extensions/typescript/src/features/taskProvider.ts", "type": "replace", "edit_start_line_idx": 107 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ /* -- zone widget */ .monaco-editor .zone-widget .zone-widget-container.reference-zone-widget { border-top-width: 1px; border-bottom-width: 1px; } .monaco-editor .zone-widget .zone-widget-container.reference-zone-widget.results-loaded { -webkit-transition: height 100ms ease-in; transition: height 100ms ease-in; } .monaco-editor .reference-zone-widget .inline { display: inline-block; vertical-align: top; } .monaco-editor .reference-zone-widget .messages { height: 100%; width: 100%; text-align: center; padding: 3em 0; } .monaco-editor .reference-zone-widget .ref-tree { line-height: 22px; font-size: 13px; } .monaco-editor .reference-zone-widget .ref-tree .reference { text-overflow: ellipsis; overflow: hidden; } .monaco-editor .reference-zone-widget .ref-tree .reference-file { display: flex; justify-content: space-between; align-items: center; } .monaco-editor .reference-zone-widget .monaco-count-badge { margin-right: .5em; height: 15px; padding: 0 .5em .5em .5em } /* High Contrast Theming */ .monaco-editor.hc-black .reference-zone-widget .ref-tree .reference-file { font-weight: bold; display: flex; justify-content: space-between; }
src/vs/editor/contrib/referenceSearch/browser/referencesWidget.css
0
https://github.com/microsoft/vscode/commit/20519a8fe1fe565cd3a7618089beba6d66266b5b
[ 0.00017678474250715226, 0.0001745080080581829, 0.00017124351870734245, 0.00017528660828247666, 0.000001842942424445937 ]
{ "id": 5, "code_window": [ "\tworkspaceFolder?: vscode.WorkspaceFolder;\n", "}\n", "\n", "export default class TsConfigProvider extends vscode.Disposable {\n", "\tprivate readonly tsconfigs = new Map<string, TSConfig>();\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "const tsconfigGlob = '**/tsconfig*.json';\n", "\n" ], "file_path": "extensions/typescript/src/utils/tsconfigProvider.ts", "type": "add", "edit_start_line_idx": 11 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as vscode from 'vscode'; export interface TSConfig { path: string; workspaceFolder?: vscode.WorkspaceFolder; } export default class TsConfigProvider extends vscode.Disposable { private readonly tsconfigs = new Map<string, TSConfig>(); private activated: boolean = false; private disposables: vscode.Disposable[] = []; constructor() { super(() => this.dispose()); } dispose(): void { this.disposables.forEach(d => d.dispose()); } public async getConfigsForWorkspace(): Promise<Iterable<TSConfig>> { if (!vscode.workspace.workspaceFolders) { return []; } await this.ensureActivated(); return this.tsconfigs.values(); } private async ensureActivated(): Promise<this> { if (this.activated) { return this; } this.activated = true; this.reloadWorkspaceConfigs(); const configFileWatcher = vscode.workspace.createFileSystemWatcher('**/tsconfig*.json'); this.disposables.push(configFileWatcher); configFileWatcher.onDidCreate(this.handleProjectCreate, this, this.disposables); configFileWatcher.onDidDelete(this.handleProjectDelete, this, this.disposables); vscode.workspace.onDidChangeWorkspaceFolders(() => { this.reloadWorkspaceConfigs(); }, this, this.disposables); return this; } private async reloadWorkspaceConfigs(): Promise<this> { this.tsconfigs.clear(); for (const config of await vscode.workspace.findFiles('**/tsconfig*.json', '**/node_modules/**')) { this.handleProjectCreate(config); } return this; } private handleProjectCreate(config: vscode.Uri) { const root = vscode.workspace.getWorkspaceFolder(config); if (root) { this.tsconfigs.set(config.fsPath, { path: config.fsPath, workspaceFolder: root }); } } private handleProjectDelete(e: vscode.Uri) { this.tsconfigs.delete(e.fsPath); } }
extensions/typescript/src/utils/tsconfigProvider.ts
1
https://github.com/microsoft/vscode/commit/20519a8fe1fe565cd3a7618089beba6d66266b5b
[ 0.9979445338249207, 0.39305299520492554, 0.0032227616757154465, 0.2495797723531723, 0.38492825627326965 ]
{ "id": 5, "code_window": [ "\tworkspaceFolder?: vscode.WorkspaceFolder;\n", "}\n", "\n", "export default class TsConfigProvider extends vscode.Disposable {\n", "\tprivate readonly tsconfigs = new Map<string, TSConfig>();\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "const tsconfigGlob = '**/tsconfig*.json';\n", "\n" ], "file_path": "extensions/typescript/src/utils/tsconfigProvider.ts", "type": "add", "edit_start_line_idx": 11 }
/*--------------------------------------------------------------------------------------------- * 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. { "buildAndWatchTscLabel": "figyelés – {0}", "buildTscLabel": "buildelés – {0}" }
i18n/hun/extensions/typescript/out/features/taskProvider.i18n.json
0
https://github.com/microsoft/vscode/commit/20519a8fe1fe565cd3a7618089beba6d66266b5b
[ 0.00017629489593673497, 0.00017629489593673497, 0.00017629489593673497, 0.00017629489593673497, 0 ]
{ "id": 5, "code_window": [ "\tworkspaceFolder?: vscode.WorkspaceFolder;\n", "}\n", "\n", "export default class TsConfigProvider extends vscode.Disposable {\n", "\tprivate readonly tsconfigs = new Map<string, TSConfig>();\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "const tsconfigGlob = '**/tsconfig*.json';\n", "\n" ], "file_path": "extensions/typescript/src/utils/tsconfigProvider.ts", "type": "add", "edit_start_line_idx": 11 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .monaco-count-badge { padding: 0.2em 0.5em; border-radius: 1em; font-size: 85%; font-weight: normal; text-align: center; display: inline; }
src/vs/base/browser/ui/countBadge/countBadge.css
0
https://github.com/microsoft/vscode/commit/20519a8fe1fe565cd3a7618089beba6d66266b5b
[ 0.00017833318270277232, 0.00017660975572653115, 0.0001748863433022052, 0.00017660975572653115, 0.0000017234197002835572 ]
{ "id": 5, "code_window": [ "\tworkspaceFolder?: vscode.WorkspaceFolder;\n", "}\n", "\n", "export default class TsConfigProvider extends vscode.Disposable {\n", "\tprivate readonly tsconfigs = new Map<string, TSConfig>();\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "const tsconfigGlob = '**/tsconfig*.json';\n", "\n" ], "file_path": "extensions/typescript/src/utils/tsconfigProvider.ts", "type": "add", "edit_start_line_idx": 11 }
/*--------------------------------------------------------------------------------------------- * 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 { MarkedString } from 'vs/base/common/htmlContent'; import { IDisposable } from 'vs/base/common/lifecycle'; import URI from 'vs/base/common/uri'; import * as editorCommon from 'vs/editor/common/editorCommon'; import { TokenizationResult, TokenizationResult2 } from 'vs/editor/common/core/token'; import LanguageFeatureRegistry from 'vs/editor/common/modes/languageFeatureRegistry'; import { CancellationToken } from 'vs/base/common/cancellation'; import { Position } from 'vs/editor/common/core/position'; import { Range, IRange } from 'vs/editor/common/core/range'; import Event from 'vs/base/common/event'; import { TokenizationRegistryImpl } from 'vs/editor/common/modes/tokenizationRegistry'; import { Color } from 'vs/base/common/color'; /** * Open ended enum at runtime * @internal */ export const enum LanguageId { Null = 0, PlainText = 1 } /** * @internal */ export class LanguageIdentifier { /** * A string identifier. Unique across languages. e.g. 'javascript'. */ public readonly language: string; /** * A numeric identifier. Unique across languages. e.g. 5 * Will vary at runtime based on registration order, etc. */ public readonly id: LanguageId; constructor(language: string, id: LanguageId) { this.language = language; this.id = id; } } /** * A mode. Will soon be obsolete. * @internal */ export interface IMode { getId(): string; getLanguageIdentifier(): LanguageIdentifier; } /** * A font style. Values are 2^x such that a bit mask can be used. * @internal */ export const enum FontStyle { NotSet = -1, None = 0, Italic = 1, Bold = 2, Underline = 4 } /** * Open ended enum at runtime * @internal */ export const enum ColorId { None = 0, DefaultForeground = 1, DefaultBackground = 2 } /** * A standard token type. Values are 2^x such that a bit mask can be used. * @internal */ export const enum StandardTokenType { Other = 0, Comment = 1, String = 2, RegEx = 4 } /** * Helpers to manage the "collapsed" metadata of an entire StackElement stack. * The following assumptions have been made: * - languageId < 256 => needs 8 bits * - unique color count < 512 => needs 9 bits * * The binary format is: * - ------------------------------------------- * 3322 2222 2222 1111 1111 1100 0000 0000 * 1098 7654 3210 9876 5432 1098 7654 3210 * - ------------------------------------------- * xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx * bbbb bbbb bfff ffff ffFF FTTT LLLL LLLL * - ------------------------------------------- * - L = LanguageId (8 bits) * - T = StandardTokenType (3 bits) * - F = FontStyle (3 bits) * - f = foreground color (9 bits) * - b = background color (9 bits) * * @internal */ export const enum MetadataConsts { LANGUAGEID_MASK = 0b00000000000000000000000011111111, TOKEN_TYPE_MASK = 0b00000000000000000000011100000000, FONT_STYLE_MASK = 0b00000000000000000011100000000000, FOREGROUND_MASK = 0b00000000011111111100000000000000, BACKGROUND_MASK = 0b11111111100000000000000000000000, LANGUAGEID_OFFSET = 0, TOKEN_TYPE_OFFSET = 8, FONT_STYLE_OFFSET = 11, FOREGROUND_OFFSET = 14, BACKGROUND_OFFSET = 23 } /** * @internal */ export interface ITokenizationSupport { getInitialState(): IState; // add offsetDelta to each of the returned indices tokenize(line: string, state: IState, offsetDelta: number): TokenizationResult; tokenize2(line: string, state: IState, offsetDelta: number): TokenizationResult2; } /** * The state of the tokenizer between two lines. * It is useful to store flags such as in multiline comment, etc. * The model will clone the previous line's state and pass it in to tokenize the next line. */ export interface IState { clone(): IState; equals(other: IState): boolean; } /** * A hover represents additional information for a symbol or word. Hovers are * rendered in a tooltip-like widget. */ export interface Hover { /** * The contents of this hover. */ contents: MarkedString[]; /** * The range to which this hover applies. When missing, the * editor will use the range at the current position or the * current position itself. */ range: IRange; } /** * The hover provider interface defines the contract between extensions and * the [hover](https://code.visualstudio.com/docs/editor/intellisense)-feature. */ export interface HoverProvider { /** * Provide a hover for the given position and document. Multiple hovers at the same * position will be merged by the editor. A hover can have a range which defaults * to the word range at the position when omitted. */ provideHover(model: editorCommon.IReadOnlyModel, position: Position, token: CancellationToken): Hover | Thenable<Hover>; } /** * @internal */ export type SuggestionType = 'method' | 'function' | 'constructor' | 'field' | 'variable' | 'class' | 'struct' | 'interface' | 'module' | 'property' | 'event' | 'operator' | 'unit' | 'value' | 'constant' | 'enum' | 'enum-member' | 'keyword' | 'snippet' | 'text' | 'color' | 'file' | 'reference' | 'customcolor' | 'folder' | 'type-parameter'; /** * @internal */ export type SnippetType = 'internal' | 'textmate'; /** * @internal */ export interface ISuggestion { label: string; insertText: string; type: SuggestionType; detail?: string; documentation?: string; filterText?: string; sortText?: string; noAutoAccept?: boolean; commitCharacters?: string[]; overwriteBefore?: number; overwriteAfter?: number; additionalTextEdits?: editorCommon.ISingleEditOperation[]; command?: Command; snippetType?: SnippetType; } /** * @internal */ export interface ISuggestResult { suggestions: ISuggestion[]; incomplete?: boolean; } /** * @internal */ export interface ISuggestSupport { triggerCharacters?: string[]; provideCompletionItems(model: editorCommon.IModel, position: Position, token: CancellationToken): ISuggestResult | Thenable<ISuggestResult>; resolveCompletionItem?(model: editorCommon.IModel, position: Position, item: ISuggestion, token: CancellationToken): ISuggestion | Thenable<ISuggestion>; } /** * The code action interface defines the contract between extensions and * the [light bulb](https://code.visualstudio.com/docs/editor/editingevolved#_code-action) feature. * @internal */ export interface CodeActionProvider { /** * Provide commands for the given document and range. */ provideCodeActions(model: editorCommon.IReadOnlyModel, range: Range, token: CancellationToken): Command[] | Thenable<Command[]>; } /** * Represents a parameter of a callable-signature. A parameter can * have a label and a doc-comment. */ export interface ParameterInformation { /** * The label of this signature. Will be shown in * the UI. */ label: string; /** * The human-readable doc-comment of this signature. Will be shown * in the UI but can be omitted. */ documentation?: string; } /** * Represents the signature of something callable. A signature * can have a label, like a function-name, a doc-comment, and * a set of parameters. */ export interface SignatureInformation { /** * The label of this signature. Will be shown in * the UI. */ label: string; /** * The human-readable doc-comment of this signature. Will be shown * in the UI but can be omitted. */ documentation?: string; /** * The parameters of this signature. */ parameters: ParameterInformation[]; } /** * Signature help represents the signature of something * callable. There can be multiple signatures but only one * active and only one active parameter. */ export interface SignatureHelp { /** * One or more signatures. */ signatures: SignatureInformation[]; /** * The active signature. */ activeSignature: number; /** * The active parameter of the active signature. */ activeParameter: number; } /** * The signature help provider interface defines the contract between extensions and * the [parameter hints](https://code.visualstudio.com/docs/editor/intellisense)-feature. */ export interface SignatureHelpProvider { signatureHelpTriggerCharacters: string[]; /** * Provide help for the signature at the given position and document. */ provideSignatureHelp(model: editorCommon.IReadOnlyModel, position: Position, token: CancellationToken): SignatureHelp | Thenable<SignatureHelp>; } /** * A document highlight kind. */ export enum DocumentHighlightKind { /** * A textual occurrence. */ Text, /** * Read-access of a symbol, like reading a variable. */ Read, /** * Write-access of a symbol, like writing to a variable. */ Write } /** * A document highlight is a range inside a text document which deserves * special attention. Usually a document highlight is visualized by changing * the background color of its range. */ export interface DocumentHighlight { /** * The range this highlight applies to. */ range: IRange; /** * The highlight kind, default is [text](#DocumentHighlightKind.Text). */ kind: DocumentHighlightKind; } /** * The document highlight provider interface defines the contract between extensions and * the word-highlight-feature. */ export interface DocumentHighlightProvider { /** * Provide a set of document highlights, like all occurrences of a variable or * all exit-points of a function. */ provideDocumentHighlights(model: editorCommon.IReadOnlyModel, position: Position, token: CancellationToken): DocumentHighlight[] | Thenable<DocumentHighlight[]>; } /** * Value-object that contains additional information when * requesting references. */ export interface ReferenceContext { /** * Include the declaration of the current symbol. */ includeDeclaration: boolean; } /** * The reference provider interface defines the contract between extensions and * the [find references](https://code.visualstudio.com/docs/editor/editingevolved#_peek)-feature. */ export interface ReferenceProvider { /** * Provide a set of project-wide references for the given position and document. */ provideReferences(model: editorCommon.IReadOnlyModel, position: Position, context: ReferenceContext, token: CancellationToken): Location[] | Thenable<Location[]>; } /** * Represents a location inside a resource, such as a line * inside a text file. */ export interface Location { /** * The resource identifier of this location. */ uri: URI; /** * The document range of this locations. */ range: IRange; } /** * The definition of a symbol represented as one or many [locations](#Location). * For most programming languages there is only one location at which a symbol is * defined. */ export type Definition = Location | Location[]; /** * The definition provider interface defines the contract between extensions and * the [go to definition](https://code.visualstudio.com/docs/editor/editingevolved#_go-to-definition) * and peek definition features. */ export interface DefinitionProvider { /** * Provide the definition of the symbol at the given position and document. */ provideDefinition(model: editorCommon.IReadOnlyModel, position: Position, token: CancellationToken): Definition | Thenable<Definition>; } /** * The implementation provider interface defines the contract between extensions and * the go to implementation feature. */ export interface ImplementationProvider { /** * Provide the implementation of the symbol at the given position and document. */ provideImplementation(model: editorCommon.IReadOnlyModel, position: Position, token: CancellationToken): Definition | Thenable<Definition>; } /** * The type definition provider interface defines the contract between extensions and * the go to type definition feature. */ export interface TypeDefinitionProvider { /** * Provide the type definition of the symbol at the given position and document. */ provideTypeDefinition(model: editorCommon.IReadOnlyModel, position: Position, token: CancellationToken): Definition | Thenable<Definition>; } /** * A symbol kind. */ export enum SymbolKind { File = 0, Module = 1, Namespace = 2, Package = 3, Class = 4, Method = 5, Property = 6, Field = 7, Constructor = 8, Enum = 9, Interface = 10, Function = 11, Variable = 12, Constant = 13, String = 14, Number = 15, Boolean = 16, Array = 17, Object = 18, Key = 19, Null = 20, EnumMember = 21, Struct = 22, Event = 23, Operator = 24, TypeParameter = 25 } /** * @internal */ export const symbolKindToCssClass = (function () { const _fromMapping: { [n: number]: string } = Object.create(null); _fromMapping[SymbolKind.File] = 'file'; _fromMapping[SymbolKind.Module] = 'module'; _fromMapping[SymbolKind.Namespace] = 'namespace'; _fromMapping[SymbolKind.Package] = 'package'; _fromMapping[SymbolKind.Class] = 'class'; _fromMapping[SymbolKind.Method] = 'method'; _fromMapping[SymbolKind.Property] = 'property'; _fromMapping[SymbolKind.Field] = 'field'; _fromMapping[SymbolKind.Constructor] = 'constructor'; _fromMapping[SymbolKind.Enum] = 'enum'; _fromMapping[SymbolKind.Interface] = 'interface'; _fromMapping[SymbolKind.Function] = 'function'; _fromMapping[SymbolKind.Variable] = 'variable'; _fromMapping[SymbolKind.Constant] = 'constant'; _fromMapping[SymbolKind.String] = 'string'; _fromMapping[SymbolKind.Number] = 'number'; _fromMapping[SymbolKind.Boolean] = 'boolean'; _fromMapping[SymbolKind.Array] = 'array'; _fromMapping[SymbolKind.Object] = 'object'; _fromMapping[SymbolKind.Key] = 'key'; _fromMapping[SymbolKind.Null] = 'null'; _fromMapping[SymbolKind.EnumMember] = 'enum-member'; _fromMapping[SymbolKind.Struct] = 'struct'; _fromMapping[SymbolKind.Event] = 'event'; _fromMapping[SymbolKind.Operator] = 'operator'; _fromMapping[SymbolKind.TypeParameter] = 'type-parameter'; return function toCssClassName(kind: SymbolKind): string { return _fromMapping[kind] || 'property'; }; })(); /** * @internal */ export interface IOutline { entries: SymbolInformation[]; } /** * Represents information about programming constructs like variables, classes, * interfaces etc. */ export interface SymbolInformation { /** * The name of this symbol. */ name: string; /** * The name of the symbol containing this symbol. */ containerName?: string; /** * The kind of this symbol. */ kind: SymbolKind; /** * The location of this symbol. */ location: Location; } /** * The document symbol provider interface defines the contract between extensions and * the [go to symbol](https://code.visualstudio.com/docs/editor/editingevolved#_goto-symbol)-feature. */ export interface DocumentSymbolProvider { /** * Provide symbol information for the given document. */ provideDocumentSymbols(model: editorCommon.IReadOnlyModel, token: CancellationToken): SymbolInformation[] | Thenable<SymbolInformation[]>; } export interface TextEdit { range: IRange; text: string; eol?: editorCommon.EndOfLineSequence; } /** * Interface used to format a model */ export interface FormattingOptions { /** * Size of a tab in spaces. */ tabSize: number; /** * Prefer spaces over tabs. */ insertSpaces: boolean; } /** * The document formatting provider interface defines the contract between extensions and * the formatting-feature. */ export interface DocumentFormattingEditProvider { /** * Provide formatting edits for a whole document. */ provideDocumentFormattingEdits(model: editorCommon.IReadOnlyModel, options: FormattingOptions, token: CancellationToken): TextEdit[] | Thenable<TextEdit[]>; } /** * The document formatting provider interface defines the contract between extensions and * the formatting-feature. */ export interface DocumentRangeFormattingEditProvider { /** * Provide formatting edits for a range in a document. * * The given range is a hint and providers can decide to format a smaller * or larger range. Often this is done by adjusting the start and end * of the range to full syntax nodes. */ provideDocumentRangeFormattingEdits(model: editorCommon.IReadOnlyModel, range: Range, options: FormattingOptions, token: CancellationToken): TextEdit[] | Thenable<TextEdit[]>; } /** * The document formatting provider interface defines the contract between extensions and * the formatting-feature. */ export interface OnTypeFormattingEditProvider { autoFormatTriggerCharacters: string[]; /** * Provide formatting edits after a character has been typed. * * The given position and character should hint to the provider * what range the position to expand to, like find the matching `{` * when `}` has been entered. */ provideOnTypeFormattingEdits(model: editorCommon.IReadOnlyModel, position: Position, ch: string, options: FormattingOptions, token: CancellationToken): TextEdit[] | Thenable<TextEdit[]>; } /** * @internal */ export interface IInplaceReplaceSupportResult { value: string; range: IRange; } /** * A link inside the editor. */ export interface ILink { range: IRange; url: string; } /** * A provider of links. */ export interface LinkProvider { provideLinks(model: editorCommon.IReadOnlyModel, token: CancellationToken): ILink[] | Thenable<ILink[]>; resolveLink?: (link: ILink, token: CancellationToken) => ILink | Thenable<ILink>; } /** * A color in RGBA format. * @internal */ export interface IColor { /** * The red component in the range [0-1]. */ readonly red: number; /** * The green component in the range [0-1]. */ readonly green: number; /** * The blue component in the range [0-1]. */ readonly blue: number; /** * The alpha component in the range [0-1]. */ readonly alpha: number; } // TODO@joao TODO@michel can we use a formatter here? /** * A color format. * @internal */ export type IColorFormat = string | { opaque: string, transparent: string }; /** * A color range is a range in a text model which represents a color. * @internal */ export interface IColorRange { /** * The range within the model. */ range: IRange; /** * The color represented in this range. */ color: IColor; // TODO@joao TODO@michel can we drop this? format: IColorFormat; /** * The available formats for this specific color. */ availableFormats: IColorFormat[]; } /** * A provider of colors for editor models. * @internal */ export interface ColorRangeProvider { /** * Provides the color ranges for a specific model. */ provideColorRanges(model: editorCommon.IReadOnlyModel, token: CancellationToken): IColorRange[] | Thenable<IColorRange[]>; } export interface IResourceEdit { resource: URI; range: IRange; newText: string; } export interface WorkspaceEdit { edits: IResourceEdit[]; rejectReason?: string; } export interface RenameProvider { provideRenameEdits(model: editorCommon.IReadOnlyModel, position: Position, newName: string, token: CancellationToken): WorkspaceEdit | Thenable<WorkspaceEdit>; } export interface Command { id: string; title: string; tooltip?: string; arguments?: any[]; } export interface ICodeLensSymbol { range: IRange; id?: string; command?: Command; } export interface CodeLensProvider { onDidChange?: Event<this>; provideCodeLenses(model: editorCommon.IReadOnlyModel, token: CancellationToken): ICodeLensSymbol[] | Thenable<ICodeLensSymbol[]>; resolveCodeLens?(model: editorCommon.IReadOnlyModel, codeLens: ICodeLensSymbol, token: CancellationToken): ICodeLensSymbol | Thenable<ICodeLensSymbol>; } // --- feature registries ------ /** * @internal */ export const ReferenceProviderRegistry = new LanguageFeatureRegistry<ReferenceProvider>(); /** * @internal */ export const RenameProviderRegistry = new LanguageFeatureRegistry<RenameProvider>(); /** * @internal */ export const SuggestRegistry = new LanguageFeatureRegistry<ISuggestSupport>(); /** * @internal */ export const SignatureHelpProviderRegistry = new LanguageFeatureRegistry<SignatureHelpProvider>(); /** * @internal */ export const HoverProviderRegistry = new LanguageFeatureRegistry<HoverProvider>(); /** * @internal */ export const DocumentSymbolProviderRegistry = new LanguageFeatureRegistry<DocumentSymbolProvider>(); /** * @internal */ export const DocumentHighlightProviderRegistry = new LanguageFeatureRegistry<DocumentHighlightProvider>(); /** * @internal */ export const DefinitionProviderRegistry = new LanguageFeatureRegistry<DefinitionProvider>(); /** * @internal */ export const ImplementationProviderRegistry = new LanguageFeatureRegistry<ImplementationProvider>(); /** * @internal */ export const TypeDefinitionProviderRegistry = new LanguageFeatureRegistry<TypeDefinitionProvider>(); /** * @internal */ export const CodeLensProviderRegistry = new LanguageFeatureRegistry<CodeLensProvider>(); /** * @internal */ export const CodeActionProviderRegistry = new LanguageFeatureRegistry<CodeActionProvider>(); /** * @internal */ export const DocumentFormattingEditProviderRegistry = new LanguageFeatureRegistry<DocumentFormattingEditProvider>(); /** * @internal */ export const DocumentRangeFormattingEditProviderRegistry = new LanguageFeatureRegistry<DocumentRangeFormattingEditProvider>(); /** * @internal */ export const OnTypeFormattingEditProviderRegistry = new LanguageFeatureRegistry<OnTypeFormattingEditProvider>(); /** * @internal */ export const LinkProviderRegistry = new LanguageFeatureRegistry<LinkProvider>(); /** * @internal */ export const ColorProviderRegistry = new LanguageFeatureRegistry<ColorRangeProvider>(); /** * @internal */ export interface ITokenizationSupportChangedEvent { changedLanguages: string[]; changedColorMap: boolean; } /** * @internal */ export interface ITokenizationRegistry { /** * An event triggered when: * - a tokenization support is registered, unregistered or changed. * - the color map is changed. */ onDidChange: Event<ITokenizationSupportChangedEvent>; /** * Fire a change event for a language. * This is useful for languages that embed other languages. */ fire(languages: string[]): void; /** * Register a tokenization support. */ register(language: string, support: ITokenizationSupport): IDisposable; /** * Get the tokenization support for a language. * Returns null if not found. */ get(language: string): ITokenizationSupport; /** * Set the new color map that all tokens will use in their ColorId binary encoded bits for foreground and background. */ setColorMap(colorMap: Color[]): void; getColorMap(): Color[]; getDefaultForeground(): Color; getDefaultBackground(): Color; } /** * @internal */ export const TokenizationRegistry = new TokenizationRegistryImpl();
src/vs/editor/common/modes.ts
0
https://github.com/microsoft/vscode/commit/20519a8fe1fe565cd3a7618089beba6d66266b5b
[ 0.009484718553721905, 0.00027829562895931304, 0.0001615226938156411, 0.00017061269318219274, 0.0009763140114955604 ]
{ "id": 6, "code_window": [ "\t\t}\n", "\t\tthis.activated = true;\n", "\n", "\t\tthis.reloadWorkspaceConfigs();\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "\t\tawait this.reloadWorkspaceConfigs();\n" ], "file_path": "extensions/typescript/src/utils/tsconfigProvider.ts", "type": "replace", "edit_start_line_idx": 39 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as vscode from 'vscode'; export interface TSConfig { path: string; workspaceFolder?: vscode.WorkspaceFolder; } export default class TsConfigProvider extends vscode.Disposable { private readonly tsconfigs = new Map<string, TSConfig>(); private activated: boolean = false; private disposables: vscode.Disposable[] = []; constructor() { super(() => this.dispose()); } dispose(): void { this.disposables.forEach(d => d.dispose()); } public async getConfigsForWorkspace(): Promise<Iterable<TSConfig>> { if (!vscode.workspace.workspaceFolders) { return []; } await this.ensureActivated(); return this.tsconfigs.values(); } private async ensureActivated(): Promise<this> { if (this.activated) { return this; } this.activated = true; this.reloadWorkspaceConfigs(); const configFileWatcher = vscode.workspace.createFileSystemWatcher('**/tsconfig*.json'); this.disposables.push(configFileWatcher); configFileWatcher.onDidCreate(this.handleProjectCreate, this, this.disposables); configFileWatcher.onDidDelete(this.handleProjectDelete, this, this.disposables); vscode.workspace.onDidChangeWorkspaceFolders(() => { this.reloadWorkspaceConfigs(); }, this, this.disposables); return this; } private async reloadWorkspaceConfigs(): Promise<this> { this.tsconfigs.clear(); for (const config of await vscode.workspace.findFiles('**/tsconfig*.json', '**/node_modules/**')) { this.handleProjectCreate(config); } return this; } private handleProjectCreate(config: vscode.Uri) { const root = vscode.workspace.getWorkspaceFolder(config); if (root) { this.tsconfigs.set(config.fsPath, { path: config.fsPath, workspaceFolder: root }); } } private handleProjectDelete(e: vscode.Uri) { this.tsconfigs.delete(e.fsPath); } }
extensions/typescript/src/utils/tsconfigProvider.ts
1
https://github.com/microsoft/vscode/commit/20519a8fe1fe565cd3a7618089beba6d66266b5b
[ 0.9969738721847534, 0.1325763612985611, 0.00016945712559390813, 0.0037362254224717617, 0.3270275890827179 ]
{ "id": 6, "code_window": [ "\t\t}\n", "\t\tthis.activated = true;\n", "\n", "\t\tthis.reloadWorkspaceConfigs();\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "\t\tawait this.reloadWorkspaceConfigs();\n" ], "file_path": "extensions/typescript/src/utils/tsconfigProvider.ts", "type": "replace", "edit_start_line_idx": 39 }
/*--------------------------------------------------------------------------------------------- * 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. { "search.action.replaceAll.disabled.label": "Substituir Todos (Submeter Pesquisa para Habilitar)", "search.action.replaceAll.enabled.label": "Substituir Tudo", "search.replace.toggle.button.title": "Alternar Substituir", "label.Search": "Pesquisar: Digite o termo de pesquisa e pressione Enter para pesquisar ou Escape para cancelar", "search.placeHolder": "Pesquisar", "label.Replace": "Substituir: Digite o termo a ser substituído e pressione Enter para visualizar ou Escape para cancelar", "search.replace.placeHolder": "Substituir", "regexp.validationFailure": "A expressão corresponde a tudo" }
i18n/ptb/src/vs/workbench/parts/search/browser/searchWidget.i18n.json
0
https://github.com/microsoft/vscode/commit/20519a8fe1fe565cd3a7618089beba6d66266b5b
[ 0.00017214885156136006, 0.0001713056117296219, 0.0001704623718978837, 0.0001713056117296219, 8.43239831738174e-7 ]
{ "id": 6, "code_window": [ "\t\t}\n", "\t\tthis.activated = true;\n", "\n", "\t\tthis.reloadWorkspaceConfigs();\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "\t\tawait this.reloadWorkspaceConfigs();\n" ], "file_path": "extensions/typescript/src/utils/tsconfigProvider.ts", "type": "replace", "edit_start_line_idx": 39 }
/*--------------------------------------------------------------------------------------------- * 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. { "vscode.extension.engines.vscode": "对于 VS Code 扩展程序,指定该扩展程序与之兼容的 VS Code 版本。不能为 *. 例如: ^0.10.5 表示最低兼容 VS Code 版本 0.10.5。", "vscode.extension.publisher": "VS Code 扩展的发布服务器。", "vscode.extension.displayName": "VS Code 库中使用的扩展的显示名称。", "vscode.extension.categories": "VS Code 库用于对扩展进行分类的类别。", "vscode.extension.galleryBanner": "VS Code 商城使用的横幅。", "vscode.extension.galleryBanner.color": "VS Code 商城页标题上的横幅颜色。", "vscode.extension.galleryBanner.theme": "横幅中使用的字体颜色主题。", "vscode.extension.contributes": "由此包表示的 VS Code 扩展的所有贡献。", "vscode.extension.preview": "在 Marketplace 中设置扩展,将其标记为“预览”。", "vscode.extension.activationEvents": "VS Code 扩展的激活事件。", "vscode.extension.activationEvents.onLanguage": "在打开被解析为指定语言的文件时发出的激活事件。", "vscode.extension.activationEvents.onCommand": "在调用指定命令时发出的激活事件。", "vscode.extension.activationEvents.onDebug": "在指定类型的调试会话开始时发出的激活事件。", "vscode.extension.activationEvents.workspaceContains": "在打开至少包含一个匹配指定 glob 模式的文件的文件夹时发出的激活事件。", "vscode.extension.activationEvents.onView": "在指定视图被展开时发出的激活事件。", "vscode.extension.activationEvents.star": "在 VS Code 启动时发出的激活事件。为确保良好的最终用户体验,请仅在其他激活事件组合不适用于你的情况时,才在扩展中使用此事件。", "vscode.extension.badges": "在 Marketplace 的扩展页边栏中显示的徽章数组。", "vscode.extension.badges.url": "徽章图像 URL。", "vscode.extension.badges.href": "徽章链接。", "vscode.extension.badges.description": "徽章说明。", "vscode.extension.extensionDependencies": "其他扩展的依赖关系。扩展的标识符始终是 ${publisher}.${name}。例如: vscode.csharp。", "vscode.extension.scripts.prepublish": "包作为 VS Code 扩展发布前执行的脚本。", "vscode.extension.icon": "128 x 128 像素图标的路径。" }
i18n/chs/src/vs/platform/extensions/common/extensionsRegistry.i18n.json
0
https://github.com/microsoft/vscode/commit/20519a8fe1fe565cd3a7618089beba6d66266b5b
[ 0.0012836098903790116, 0.0005028664600104094, 0.00016954632883425802, 0.0002791547740343958, 0.000458745751529932 ]
{ "id": 6, "code_window": [ "\t\t}\n", "\t\tthis.activated = true;\n", "\n", "\t\tthis.reloadWorkspaceConfigs();\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "\t\tawait this.reloadWorkspaceConfigs();\n" ], "file_path": "extensions/typescript/src/utils/tsconfigProvider.ts", "type": "replace", "edit_start_line_idx": 39 }
/*--------------------------------------------------------------------------------------------- * 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. { "removeTag": "Emmet: 태그 제거" }
i18n/kor/src/vs/workbench/parts/emmet/electron-browser/actions/removeTag.i18n.json
0
https://github.com/microsoft/vscode/commit/20519a8fe1fe565cd3a7618089beba6d66266b5b
[ 0.00017606963228899986, 0.00017606963228899986, 0.00017606963228899986, 0.00017606963228899986, 0 ]
{ "id": 7, "code_window": [ "\n", "\t\tconst configFileWatcher = vscode.workspace.createFileSystemWatcher('**/tsconfig*.json');\n", "\t\tthis.disposables.push(configFileWatcher);\n", "\t\tconfigFileWatcher.onDidCreate(this.handleProjectCreate, this, this.disposables);\n", "\t\tconfigFileWatcher.onDidDelete(this.handleProjectDelete, this, this.disposables);\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst configFileWatcher = vscode.workspace.createFileSystemWatcher(tsconfigGlob);\n" ], "file_path": "extensions/typescript/src/utils/tsconfigProvider.ts", "type": "replace", "edit_start_line_idx": 41 }
/*--------------------------------------------------------------------------------------------- * 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 fs from 'fs'; import * as path from 'path'; import * as vscode from 'vscode'; import * as Proto from '../protocol'; import TypeScriptServiceClient from '../typescriptServiceClient'; import TsConfigProvider, { TSConfig } from '../utils/tsconfigProvider'; import { isImplicitProjectConfigFile } from '../utils/tsconfig'; import * as nls from 'vscode-nls'; const localize = nls.loadMessageBundle(); const exists = (file: string): Promise<boolean> => new Promise<boolean>((resolve, _reject) => { fs.exists(file, (value: boolean) => { resolve(value); }); }); interface TypeScriptTaskDefinition extends vscode.TaskDefinition { tsconfig: string; } /** * Provides tasks for building `tsconfig.json` files in a project. */ class TscTaskProvider implements vscode.TaskProvider { private readonly tsconfigProvider: TsConfigProvider; public constructor( private readonly lazyClient: () => TypeScriptServiceClient ) { this.tsconfigProvider = new TsConfigProvider(); } dispose() { this.tsconfigProvider.dispose(); } public async provideTasks(token: vscode.CancellationToken): Promise<vscode.Task[]> { const folders = vscode.workspace.workspaceFolders; if (!folders || !folders.length) { return []; } const configPaths: Set<string> = new Set(); const tasks: vscode.Task[] = []; for (const project of await this.getAllTsConfigs(token)) { if (!configPaths.has(project.path)) { configPaths.add(project.path); tasks.push(await this.getBuildTaskForProject(project)); } } return tasks; } public resolveTask(_task: vscode.Task): vscode.Task | undefined { return undefined; } private async getAllTsConfigs(token: vscode.CancellationToken): Promise<TSConfig[]> { const out = new Set<TSConfig>(); const configs = (await this.getTsConfigForActiveFile(token)).concat(await this.getTsConfigsInWorkspace()); for (const config of configs) { if (await exists(config.path)) { out.add(config); } } return Array.from(out); } private async getTsConfigForActiveFile(token: vscode.CancellationToken): Promise<TSConfig[]> { const editor = vscode.window.activeTextEditor; if (editor) { if (path.basename(editor.document.fileName).match(/^tsconfig\.(.\.)?json$/)) { const path = editor.document.uri; const folder = vscode.workspace.getWorkspaceFolder(path); return [{ path: path.fsPath, workspaceFolder: folder }]; } } const file = this.getActiveTypeScriptFile(); if (!file) { return []; } const res: Proto.ProjectInfoResponse = await this.lazyClient().execute( 'projectInfo', { file, needFileNameList: false } as protocol.ProjectInfoRequestArgs, token); if (!res || !res.body) { return []; } const { configFileName } = res.body; if (configFileName && !isImplicitProjectConfigFile(configFileName)) { const path = vscode.Uri.file(configFileName); const folder = vscode.workspace.getWorkspaceFolder(path); return [{ path: configFileName, workspaceFolder: folder }]; } return []; } private async getTsConfigsInWorkspace(): Promise<TSConfig[]> { return Array.from(await this.tsconfigProvider.getConfigsForWorkspace()); } private async getCommand(project: TSConfig): Promise<string> { if (project.workspaceFolder) { const platform = process.platform; const bin = path.join(project.workspaceFolder.uri.fsPath, 'node_modules', '.bin'); if (platform === 'win32' && await exists(path.join(bin, 'tsc.cmd'))) { return path.join(bin, 'tsc.cmd'); } else if ((platform === 'linux' || platform === 'darwin') && await exists(path.join(bin, 'tsc'))) { return path.join(bin, 'tsc'); } } return 'tsc'; } private shouldUseWatchForBuild(configFile: TSConfig): boolean { try { const config = JSON.parse(fs.readFileSync(configFile.path, 'utf-8')); if (config) { return !!config.compileOnSave; } } catch (e) { // noop } return false; } private getActiveTypeScriptFile(): string | null { const editor = vscode.window.activeTextEditor; if (editor) { const document = editor.document; if (document && (document.languageId === 'typescript' || document.languageId === 'typescriptreact')) { return this.lazyClient().normalizePath(document.uri); } } return null; } private async getBuildTaskForProject(project: TSConfig): Promise<vscode.Task> { const command = await this.getCommand(project); let label: string = project.path; if (project.workspaceFolder) { const relativePath = path.relative(project.workspaceFolder.uri.fsPath, project.path); if (vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders.length > 1) { label = path.join(project.workspaceFolder.name, relativePath); } else { label = relativePath; } } const watch = this.shouldUseWatchForBuild(project); const identifier: TypeScriptTaskDefinition = { type: 'typescript', tsconfig: label, watch: watch }; const buildTask = new vscode.Task( identifier, watch ? localize('buildAndWatchTscLabel', 'watch - {0}', label) : localize('buildTscLabel', 'build - {0}', label), 'tsc', new vscode.ShellExecution(`${command} ${watch ? '--watch' : ''} -p "${project.path}"`), '$tsc'); buildTask.group = vscode.TaskGroup.Build; return buildTask; } } type AutoDetect = 'on' | 'off'; /** * Manages registrations of TypeScript task provides with VScode. */ export default class TypeScriptTaskProviderManager { private taskProviderSub: vscode.Disposable | undefined = undefined; private readonly disposables: vscode.Disposable[] = []; constructor( private readonly lazyClient: () => TypeScriptServiceClient ) { vscode.workspace.onDidChangeConfiguration(this.onConfigurationChanged, this, this.disposables); this.onConfigurationChanged(); } dispose() { if (this.taskProviderSub) { this.taskProviderSub.dispose(); this.taskProviderSub = undefined; } this.disposables.forEach(x => x.dispose()); } private onConfigurationChanged() { let autoDetect = vscode.workspace.getConfiguration('typescript.tsc').get<AutoDetect>('autoDetect'); if (this.taskProviderSub && autoDetect === 'off') { this.taskProviderSub.dispose(); this.taskProviderSub = undefined; } else if (!this.taskProviderSub && autoDetect === 'on') { this.taskProviderSub = vscode.workspace.registerTaskProvider('typescript', new TscTaskProvider(this.lazyClient)); } } }
extensions/typescript/src/features/taskProvider.ts
1
https://github.com/microsoft/vscode/commit/20519a8fe1fe565cd3a7618089beba6d66266b5b
[ 0.0010052702855318785, 0.0003711572790052742, 0.00016433738346677274, 0.00019856759172398597, 0.00025811794330365956 ]
{ "id": 7, "code_window": [ "\n", "\t\tconst configFileWatcher = vscode.workspace.createFileSystemWatcher('**/tsconfig*.json');\n", "\t\tthis.disposables.push(configFileWatcher);\n", "\t\tconfigFileWatcher.onDidCreate(this.handleProjectCreate, this, this.disposables);\n", "\t\tconfigFileWatcher.onDidDelete(this.handleProjectDelete, this, this.disposables);\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst configFileWatcher = vscode.workspace.createFileSystemWatcher(tsconfigGlob);\n" ], "file_path": "extensions/typescript/src/utils/tsconfigProvider.ts", "type": "replace", "edit_start_line_idx": 41 }
/*--------------------------------------------------------------------------------------------- * 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. { "showTriggerActions": "Показать все команды", "clearCommandHistory": "Очистить журнал команд", "showCommands.label": "Палитра команд...", "entryAriaLabelWithKey": "{0}, {1}, команды", "entryAriaLabel": "{0}, команды", "canNotRun": "Выполнить команду {0} отсюда невозможно.", "actionNotEnabled": "Команда {0} не разрешена в текущем контексте.", "recentlyUsed": "недавно использованные", "morecCommands": "другие команды", "commandLabel": "{0}: {1}", "cat.title": "{0}: {1}", "noCommandsMatching": "Нет соответствующих команд" }
i18n/rus/src/vs/workbench/parts/quickopen/browser/commandsHandler.i18n.json
0
https://github.com/microsoft/vscode/commit/20519a8fe1fe565cd3a7618089beba6d66266b5b
[ 0.0001724868343444541, 0.00016937268082983792, 0.0001662585127633065, 0.00016937268082983792, 0.0000031141607905738056 ]