AtCoder Easy Test

Make testing sample cases easy

当前为 2020-12-15 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name AtCoder Easy Test
  3. // @namespace http://atcoder.jp/
  4. // @version 1.3.6
  5. // @description Make testing sample cases easy
  6. // @author magurofly
  7. // @match https://atcoder.jp/contests/*/tasks/*
  8. // @grant none
  9. // ==/UserScript==
  10.  
  11. // This script uses variables from page below:
  12. // * `$`
  13. // * `getSourceCode`
  14. // * `csrfToken`
  15.  
  16. // This scripts consists of three modules:
  17. // * bottom menu
  18. // * code runner
  19. // * view
  20.  
  21. (function script() {
  22.  
  23. const VERSION = "1.3.6";
  24.  
  25. if (typeof unsafeWindow !== "undefined") {
  26. console.log(unsafeWindow);
  27. unsafeWindow.eval(`(${script})();`);
  28. console.log("Script run in unsafeWindow");
  29. return;
  30. }
  31. const $ = window.$;
  32. const getSourceCode = window.getSourceCode;
  33. const csrfToken = window.csrfToken;
  34.  
  35. // -- code runner --
  36. const codeRunner = (function() {
  37. 'use strict';
  38.  
  39. function buildParams(data) {
  40. return Object.entries(data).map(([key, value]) =>
  41. encodeURIComponent(key) + "=" + encodeURIComponent(value)).join("&");
  42. }
  43.  
  44. function sleep(ms) {
  45. return new Promise(done => setTimeout(done, ms));
  46. }
  47.  
  48. class CodeRunner {
  49. constructor(label, site) {
  50. this.label = `${label} [${site}]`;
  51. }
  52.  
  53. async test(sourceCode, input, supposedOutput, options) {
  54. const result = await this.run(sourceCode, input);
  55. if (result.status != "OK" || typeof supposedOutput !== "string") return result;
  56. let output = result.stdout || "";
  57.  
  58. if (options.trim) {
  59. supposedOutput = supposedOutput.trim();
  60. output = output.trim();
  61. }
  62.  
  63. let equals = (x, y) => x === y;
  64.  
  65. if ("allowableError" in options) {
  66. const floatPattern = /^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$/;
  67. const superEquals = equals;
  68. equals = (x, y) => {
  69. if (floatPattern.test(x) && floatPattern.test(y)) return Math.abs(parseFloat(x) - parseFloat(y)) <= options.allowableError;
  70. return superEquals(x, y);
  71. }
  72. }
  73.  
  74. if (options.split) {
  75. const superEquals = equals;
  76. equals = (x, y) => {
  77. x = x.split(/\s+/);
  78. y = y.split(/\s+/);
  79. if (x.length != y.length) return false;
  80. const len = x.length;
  81. for (let i = 0; i < len; i++) {
  82. if (!superEquals(x[i], y[i])) return false;
  83. }
  84. return true;
  85. }
  86. }
  87.  
  88. if (equals(output, supposedOutput)) {
  89. result.status = "AC";
  90. } else {
  91. result.status = "WA";
  92. }
  93.  
  94. return result;
  95. }
  96. }
  97.  
  98. class WandboxRunner extends CodeRunner {
  99. constructor(name, label, options = {}) {
  100. super(label, "Wandbox");
  101. this.name = name;
  102. this.options = options;
  103. }
  104.  
  105. run(sourceCode, input) {
  106. let options = this.options;
  107. if (typeof options == "function") options = options(sourceCode, input);
  108. return this.request(Object.assign(JSON.stringify({
  109. compiler: this.name,
  110. code: sourceCode,
  111. stdin: input,
  112. }), this.options));
  113. }
  114.  
  115. async request(body) {
  116. const startTime = Date.now();
  117. let res;
  118. try {
  119. res = await fetch("https://wandbox.org/api/compile.json", {
  120. method: "POST",
  121. mode: "cors",
  122. headers: {
  123. "Content-Type": "application/json",
  124. },
  125. body,
  126. }).then(r => r.json());
  127. } catch (error) {
  128. return {
  129. status: "IE",
  130. stderr: error,
  131. };
  132. }
  133. const endTime = Date.now();
  134.  
  135. const result = {
  136. status: "OK",
  137. exitCode: res.status,
  138. execTime: endTime - startTime,
  139. stdout: res.program_output,
  140. stderr: res.program_error,
  141. };
  142. if (res.status != 0) {
  143. if (res.signal) {
  144. result.exitCode += " (" + res.signal + ")";
  145. }
  146. result.stdout = (res.compiler_output || "") + (result.stdout || "");
  147. result.stderr = (res.compiler_error || "") + (result.stderr || "");
  148. if (res.compiler_output || res.compiler_error) {
  149. result.status = "CE";
  150. } else {
  151. result.status = "RE";
  152. }
  153. }
  154.  
  155. return result;
  156. }
  157. }
  158.  
  159. class PaizaIORunner extends CodeRunner {
  160. constructor(name, label) {
  161. super(label, "PaizaIO");
  162. this.name = name;
  163. }
  164.  
  165. async run(sourceCode, input) {
  166. let id, status, error;
  167. try {
  168. const res = await fetch("https://api.paiza.io/runners/create?" + buildParams({
  169. source_code: sourceCode,
  170. language: this.name,
  171. input,
  172. longpoll: true,
  173. longpoll_timeout: 10,
  174. api_key: "guest",
  175. }), {
  176. method: "POST",
  177. mode: "cors",
  178. }).then(r => r.json());
  179. id = res.id;
  180. status = res.status;
  181. error = res.error;
  182. } catch (error) {
  183. return {
  184. status: "IE",
  185. stderr: error,
  186. };
  187. }
  188.  
  189. while (status == "running") {
  190. const res = await (await fetch("https://api.paiza.io/runners/get_status?" + buildParams({
  191. id,
  192. api_key: "guest",
  193. }), {
  194. mode: "cors",
  195. })).json();
  196. status = res.status;
  197. error = res.error;
  198. }
  199.  
  200. const res = await fetch("https://api.paiza.io/runners/get_details?" + buildParams({
  201. id,
  202. api_key: "guest",
  203. }), {
  204. mode: "cors",
  205. }).then(r => r.json());
  206.  
  207. const result = {
  208. exitCode: res.exit_code,
  209. execTime: +res.time * 1e3,
  210. memory: +res.memory * 1e-3,
  211. };
  212.  
  213. if (res.build_result == "failure") {
  214. result.status = "CE";
  215. result.exitCode = res.build_exit_code;
  216. result.stdout = res.build_stdout;
  217. result.stderr = res.build_stderr;
  218. } else {
  219. result.status = (res.result == "timeout") ? "TLE" : (res.result == "failure") ? "RE" : "OK";
  220. result.exitCode = res.exit_code;
  221. result.stdout = res.stdout;
  222. result.stderr = res.stderr;
  223. }
  224.  
  225. return result;
  226. }
  227. }
  228.  
  229. const loader = {
  230. loaded: {},
  231. async load(url, options = { mode: "cors", }) {
  232. if (!(url in this.loaded)) {
  233. this.loaded[url] = await fetch(url, options);
  234. }
  235. return this.loaded[url];
  236. },
  237. };
  238.  
  239. class WandboxCppRunner extends WandboxRunner {
  240. async run(sourceCode, input) {
  241. const allFiles = ["convolution", "dsu", "fenwicktree", "internal_bit", "internal_math", "internal_queue", "internal_scc", "internal_type_traits", "lazysegtree", "math", "maxflow", "mincostflow", "modint", "scc", "segtree", "string", "twosat"];
  242. const files = new Set(["all"].concat(allFiles).filter(file => new RegExp(String.raw`^#\s*include\s*<atcoder/${file}>`, "m").test(sourceCode)));
  243. let allHeaders = false;
  244. if (files.has("all")) {
  245. allHeaders = true;
  246. files.delete("all");
  247. for (const file of allFiles) {
  248. files.add(file);
  249. }
  250. }
  251.  
  252. if (files.has("convolution")) {
  253. files.add("modint");
  254. }
  255. if (files.has("convolution") || files.has("lazysegtree") || files.has("segtree")) {
  256. files.add("internal_bit");
  257. }
  258. if (files.has("maxflow")) {
  259. files.add("internal_queue");
  260. }
  261. if (files.has("scc") || files.has("twosat")) {
  262. files.add("internal_scc");
  263. }
  264. if (files.has("math") || files.has("modint")) {
  265. files.add("internal_math");
  266. }
  267. if (files.has("fenwicktree") || files.has("fenwicktree")) {
  268. files.add("internal_type_traits");
  269. }
  270.  
  271. const ACLBase = "https://cdn.jsdelivr.net/gh/atcoder/ac-library/atcoder/";
  272.  
  273. const codePromises = [];
  274. const codes = [];
  275. for (const file of files) {
  276. codePromises.push(fetch(ACLBase + file + ".hpp", {
  277. mode: "cors",
  278. cache: "force-cache",
  279. })
  280. .then(r => r.text())
  281. .then(code => codes.push({ file: "atcoder/" + file, code })));
  282. }
  283. if (allHeaders) {
  284. codePromises.push(fetch(ACLBase + "all", {
  285. mode: "cors",
  286. cache: "force-cache",
  287. })
  288. .then(r => r.text())
  289. .then(code => codes.push({ file: "atcoder/all", code })));
  290. }
  291.  
  292. await Promise.all(codePromises);
  293.  
  294.  
  295. let options = this.options;
  296. if (typeof options == "function") options = options(sourceCode, input);
  297. return await this.request(JSON.stringify(Object.assign({
  298. compiler: this.name,
  299. code: sourceCode,
  300. stdin: input,
  301. codes,
  302. "compiler-option-raw": "-I.",
  303. }, options)));
  304. }
  305. }
  306.  
  307. let waitAtCoderCustomTest = Promise.resolve();
  308. const AtCoderCustomTestBase = location.href.replace(/\/tasks\/.+$/, "/custom_test");
  309. const AtCoderCustomTestResultAPI = AtCoderCustomTestBase + "/json?reload=true";
  310. const AtCoderCustomTestSubmitAPI = AtCoderCustomTestBase + "/submit/json";
  311. class AtCoderRunner extends CodeRunner {
  312. constructor(languageId, label) {
  313. super(label, "AtCoder");
  314. this.languageId = languageId;
  315. }
  316.  
  317. async run(sourceCode, input) {
  318. const promise = this.submit(sourceCode, input);
  319. waitAtCoderCustomTest = promise;
  320. return await promise;
  321. }
  322.  
  323. async submit(sourceCode, input) {
  324. try {
  325. await waitAtCoderCustomTest;
  326. } catch (error) {
  327. console.error(error);
  328. }
  329.  
  330. const error = await fetch(AtCoderCustomTestSubmitAPI, {
  331. method: "POST",
  332. credentials: "include",
  333. headers: {
  334. "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
  335. },
  336. body: buildParams({
  337. "data.LanguageId": this.languageId,
  338. sourceCode,
  339. input,
  340. csrf_token: csrfToken,
  341. }),
  342. }).then(r => r.text());
  343.  
  344. if (error) {
  345. throw new Error(error)
  346. }
  347.  
  348. await sleep(100);
  349.  
  350. for (;;) {
  351. const data = await fetch(AtCoderCustomTestResultAPI, {
  352. method: "GET",
  353. credentials: "include",
  354. }).then(r => r.json());
  355.  
  356. if (!("Result" in data)) continue;
  357. const result = data.Result;
  358.  
  359. if ("Interval" in data) {
  360. await sleep(data.Interval);
  361. continue;
  362. }
  363.  
  364. return {
  365. status: (result.ExitCode == 0) ? "OK" : (result.TimeConsumption == -1) ? "CE" : "RE",
  366. exitCode: result.ExitCode,
  367. execTime: result.TimeConsumption,
  368. memory: result.MemoryConsumption,
  369. stdout: data.Stdout,
  370. stderr: data.Stderr,
  371. };
  372. }
  373. }
  374. }
  375.  
  376. const runners = {
  377. 4001: [new WandboxRunner("gcc-9.2.0-c", "C (GCC 9.2.0)")],
  378. 4002: [new PaizaIORunner("c", "C (C17 / Clang 10.0.0)", )],
  379. 4003: [new WandboxCppRunner("gcc-9.2.0", "C++ (GCC 9.2.0)", {options: "warning,boost-1.73.0-gcc-9.2.0,gnu++17"})],
  380. 4004: [new WandboxCppRunner("clang-10.0.0", "C++ (Clang 10.0.0)", {options: "warning,boost-nothing-clang-10.0.0,c++17"})],
  381. 4006: [new PaizaIORunner("python3", "Python (3.8.2)")],
  382. 4007: [new PaizaIORunner("bash", "Bash (5.0.17)")],
  383. 4010: [new WandboxRunner("csharp", "C# (.NET Core 6.0.100-alpha.1.20562.2)")],
  384. 4011: [new WandboxRunner("mono-head", "C# (Mono-mcs 5.19.0.0)")],
  385. 4013: [new PaizaIORunner("clojure", "Clojure (1.10.1-1)")],
  386. 4017: [new PaizaIORunner("d", "D (LDC 1.23.0)")],
  387. 4020: [new PaizaIORunner("erlang", "Erlang (10.6.4)")],
  388. 4021: [new PaizaIORunner("elixir", "Elixir (1.10.4)")],
  389. 4022: [new PaizaIORunner("fsharp", "F# (Interactive 4.0)")],
  390. 4023: [new PaizaIORunner("fsharp", "F# (Interactive 4.0)")],
  391. 4026: [new WandboxRunner("go-1.14.1", "Go (1.14.1)")],
  392. 4027: [new WandboxRunner("ghc-head", "Haskell (GHC 8.7.20181121)")],
  393. 4030: [new PaizaIORunner("javascript", "JavaScript (Node.js 12.18.3)")],
  394. 4032: [new PaizaIORunner("kotlin", "Kotlin (1.4.0)")],
  395. 4033: [new WandboxRunner("lua-5.3.4", "Lua (Lua 5.3.4)")],
  396. 4034: [new WandboxRunner("luajit-head", "Lua (LuaJIT 2.1.0-beta3)")],
  397. 4036: [new WandboxRunner("nim-1.0.6", "Nim (1.0.6)")],
  398. 4037: [new PaizaIORunner("objective-c", "Objective-C (Clang 10.0.0)")],
  399. 4039: [new WandboxRunner("ocaml-head", "OCaml (4.13.0+dev0-2020-10-19)")],
  400. 4041: [new WandboxRunner("fpc-3.0.2", "Pascal (FPC 3.0.2)")],
  401. 4042: [new PaizaIORunner("perl", "Perl (5.30.0)")],
  402. 4044: [
  403. new PaizaIORunner("php", "PHP (7.4.10)"),
  404. new WandboxRunner("php-7.3.3", "PHP (7.3.3)"),
  405. ],
  406. 4046: [new WandboxRunner("pypy-head", "PyPy2 (7.3.4-alpha0)")],
  407. 4047: [new WandboxRunner("pypy-7.2.0-3", "PyPy3 (7.2.0)")],
  408. 4049: [
  409. new WandboxRunner("ruby-head", "Ruby (HEAD 3.0.0dev)"),
  410. new PaizaIORunner("ruby", "Ruby (2.7.1)"),
  411. new WandboxRunner("ruby-2.7.0-preview1", "Ruby (2.7.0-preview1)"),
  412. ],
  413. 4050: [
  414. new AtCoderRunner(4050, "Rust (1.42.0)"),
  415. new WandboxRunner("rust-head", "Rust (1.37.0-dev)"),
  416. new PaizaIORunner("rust", "Rust (1.43.0)"),
  417. ],
  418. 4051: [new PaizaIORunner("scala", "Scala (2.13.3)")],
  419. 4053: [new PaizaIORunner("scheme", "Scheme (Gauche 0.9.6)")],
  420. 4055: [new PaizaIORunner("swift", "Swift (5.2.5)")],
  421. 4056: [{
  422. label: "Text (JavaScript)",
  423. async run(sourceCode, input) {
  424. return {
  425. status: "OK",
  426. exitCode: 0,
  427. stdout: sourceCode,
  428. };
  429. },
  430. }],
  431. 4058: [new PaizaIORunner("vb", "Visual Basic (.NET Core 4.0.1)")],
  432. 4061: [new PaizaIORunner("cobol", "COBOL - Free (OpenCOBOL 2.2.0)")],
  433. 4101: [new WandboxCppRunner("gcc-9.2.0", "C++ (GCC 9.2.0)")],
  434. 4102: [new WandboxCppRunner("clang-10.0.0", "C++ (Clang 10.0.0)")],
  435. };
  436.  
  437. $("#select-lang option[value]").each((_, e) => {
  438. const elem = $(e);
  439. const languageId = elem.val();
  440. if (!(languageId in runners)) runners[languageId] = [];
  441. if (runners[languageId].some(runner => runner instanceof AtCoderRunner)) return;
  442. runners[languageId].push(new AtCoderRunner(languageId, elem.text()));
  443. });
  444.  
  445. console.info("codeRunner OK");
  446.  
  447. return {
  448. run(languageId, index, sourceCode, input, supposedOutput = null, options = { trim: true, split: true, }) {
  449. if (!(languageId in runners)) {
  450. return Promise.reject("language not supported");
  451. }
  452. return runners[languageId][index].test(sourceCode, input, supposedOutput, options);
  453. },
  454.  
  455. getEnvironment(languageId) {
  456. if (!(languageId in runners)) {
  457. return Promise.reject("language not supported");
  458. }
  459. return Promise.resolve(runners[languageId].map(runner => runner.label));
  460. },
  461. };
  462. })();
  463.  
  464.  
  465. // -- bottom menu --
  466. const bottomMenu = (function () {
  467. 'use strict';
  468.  
  469. const tabs = new Set();
  470.  
  471. const bottomMenuKey = $(`<button id="bottom-menu-key" type="button" class="navbar-toggle collapsed glyphicon glyphicon-menu-down" data-toggle="collapse" data-target="#bottom-menu">`);
  472. const bottomMenuTabs = $(`<ul id="bottom-menu-tabs" class="nav nav-tabs">`);
  473. const bottomMenuContents = $(`<div id="bottom-menu-contents" class="tab-content">`);
  474.  
  475. $(() => {
  476. $(`<style>`)
  477. .text(`
  478.  
  479. #bottom-menu-wrapper {
  480. background: transparent;
  481. border: none;
  482. pointer-events: none;
  483. padding: 0;
  484. }
  485.  
  486. #bottom-menu-wrapper>.container {
  487. position: absolute;
  488. bottom: 0;
  489. width: 100%;
  490. padding: 0;
  491. }
  492.  
  493. #bottom-menu-wrapper>.container>.navbar-header {
  494. float: none;
  495. }
  496.  
  497. #bottom-menu-key {
  498. display: block;
  499. float: none;
  500. margin: 0 auto;
  501. padding: 10px 3em;
  502. border-radius: 5px 5px 0 0;
  503. background: #000;
  504. opacity: 0.85;
  505. color: #FFF;
  506. cursor: pointer;
  507. pointer-events: auto;
  508. text-align: center;
  509. }
  510.  
  511. #bottom-menu-key.collapsed:before {
  512. content: "\\e260";
  513. }
  514.  
  515. #bottom-menu-tabs {
  516. padding: 3px 0 0 10px;
  517. cursor: n-resize;
  518. }
  519.  
  520. #bottom-menu-tabs a {
  521. pointer-events: auto;
  522. }
  523.  
  524. #bottom-menu {
  525. pointer-events: auto;
  526. background: rgba(0, 0, 0, 0.8);
  527. color: #fff;
  528. max-height: unset;
  529. }
  530.  
  531. #bottom-menu.collapse:not(.in) {
  532. display: none !important;
  533. }
  534.  
  535. #bottom-menu-tabs>li>a {
  536. background: rgba(100, 100, 100, 0.5);
  537. border: solid 1px #ccc;
  538. color: #fff;
  539. }
  540.  
  541. #bottom-menu-tabs>li>a:hover {
  542. background: rgba(150, 150, 150, 0.5);
  543. border: solid 1px #ccc;
  544. color: #333;
  545. }
  546.  
  547. #bottom-menu-tabs>li.active>a {
  548. background: #eee;
  549. border: solid 1px #ccc;
  550. color: #333;
  551. }
  552.  
  553. .bottom-menu-btn-close {
  554. font-size: 8pt;
  555. vertical-align: baseline;
  556. padding: 0 0 0 6px;
  557. margin-right: -6px;
  558. }
  559.  
  560. #bottom-menu-contents {
  561. padding: 5px 15px;
  562. max-height: 50vh;
  563. overflow-y: auto;
  564. }
  565.  
  566. #bottom-menu-contents .panel {
  567. color: #333;
  568. }
  569.  
  570. `)
  571. .appendTo("head");
  572. const bottomMenu = $(`<div id="bottom-menu" class="collapse navbar-collapse">`).append(bottomMenuTabs, bottomMenuContents);
  573. $(`<div id="bottom-menu-wrapper" class="navbar navbar-default navbar-fixed-bottom">`)
  574. .append($(`<div class="container">`)
  575. .append(
  576. $(`<div class="navbar-header">`).append(bottomMenuKey),
  577. bottomMenu))
  578. .appendTo("#main-div");
  579.  
  580. let resizeStart = null;
  581. bottomMenuTabs.on({
  582. mousedown({target, pageY}) {
  583. if (!$(target).is("#bottom-menu-tabs")) return;
  584. resizeStart = {y: pageY, height: bottomMenuContents.height()};
  585. },
  586. mousemove(e) {
  587. if (!resizeStart) return;
  588. e.preventDefault();
  589. bottomMenuContents.height(resizeStart.height - (e.pageY - resizeStart.y));
  590. },
  591. });
  592. $(document).on({
  593. mouseup() {
  594. resizeStart = null;
  595. },
  596. mouseleave() {
  597. resizeStart = null;
  598. },
  599. });
  600. });
  601.  
  602. const menuController = {
  603. addTab(tabId, tabLabel, paneContent, options = {}) {
  604. console.log("addTab: %s (%s)", tabLabel, tabId, paneContent);
  605. const tab = $(`<a id="bottom-menu-tab-${tabId}" href="#" data-target="#bottom-menu-pane-${tabId}" data-toggle="tab">`)
  606. .click(e => {
  607. e.preventDefault();
  608. tab.tab("show");
  609. })
  610. .append(tabLabel);
  611. const tabLi = $(`<li>`).append(tab).appendTo(bottomMenuTabs);
  612. const pane = $(`<div class="tab-pane" id="bottom-menu-pane-${tabId}">`).append(paneContent).appendTo(bottomMenuContents);
  613. console.dirxml(bottomMenuContents);
  614. const controller = {
  615. close() {
  616. tabLi.remove();
  617. pane.remove();
  618. tabs.delete(tab);
  619. if (tabLi.hasClass("active") && tabs.size > 0) {
  620. tabs.values().next().value.tab("show");
  621. }
  622. },
  623.  
  624. show() {
  625. menuController.show();
  626. tab.tab("show");
  627. }
  628. };
  629. tabs.add(tab);
  630. if (options.closeButton) tab.append($(`<a class="bottom-menu-btn-close btn btn-link glyphicon glyphicon-remove">`).click(() => controller.close()));
  631. if (options.active || tabs.size == 1) pane.ready(() => tab.tab("show"));
  632. return controller;
  633. },
  634.  
  635. show() {
  636. if (bottomMenuKey.hasClass("collapsed")) bottomMenuKey.click();
  637. },
  638.  
  639. toggle() {
  640. bottomMenuKey.click();
  641. },
  642. };
  643.  
  644. console.info("bottomMenu OK");
  645.  
  646. return menuController;
  647. })();
  648.  
  649. $(() => {
  650. async function runTest(title, input, output = null) {
  651. const uid = Date.now().toString();
  652. title = title ? "Result " + title : "Result";
  653. const content = $(`<div class="container">`)
  654. .html(`
  655. <div class="row"><div class="form-group">
  656. <label class="control-label col-sm-2" for="atcoder-easy-test-${uid}-stdin">Standard Input</label>
  657. <div class="col-sm-8">
  658. <textarea id="atcoder-easy-test-${uid}-stdin" class="form-control" rows="5" readonly></textarea>
  659. </div>
  660. </div></div>
  661. <div class="row"><div class="col-sm-4 col-sm-offset-4">
  662. <div class="panel panel-default"><table class="table table-bordered">
  663. <tr id="atcoder-easy-test-${uid}-row-exit-code">
  664. <th class="text-center">Exit Code</th>
  665. <td id="atcoder-easy-test-${uid}-exit-code" class="text-right"></td>
  666. </tr>
  667. <tr id="atcoder-easy-test-${uid}-row-exec-time">
  668. <th class="text-center">Exec Time</th>
  669. <td id="atcoder-easy-test-${uid}-exec-time" class="text-right"></td>
  670. </tr>
  671. <tr id="atcoder-easy-test-${uid}-row-memory">
  672. <th class="text-center">Memory</th>
  673. <td id="atcoder-easy-test-${uid}-memory" class="text-right"></td>
  674. </tr>
  675. </table></div>
  676. </div></div>
  677. <div class="row"><div class="form-group">
  678. <label class="control-label col-sm-2" for="atcoder-easy-test-${uid}-stdout">Standard Output</label>
  679. <div class="col-sm-8">
  680. <textarea id="atcoder-easy-test-${uid}-stdout" class="form-control" rows="5" readonly></textarea>
  681. </div>
  682. </div></div>
  683. <div class="row"><div class="form-group">
  684. <label class="control-label col-sm-2" for="atcoder-easy-test-${uid}-stderr">Standard Error</label>
  685. <div class="col-sm-8">
  686. <textarea id="atcoder-easy-test-${uid}-stderr" class="form-control" rows="5" readonly></textarea>
  687. </div>
  688. </div></div>
  689. `);
  690. const tab = bottomMenu.addTab("easy-test-result-" + uid, title, content, { active: true, closeButton: true });
  691. $(`#atcoder-easy-test-${uid}-stdin`).val(input);
  692.  
  693. const options = { trim: true, split: true, };
  694. if ($("#atcoder-easy-test-allowable-error-check").prop("checked")) {
  695. options.allowableError = parseFloat($("#atcoder-easy-test-allowable-error").val());
  696. }
  697.  
  698. const result = await codeRunner.run($("#select-lang>select").val(), +$("#atcoder-easy-test-language").val(), window.getSourceCode(), input, output, options);
  699.  
  700. $(`#atcoder-easy-test-${uid}-row-exit-code`).toggleClass("bg-danger", result.exitCode != 0).toggleClass("bg-success", result.exitCode == 0);
  701. $(`#atcoder-easy-test-${uid}-exit-code`).text(result.exitCode);
  702. if ("execTime" in result) $(`#atcoder-easy-test-${uid}-exec-time`).text(result.execTime + " ms");
  703. if ("memory" in result) $(`#atcoder-easy-test-${uid}-memory`).text(result.memory + " KB");
  704. $(`#atcoder-easy-test-${uid}-stdout`).val(result.stdout);
  705. $(`#atcoder-easy-test-${uid}-stderr`).val(result.stderr);
  706.  
  707. result.uid = uid;
  708. result.tab = tab;
  709. return result;
  710. }
  711.  
  712. console.log("bottomMenu", bottomMenu);
  713.  
  714. bottomMenu.addTab("easy-test", "Easy Test", $(`<form id="atcoder-easy-test-container" class="form-horizontal">`)
  715. .html(`
  716. <small style="position: absolute; bottom: 0; right: 0;">AtCoder Easy Test v${VERSION}</small>
  717. <div class="row">
  718. <div class="col-12 col-md-10">
  719. <div class="form-group">
  720. <label class="control-label col-sm-2">Test Environment</label>
  721. <div class="col-sm-8">
  722. <select class="form-control" id="atcoder-easy-test-language"></select>
  723. <!--input id="atcoder-easy-test-language" type="text" class="form-control" readonly-->
  724. </div>
  725. </div>
  726. </div>
  727. </div>
  728. <div class="row">
  729. <div class="col-12 col-md-10">
  730. <div class="form-group">
  731. <label class="control-label col-sm-2" for="atcoder-easy-test-allowable-error-check">Allowable Error</label>
  732. <div class="col-sm-8">
  733. <div class="input-group">
  734. <span class="input-group-addon">
  735. <input id="atcoder-easy-test-allowable-error-check" type="checkbox" checked>
  736. </span>
  737. <input id="atcoder-easy-test-allowable-error" type="text" class="form-control" value="1e-6">
  738. </div>
  739. </div>
  740. </div>
  741. </div>
  742. </div>
  743. <div class="row">
  744. <div class="col-12 col-md-10">
  745. <div class="form-group">
  746. <label class="control-label col-sm-2" for="atcoder-easy-test-input">Standard Input</label>
  747. <div class="col-sm-8">
  748. <textarea id="atcoder-easy-test-input" name="input" class="form-control" rows="5"></textarea>
  749. </div>
  750. </div>
  751. </div>
  752. <div class="col-12 col-md-4">
  753. <label class="control-label col-sm-2"></label>
  754. <div class="form-group">
  755. <div class="col-sm-8">
  756. <a id="atcoder-easy-test-run" class="btn btn-primary">Run</a>
  757. </div>
  758. </div>
  759. </div>
  760. </div>
  761. <style>
  762. #atcoder-easy-test-language {
  763. border: none;
  764. background: transparent;
  765. font: inherit;
  766. color: #fff;
  767. }
  768. #atcoder-easy-test-language option {
  769. border: none;
  770. color: #333;
  771. font: inherit;
  772. }
  773. </style>
  774. `).ready(() => {
  775. $("#atcoder-easy-test-run").click(() => runTest("", $("#atcoder-easy-test-input").val()));
  776. $("#select-lang>select").on("change", () => setLanguage());
  777. $("#atcoder-easy-test-allowable-error").attr("disabled", this.checked);
  778. $("#atcoder-easy-test-allowable-error-check").on("change", function () {
  779. $("#atcoder-easy-test-allowable-error").attr("disabled", !this.checked);
  780. });
  781.  
  782. function setLanguage() {
  783. const languageId = $("#select-lang>select").val();
  784. codeRunner.getEnvironment(languageId).then(labels => {
  785. console.log(`language: ${labels[0]} (${languageId})`);
  786. $("#atcoder-easy-test-language").css("color", "#fff").empty().append(labels.map((label, index) => $(`<option>`).val(index).text(label)));
  787. $("#atcoder-easy-test-run").removeClass("disabled");
  788. $("#atcoder-easy-test-btn-test-all").attr("disabled", false);
  789. }, error => {
  790. console.log(`language: ? (${languageId})`);
  791. $("#atcoder-easy-test-language").css("color", "#f55").empty().append($(`<option>`).text(error));
  792. $("#atcoder-easy-test-run").addClass("disabled");
  793. $("#atcoder-easy-test-btn-test-all").attr("disabled", true);
  794. });
  795. }
  796.  
  797. setLanguage();
  798. }), { active: true });
  799.  
  800. const testfuncs = [];
  801. const runButtons = [];
  802.  
  803. const testcases = $("#task-statement .div-btn-copy+pre").toArray().filter(e => e.offsetParent && !$(e).closest(".io-style")[0]);
  804. for (let i = 0; i < testcases.length; i += 2) {
  805. const input = $(testcases[i]), output = $(testcases[i+1]);
  806. const testfunc = async () => {
  807. const title = input.closest(".part").find("h3")[0].childNodes[0].data;
  808. const result = await runTest(title, input.text(), output.text());
  809. if (result.status == "OK" || result.status == "AC") {
  810. $(`#atcoder-easy-test-${result.uid}-stdout`).addClass("bg-success");
  811. }
  812. return result;
  813. };
  814. testfuncs.push(testfunc);
  815.  
  816. const runButton = $(`<a class="btn btn-primary btn-sm" style="vertical-align: top; margin-left: 0.5em">`)
  817. .text("Run")
  818. .click(async () => {
  819. await testfunc();
  820. if ($("#bottom-menu-key").hasClass("collapsed")) $("#bottom-menu-key").click();
  821. });
  822. input.closest(".part").find(".btn-copy").eq(0).after(runButton);
  823. runButtons.push(runButton);
  824. }
  825.  
  826. const testAllResultRow = $(`<div class="row">`);
  827. const testAllButton = $(`<a id="atcoder-easy-test-btn-test-all" class="btn btn-default btn-sm" style="margin-left: 5px">`)
  828. .text("Test All Samples")
  829. .attr({
  830. title: "Alt+Enter",
  831. "data-toggle": "tooltip",
  832. })
  833. .click(async () => {
  834. if (testAllButton.attr("disabled")) throw new Error("Button is disabled");
  835. const statuses = testfuncs.map(_ => $(`<div class="label label-default" style="margin: 3px">`).text("WJ..."));
  836. const progress = $(`<div class="progress-bar">`).text(`0 / ${testfuncs.length}`);
  837. let finished = 0;
  838. const closeButton = $(`<button type="button" class="close" data-dismiss="alert" aria-label="close">`)
  839. .append($(`<span aria-hidden="true">`).text("\xd7"));
  840. const resultAlert = $(`<div class="alert alert-dismissible">`)
  841. .append(closeButton)
  842. .append($(`<div class="progress">`).append(progress))
  843. .append(...statuses)
  844. .appendTo(testAllResultRow);
  845. const results = await Promise.all(testfuncs.map(async (testfunc, i) => {
  846. const result = await testfunc();
  847. finished++;
  848. progress.text(`${finished} / ${statuses.length}`).css("width", `${finished/statuses.length*100}%`);
  849. statuses[i].toggleClass("label-success", result.status == "AC").toggleClass("label-warning", result.status != "AC").text(result.status).click(() => result.tab.show()).css("cursor", "pointer");
  850. return result;
  851. }));
  852. if (results.every(({status}) => status == "AC")) {
  853. resultAlert.addClass("alert-success");
  854. } else {
  855. resultAlert.addClass("alert-warning");
  856. }
  857. closeButton.click(() => {
  858. for (const {tab} of results) {
  859. tab.close();
  860. }
  861. });
  862. });
  863. $("#submit").after(testAllButton).closest("form").append(testAllResultRow);
  864. $(document).on("keydown", e => {
  865. if (e.altKey) {
  866. switch (e.key) {
  867. case "Enter":
  868. testAllButton.click();
  869. break;
  870. case "Escape":
  871. bottomMenu.toggle();
  872. break;
  873. }
  874. }
  875. });
  876.  
  877. console.info("view OK");
  878. });
  879.  
  880. })();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址