AtCoder Easy Test v2

Make testing sample cases easy

As of 2023-04-23. See the latest version.

  1. // ==UserScript==
  2. // @name AtCoder Easy Test v2
  3. // @namespace https://atcoder.jp/
  4. // @version 2.11.5
  5. // @description Make testing sample cases easy
  6. // @author magurofly
  7. // @license MIT
  8. // @supportURL https://github.com/magurofly/atcoder-easy-test/
  9. // @match https://atcoder.jp/contests/*/tasks/*
  10. // @match https://atcoder.jp/contests/*/submit*
  11. // @match https://yukicoder.me/problems/no/*
  12. // @match https://yukicoder.me/problems/*
  13. // @match http://codeforces.com/contest/*/problem/*
  14. // @match http://codeforces.com/gym/*/problem/*
  15. // @match http://codeforces.com/problemset/problem/*
  16. // @match http://codeforces.com/group/*/contest/*/problem/*
  17. // @match http://*.contest.codeforces.com/group/*/contest/*/problem/*
  18. // @match https://codeforces.com/contest/*/problem/*
  19. // @match https://codeforces.com/gym/*/problem/*
  20. // @match https://codeforces.com/problemset/problem/*
  21. // @match https://codeforces.com/group/*/contest/*/problem/*
  22. // @match https://*.contest.codeforces.com/group/*/contest/*/problem/*
  23. // @match https://m1.codeforces.com/contest/*/problem/*
  24. // @match https://m2.codeforces.com/contest/*/problem/*
  25. // @match https://m3.codeforces.com/contest/*/problem/*
  26. // @match https://greatest.deepsurf.us/*/scripts/433152-atcoder-easy-test-v2
  27. // @grant unsafeWindow
  28. // @grant GM_getValue
  29. // @grant GM_setValue
  30. // ==/UserScript==
  31. (function() {
  32.  
  33. if (typeof GM_getValue !== "function") {
  34. if (typeof GM === "object" && typeof GM.getValue === "function") {
  35. GM_getValue = GM.getValue;
  36. GM_setValue = GM.setValeu;
  37. } else {
  38. const storage = JSON.parse(localStorage.AtCoderEasyTest || "{}");
  39. GM_getValue = (key, defaultValue = null) => ((key in storage) ? storage[key] : defaultValue);
  40. GM_setValue = (key, value) => {
  41. storage[key] = value;
  42. localStorage.AtCoderEasyTest = JSON.stringify(storage);
  43. };
  44. }
  45. }
  46.  
  47. if (typeof unsafeWindow !== "object") unsafeWindow = window;
  48. function buildParams(data) {
  49. return Object.entries(data).map(([key, value]) => encodeURIComponent(key) + "=" + encodeURIComponent(value)).join("&");
  50. }
  51. function sleep(ms) {
  52. return new Promise(done => setTimeout(done, ms));
  53. }
  54. function doneOrFail(p) {
  55. return p.then(() => Promise.resolve(), () => Promise.resolve());
  56. }
  57. function html2element(html) {
  58. const template = document.createElement("template");
  59. template.innerHTML = html;
  60. return template.content.firstChild;
  61. }
  62. function newElement(tagName, attrs = {}, children = []) {
  63. const e = document.createElement(tagName);
  64. for (const [key, value] of Object.entries(attrs)) {
  65. if (key == "style") {
  66. for (const [propKey, propValue] of Object.entries(value)) {
  67. e.style[propKey] = propValue;
  68. }
  69. }
  70. else {
  71. e[key] = value;
  72. }
  73. }
  74. for (const child of children) {
  75. e.appendChild(child);
  76. }
  77. return e;
  78. }
  79. function uuid() {
  80. return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".
  81. replace(/x/g, () => "0123456789abcdef"[Math.random() * 16 | 0]).
  82. replace(/y/g, () => "89ab"[Math.random() * 4 | 0]);
  83. }
  84. async function loadScript(src, ctx = null, env = {}) {
  85. const js = await fetch(src).then(res => res.text());
  86. const keys = [];
  87. const values = [];
  88. for (const [key, value] of Object.entries(env)) {
  89. keys.push(key);
  90. values.push(value);
  91. }
  92. unsafeWindow["Function"](keys.join(), js).apply(ctx, values);
  93. }
  94. const eventListeners = {};
  95. const events = {
  96. on(name, listener) {
  97. const listeners = (name in eventListeners ? eventListeners[name] : eventListeners[name] = []);
  98. listeners.push(listener);
  99. },
  100. trig(name) {
  101. if (name in eventListeners) {
  102. for (const listener of eventListeners[name])
  103. listener();
  104. }
  105. },
  106. };
  107. class ObservableValue {
  108. _value;
  109. _listeners;
  110. constructor(value) {
  111. this._value = value;
  112. this._listeners = new Set();
  113. }
  114. get value() {
  115. return this._value;
  116. }
  117. set value(value) {
  118. this._value = value;
  119. for (const listener of this._listeners)
  120. listener(value);
  121. }
  122. addListener(listener) {
  123. this._listeners.add(listener);
  124. listener(this._value);
  125. }
  126. removeListener(listener) {
  127. this._listeners.delete(listener);
  128. }
  129. map(f) {
  130. const y = new ObservableValue(f(this.value));
  131. this.addListener(x => {
  132. y.value = f(x);
  133. });
  134. return y;
  135. }
  136. }
  137.  
  138. var hPage = "<!DOCTYPE html>\n<html>\n <head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n <title>AtCoder Easy Test</title>\n <link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css\" rel=\"stylesheet\">\n </head>\n <body>\n <div class=\"container\" id=\"root\">\n </div>\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js\"></script>\n </body>\n</html>";
  139.  
  140. const components = [];
  141. const settings = {
  142. add(title, generator) {
  143. components.push({ title, generator });
  144. },
  145. open() {
  146. const win = window.open("about:blank");
  147. const doc = win.document;
  148. doc.open();
  149. doc.write(hPage);
  150. doc.close();
  151. const root = doc.getElementById("root");
  152. for (const { title, generator } of components) {
  153. const panel = newElement("div", { className: "panel panel-default" }, [
  154. newElement("div", { className: "panel-heading", textContent: title }),
  155. newElement("div", { className: "panel-body" }, [generator(win)]),
  156. ]);
  157. root.appendChild(panel);
  158. }
  159. },
  160. };
  161.  
  162. const options = [];
  163. let data = {};
  164. function toString() {
  165. return JSON.stringify(data);
  166. }
  167. function save() {
  168. GM_setValue("config", toString());
  169. }
  170. function load() {
  171. data = JSON.parse(GM_getValue("config") || "{}");
  172. }
  173. function reset() {
  174. data = {};
  175. save();
  176. }
  177. load();
  178. // 設定ページ
  179. settings.add("config", (win) => {
  180. const root = newElement("form", { className: "form-horizontal" });
  181. options.sort((a, b) => {
  182. const x = a.key.split(".");
  183. const y = b.key.split(".");
  184. return x < y ? -1 : x > y ? 1 : 0;
  185. });
  186. for (const { type, key, defaultValue, description } of options) {
  187. const id = uuid();
  188. const control = newElement("div", { className: "col-sm-3 text-center" });
  189. const group = newElement("div", { className: "form-group" }, [
  190. control,
  191. newElement("label", {
  192. className: "col-sm-3",
  193. htmlFor: id,
  194. textContent: key,
  195. style: {
  196. fontFamily: "monospace",
  197. },
  198. }),
  199. newElement("label", {
  200. className: "col-sm-6",
  201. htmlFor: id,
  202. textContent: description,
  203. }),
  204. ]);
  205. root.appendChild(group);
  206. switch (type) {
  207. case "flag": {
  208. control.appendChild(newElement("input", {
  209. id,
  210. type: "checkbox",
  211. checked: config.get(key, defaultValue),
  212. onchange() {
  213. config.set(key, this.checked);
  214. },
  215. }));
  216. break;
  217. }
  218. case "count": {
  219. control.appendChild(newElement("input", {
  220. id,
  221. type: "number",
  222. min: "0",
  223. value: config.get(key, defaultValue),
  224. onchange() {
  225. config.set(key, +this.value);
  226. },
  227. }));
  228. break;
  229. }
  230. default:
  231. throw new TypeError(`AtCoderEasyTest.setting: undefined option type ${type} for ${key}`);
  232. }
  233. }
  234. root.appendChild(newElement("button", {
  235. className: "btn btn-danger",
  236. textContent: "Reset",
  237. type: "button",
  238. onclick() {
  239. if (win.confirm("Configuration data will be cleared. Are you sure?")) {
  240. config.reset();
  241. }
  242. },
  243. }));
  244. return root;
  245. });
  246. const config = {
  247. getString(key, defaultValue = "") {
  248. if (!(key in data))
  249. config.setString(key, defaultValue);
  250. return data[key];
  251. },
  252. setString(key, value) {
  253. data[key] = value;
  254. save();
  255. },
  256. has(key) {
  257. return key in data;
  258. },
  259. get(key, defaultValue = null) {
  260. if (!(key in data))
  261. config.set(key, defaultValue);
  262. return JSON.parse(data[key]);
  263. },
  264. set(key, value) {
  265. config.setString(key, JSON.stringify(value));
  266. },
  267. save,
  268. load,
  269. toString,
  270. reset,
  271. /** 設定項目を登録 */
  272. registerFlag(key, defaultValue, description) {
  273. options.push({
  274. type: "flag",
  275. key,
  276. defaultValue,
  277. description,
  278. });
  279. },
  280. registerCount(key, defaultValue, description) {
  281. options.push({
  282. type: "count",
  283. key,
  284. defaultValue,
  285. description,
  286. });
  287. },
  288. };
  289.  
  290. config.registerCount("codeSaver.limit", 10, "Max number to save codes");
  291. const codeSaver = {
  292. get() {
  293. // `json` は、ソースコード文字列またはJSON文字列
  294. let json = unsafeWindow.localStorage.AtCoderEasyTest$lastCode;
  295. let data = [];
  296. try {
  297. if (typeof json == "string") {
  298. data.push(...JSON.parse(json));
  299. }
  300. else {
  301. data = [];
  302. }
  303. }
  304. catch (e) {
  305. data.push({
  306. path: unsafeWindow.localStorage.AtCoderEasyTset$lastPage,
  307. code: json,
  308. });
  309. }
  310. return data;
  311. },
  312. set(data) {
  313. unsafeWindow.localStorage.AtCoderEasyTest$lastCode = JSON.stringify(data);
  314. },
  315. save(savePath, code) {
  316. let data = codeSaver.get();
  317. const idx = data.findIndex(({ path }) => path == savePath);
  318. if (idx != -1)
  319. data.splice(idx, idx + 1);
  320. data.push({
  321. path: savePath,
  322. code,
  323. });
  324. while (data.length > config.get("codeSaver.limit", 10))
  325. data.shift();
  326. codeSaver.set(data);
  327. },
  328. restore(savedPath) {
  329. const data = codeSaver.get();
  330. const idx = data.findIndex(({ path }) => path === savedPath);
  331. if (idx == -1 || !(data[idx] instanceof Object))
  332. return Promise.reject(`No saved code found for ${location.pathname}`);
  333. return Promise.resolve(data[idx].code);
  334. }
  335. };
  336. settings.add(`codeSaver (${location.host})`, (win) => {
  337. const root = newElement("table", { className: "table" }, [
  338. newElement("thead", {}, [
  339. newElement("tr", {}, [
  340. newElement("th", { textContent: "path" }),
  341. newElement("th", { textContent: "code" }),
  342. ]),
  343. ]),
  344. newElement("tbody"),
  345. ]);
  346. root.tBodies;
  347. for (const savedCode of codeSaver.get()) {
  348. root.tBodies[0].appendChild(newElement("tr", {}, [
  349. newElement("td", { textContent: savedCode.path }),
  350. newElement("td", {}, [
  351. newElement("textarea", {
  352. rows: 1,
  353. cols: 30,
  354. textContent: savedCode.code,
  355. }),
  356. ]),
  357. ]));
  358. }
  359. return root;
  360. });
  361.  
  362. function similarLangs(targetLang, candidateLangs) {
  363. const [targetName, targetDetail] = targetLang.split(" ", 2);
  364. const selectedLangs = candidateLangs.filter(candidateLang => {
  365. const [name, _] = candidateLang.split(" ", 2);
  366. return name == targetName;
  367. }).map(candidateLang => {
  368. const [_, detail] = candidateLang.split(" ", 2);
  369. return [candidateLang, similarity(detail, targetDetail)];
  370. });
  371. return selectedLangs.sort((a, b) => a[1] - b[1]).map(([lang, _]) => lang);
  372. }
  373. function similarity(s, t) {
  374. const n = s.length, m = t.length;
  375. let dp = new Array(m + 1).fill(0);
  376. for (let i = 0; i < n; i++) {
  377. const dp2 = new Array(m + 1).fill(0);
  378. for (let j = 0; j < m; j++) {
  379. const cost = (s.charCodeAt(i) - t.charCodeAt(j)) ** 2;
  380. dp2[j + 1] = Math.min(dp[j] + cost, dp[j + 1] + cost * 0.25, dp2[j] + cost * 0.25);
  381. }
  382. dp = dp2;
  383. }
  384. return dp[m];
  385. }
  386.  
  387. class CodeRunner {
  388. get label() {
  389. return this._label;
  390. }
  391. constructor(label, site) {
  392. this._label = `${label} [${site}]`;
  393. }
  394. async test(sourceCode, input, expectedOutput, options) {
  395. let result = { status: "IE", input };
  396. try {
  397. result = await this.run(sourceCode, input);
  398. }
  399. catch (e) {
  400. result.error = e.toString();
  401. return result;
  402. }
  403. if (expectedOutput != null)
  404. result.expectedOutput = expectedOutput;
  405. if (result.status != "OK" || typeof expectedOutput != "string")
  406. return result;
  407. let output = result.output || "";
  408. if (options.trim) {
  409. expectedOutput = expectedOutput.trim();
  410. output = output.trim();
  411. }
  412. let equals = (x, y) => x === y;
  413. if (options.allowableError) {
  414. const floatPattern = /^[-+]?[0-9]*\.[0-9]+([eE][-+]?[0-9]+)?$/;
  415. const superEquals = equals;
  416. equals = (x, y) => {
  417. if (floatPattern.test(x) || floatPattern.test(y)) {
  418. const a = parseFloat(x);
  419. const b = parseFloat(y);
  420. return Math.abs(a - b) <= Math.max(options.allowableError, Math.abs(b) * options.allowableError);
  421. }
  422. return superEquals(x, y);
  423. };
  424. }
  425. if (options.split) {
  426. const superEquals = equals;
  427. equals = (x, y) => {
  428. const xs = x.split(/\s+/);
  429. const ys = y.split(/\s+/);
  430. if (xs.length != ys.length)
  431. return false;
  432. const len = xs.length;
  433. for (let i = 0; i < len; i++) {
  434. if (!superEquals(xs[i], ys[i]))
  435. return false;
  436. }
  437. return true;
  438. };
  439. }
  440. result.status = equals(output, expectedOutput) ? "AC" : "WA";
  441. return result;
  442. }
  443. }
  444.  
  445. class CustomRunner extends CodeRunner {
  446. run;
  447. constructor(label, run) {
  448. super(label, "Browser");
  449. this.run = run;
  450. }
  451. }
  452.  
  453. let waitAtCoderCustomTest = Promise.resolve();
  454. const AtCoderCustomTestBase = location.href.replace(/\/tasks\/.+$/, "/custom_test");
  455. const AtCoderCustomTestResultAPI = AtCoderCustomTestBase + "/json?reload=true";
  456. const AtCoderCustomTestSubmitAPI = AtCoderCustomTestBase + "/submit/json";
  457. class AtCoderRunner extends CodeRunner {
  458. languageId;
  459. constructor(languageId, label) {
  460. super(label, "AtCoder");
  461. this.languageId = languageId;
  462. }
  463. async run(sourceCode, input) {
  464. const promise = this.submit(sourceCode, input);
  465. waitAtCoderCustomTest = promise;
  466. return await promise;
  467. }
  468. async submit(sourceCode, input) {
  469. try {
  470. await waitAtCoderCustomTest;
  471. }
  472. catch (error) {
  473. console.error(error);
  474. }
  475. const error = await fetch(AtCoderCustomTestSubmitAPI, {
  476. method: "POST",
  477. credentials: "include",
  478. headers: {
  479. "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
  480. },
  481. body: buildParams({
  482. "data.LanguageId": String(this.languageId),
  483. sourceCode,
  484. input,
  485. csrf_token: unsafeWindow.csrfToken,
  486. }),
  487. }).then(r => r.text());
  488. if (error) {
  489. throw new Error(error);
  490. }
  491. await sleep(100);
  492. for (;;) {
  493. const data = await fetch(AtCoderCustomTestResultAPI, {
  494. method: "GET",
  495. credentials: "include",
  496. }).then(r => r.json());
  497. if (!("Result" in data))
  498. continue;
  499. const result = data.Result;
  500. if ("Interval" in data) {
  501. await sleep(data.Interval);
  502. continue;
  503. }
  504. return {
  505. status: (result.ExitCode == 0) ? "OK" : (result.TimeConsumption == -1) ? "CE" : "RE",
  506. exitCode: result.ExitCode,
  507. execTime: result.TimeConsumption,
  508. memory: result.MemoryConsumption,
  509. input,
  510. output: data.Stdout,
  511. error: data.Stderr,
  512. };
  513. }
  514. }
  515. }
  516.  
  517. class PaizaIORunner extends CodeRunner {
  518. name;
  519. constructor(name, label) {
  520. super(label, "PaizaIO");
  521. this.name = name;
  522. }
  523. async run(sourceCode, input) {
  524. let id, status, error;
  525. try {
  526. const res = await fetch("https://api.paiza.io/runners/create?" + buildParams({
  527. source_code: sourceCode,
  528. language: this.name,
  529. input,
  530. longpoll: "true",
  531. longpoll_timeout: "10",
  532. api_key: "guest",
  533. }), {
  534. method: "POST",
  535. mode: "cors",
  536. }).then(r => r.json());
  537. id = res.id;
  538. status = res.status;
  539. error = res.error;
  540. }
  541. catch (error) {
  542. return {
  543. status: "IE",
  544. input,
  545. error: String(error),
  546. };
  547. }
  548. while (status == "running") {
  549. const res = await fetch("https://api.paiza.io/runners/get_status?" + buildParams({
  550. id,
  551. api_key: "guest",
  552. }), {
  553. mode: "cors",
  554. }).then(res => res.json());
  555. status = res.status;
  556. error = res.error;
  557. }
  558. const res = await fetch("https://api.paiza.io/runners/get_details?" + buildParams({
  559. id,
  560. api_key: "guest",
  561. }), {
  562. mode: "cors",
  563. }).then(r => r.json());
  564. const result = {
  565. status: "OK",
  566. exitCode: String(res.exit_code),
  567. execTime: +res.time * 1e3,
  568. memory: +res.memory * 1e-3,
  569. input,
  570. };
  571. if (res.build_result == "failure") {
  572. result.status = "CE";
  573. result.exitCode = res.build_exit_code;
  574. result.output = res.build_stdout;
  575. result.error = res.build_stderr;
  576. }
  577. else {
  578. result.status = (res.result == "timeout") ? "TLE" : (res.result == "failure") ? "RE" : "OK";
  579. result.exitCode = res.exit_code;
  580. result.output = res.stdout;
  581. result.error = res.stderr;
  582. }
  583. return result;
  584. }
  585. }
  586.  
  587. class WandboxRunner extends CodeRunner {
  588. name;
  589. options;
  590. constructor(name, label, options = {}) {
  591. super(label, "Wandbox");
  592. this.name = name;
  593. this.options = options;
  594. }
  595. getOptions(sourceCode, input) {
  596. if (typeof this.options == "function")
  597. return this.options(sourceCode, input);
  598. return this.options;
  599. }
  600. run(sourceCode, input) {
  601. const options = this.getOptions(sourceCode, input);
  602. return this.request(Object.assign({
  603. compiler: this.name,
  604. code: sourceCode,
  605. stdin: input,
  606. }, options));
  607. }
  608. async request(body) {
  609. const startTime = Date.now();
  610. let res;
  611. try {
  612. res = await fetch("https://wandbox.org/api/compile.json", {
  613. method: "POST",
  614. mode: "cors",
  615. headers: {
  616. "Content-Type": "application/json",
  617. },
  618. body: JSON.stringify(body),
  619. }).then(r => r.json());
  620. }
  621. catch (error) {
  622. console.error(error);
  623. return {
  624. status: "IE",
  625. input: body.stdin,
  626. error: String(error),
  627. };
  628. }
  629. const endTime = Date.now();
  630. const result = {
  631. status: "OK",
  632. exitCode: String(res.status),
  633. execTime: endTime - startTime,
  634. input: body.stdin,
  635. output: String(res.program_output || ""),
  636. error: String(res.program_error || ""),
  637. };
  638. // 正常終了以外の場合
  639. if (res.status != 0) {
  640. if (res.signal) {
  641. result.exitCode += ` (${res.signal})`;
  642. }
  643. result.output = String(res.compiler_output || "") + String(result.output || "");
  644. result.error = String(res.compiler_error || "") + String(result.error || "");
  645. if (res.compiler_output || res.compiler_error) {
  646. result.status = "CE";
  647. }
  648. else {
  649. result.status = "RE";
  650. }
  651. }
  652. return result;
  653. }
  654. }
  655.  
  656. class WandboxCppRunner extends WandboxRunner {
  657. async run(sourceCode, input) {
  658. // ACL を結合する
  659. const ACLBase = "https://cdn.jsdelivr.net/gh/atcoder/ac-library/";
  660. const files = new Map();
  661. const includeHeader = async (source) => {
  662. const pattern = /^#\s*include\s*[<"]atcoder\/([^>"]+)[>"]/gm;
  663. const loaded = [];
  664. let match;
  665. while (match = pattern.exec(source)) {
  666. const file = "atcoder/" + match[1];
  667. if (files.has(file))
  668. continue;
  669. files.set(file, null);
  670. loaded.push([file, fetch(ACLBase + file, { mode: "cors", cache: "force-cache", }).then(r => r.text())]);
  671. }
  672. const included = await Promise.all(loaded.map(async ([file, r]) => {
  673. const source = await r;
  674. files.set(file, source);
  675. return source;
  676. }));
  677. for (const source of included) {
  678. await includeHeader(source);
  679. }
  680. };
  681. await includeHeader(sourceCode);
  682. const codes = [];
  683. for (const [file, code] of files) {
  684. codes.push({ file, code, });
  685. }
  686. const options = this.getOptions(sourceCode, input);
  687. return await this.request(Object.assign({
  688. compiler: this.name,
  689. code: sourceCode,
  690. stdin: input,
  691. codes,
  692. }, options));
  693. }
  694. }
  695.  
  696. let brythonRunnerLoaded = false;
  697. const brythonRunner = new CustomRunner("Brython", async (sourceCode, input) => {
  698. if (!brythonRunnerLoaded) {
  699. // BrythonRunner を読み込む
  700. await new Promise((resolve) => {
  701. const script = document.createElement("script");
  702. script.src = "https://cdn.jsdelivr.net/gh/pythonpad/brython-runner/lib/brython-runner.bundle.js";
  703. script.onload = () => {
  704. brythonRunnerLoaded = true;
  705. resolve(null);
  706. };
  707. document.head.appendChild(script);
  708. });
  709. }
  710. let stdout = "";
  711. let stderr = "";
  712. let stdinOffset = 0;
  713. const BrythonRunner = unsafeWindow.BrythonRunner;
  714. const runner = new BrythonRunner({
  715. stdout: { write(content) { stdout += content; }, flush() { } },
  716. stderr: { write(content) { stderr += content; }, flush() { } },
  717. stdin: { async readline() {
  718. let index = input.indexOf("\n", stdinOffset) + 1;
  719. if (index == 0)
  720. index = input.length;
  721. const text = input.slice(stdinOffset, index);
  722. stdinOffset = index;
  723. return text;
  724. } },
  725. });
  726. const timeStart = Date.now();
  727. await runner.runCode(sourceCode);
  728. const timeEnd = Date.now();
  729. return {
  730. status: "OK",
  731. exitCode: "0",
  732. execTime: (timeEnd - timeStart),
  733. input,
  734. output: stdout,
  735. error: stderr,
  736. };
  737. });
  738.  
  739. async function loadPyodide() {
  740. const script = await fetch("https://cdn.jsdelivr.net/pyodide/v0.18.1/full/pyodide.js").then(res => res.text());
  741. unsafeWindow["Function"](script)();
  742. const pyodide = await unsafeWindow["loadPyodide"]({
  743. indexURL: "https://cdn.jsdelivr.net/pyodide/v0.18.1/full/",
  744. });
  745. await pyodide.runPythonAsync(`
  746. import contextlib, io, platform
  747. class __redirect_stdin(contextlib._RedirectStream):
  748. _stream = "stdin"
  749. `);
  750. return pyodide;
  751. }
  752. let _pyodide = Promise.reject("Pyodide is not yet loaded");
  753. let _serial = Promise.resolve();
  754. const pyodideRunner = new CustomRunner("Pyodide", (sourceCode, input) => new Promise((resolve, reject) => {
  755. _serial = _serial.finally(async () => {
  756. const pyodide = await (_pyodide = _pyodide.catch(loadPyodide));
  757. const code = `
  758. def __run():
  759. global __stdout, __stderr, __stdin, __code
  760. with __redirect_stdin(io.StringIO(__stdin)):
  761. with contextlib.redirect_stdout(io.StringIO()) as __stdout:
  762. with contextlib.redirect_stderr(io.StringIO()) as __stderr:
  763. try:
  764. pass
  765. ` + sourceCode.split("\n").map(line => " " + line).join("\n") + `
  766. except SystemExit as e:
  767. __code = e.code
  768. `;
  769. let status = "OK";
  770. let exitCode = "0";
  771. let stdout = "";
  772. let stderr = "";
  773. let startTime = -Infinity;
  774. let endTime = Infinity;
  775. pyodide.globals.__stdin = input;
  776. try {
  777. pyodide.globals.__code = null;
  778. await pyodide.loadPackagesFromImports(code);
  779. await pyodide.runPythonAsync(code);
  780. startTime = Date.now();
  781. pyodide.runPython("__run()");
  782. endTime = Date.now();
  783. stdout += pyodide.globals.__stdout.getvalue();
  784. stderr += pyodide.globals.__stderr.getvalue();
  785. if (typeof pyodide.globals.__code == "number") {
  786. exitCode = String(pyodide.globals.__code);
  787. if (pyodide.globals.__code != 0)
  788. status = "RE";
  789. }
  790. }
  791. catch (error) {
  792. status = "RE";
  793. exitCode = "-1";
  794. stderr += error.toString();
  795. }
  796. resolve({
  797. status,
  798. exitCode,
  799. execTime: (endTime - startTime),
  800. input,
  801. output: stdout,
  802. error: stderr,
  803. });
  804. });
  805. }));
  806.  
  807. function pairs(list) {
  808. const pairs = [];
  809. const len = list.length >> 1;
  810. for (let i = 0; i < len; i++)
  811. pairs.push([list[i * 2], list[i * 2 + 1]]);
  812. return pairs;
  813. }
  814. async function init$5() {
  815. if (location.host != "atcoder.jp")
  816. throw "Not AtCoder";
  817. const doc = unsafeWindow.document;
  818. const langMap = {
  819. 4001: "C GCC 9.2.1",
  820. 4002: "C Clang 10.0.0",
  821. 4003: "C++ GCC 9.2.1",
  822. 4004: "C++ Clang 10.0.0",
  823. 4005: "Java OpenJDK 11.0.6",
  824. 4006: "Python3 CPython 3.8.2",
  825. 4007: "Bash 5.0.11",
  826. 4008: "bc 1.07.1",
  827. 4009: "Awk GNU Awk 4.1.4",
  828. 4010: "C# .NET Core 3.1.201",
  829. 4011: "C# Mono-mcs 6.8.0.105",
  830. 4012: "C# Mono-csc 3.5.0",
  831. 4013: "Clojure 1.10.1.536",
  832. 4014: "Crystal 0.33.0",
  833. 4015: "D DMD 2.091.0",
  834. 4016: "D GDC 9.2.1",
  835. 4017: "D LDC 1.20.1",
  836. 4018: "Dart 2.7.2",
  837. 4019: "dc 1.4.1",
  838. 4020: "Erlang 22.3",
  839. 4021: "Elixir 1.10.2",
  840. 4022: "F# .NET Core 3.1.201",
  841. 4023: "F# Mono 10.2.3",
  842. 4024: "Forth gforth 0.7.3",
  843. 4025: "Fortran GNU Fortran 9.2.1",
  844. 4026: "Go 1.14.1",
  845. 4027: "Haskell GHC 8.8.3",
  846. 4028: "Haxe 4.0.3",
  847. 4029: "Haxe 4.0.3",
  848. 4030: "JavaScript Node.js 12.16.1",
  849. 4031: "Julia 1.4.0",
  850. 4032: "Kotlin 1.3.71",
  851. 4033: "Lua Lua 5.3.5",
  852. 4034: "Lua LuaJIT 2.1.0",
  853. 4035: "Dash 0.5.8",
  854. 4036: "Nim 1.0.6",
  855. 4037: "Objective-C Clang 10.0.0",
  856. 4038: "Lisp SBCL 2.0.3",
  857. 4039: "OCaml 4.10.0",
  858. 4040: "Octave 5.2.0",
  859. 4041: "Pascal FPC 3.0.4",
  860. 4042: "Perl 5.26.1",
  861. 4043: "Raku Rakudo 2020.02.1",
  862. 4044: "PHP 7.4.4",
  863. 4045: "Prolog SWI-Prolog 8.0.3",
  864. 4046: "Python PyPy2 7.3.0",
  865. 4047: "Python3 PyPy3 7.3.0",
  866. 4048: "Racket 7.6",
  867. 4049: "Ruby 2.7.1",
  868. 4050: "Rust 1.42.0",
  869. 4051: "Scala 2.13.1",
  870. 4052: "Java OpenJDK 1.8.0",
  871. 4053: "Scheme Gauche 0.9.9",
  872. 4054: "ML MLton 20130715",
  873. 4055: "Swift 5.2.1",
  874. 4056: "Text cat 8.28",
  875. 4057: "TypeScript 3.8",
  876. 4058: "Basic .NET Core 3.1.101",
  877. 4059: "Zsh 5.4.2",
  878. 4060: "COBOL Fixed OpenCOBOL 1.1.0",
  879. 4061: "COBOL Free OpenCOBOL 1.1.0",
  880. 4062: "Brainfuck bf 20041219",
  881. 4063: "Ada Ada2012 GNAT 9.2.1",
  882. 4064: "Unlambda 2.0.0",
  883. 4065: "Cython 0.29.16",
  884. 4066: "Sed 4.4",
  885. 4067: "Vim 8.2.0460",
  886. };
  887. const languageId = new ObservableValue(unsafeWindow.$("#select-lang select.current").val());
  888. unsafeWindow.$("#select-lang select").change(() => {
  889. languageId.value = unsafeWindow.$("#select-lang select.current").val();
  890. });
  891. const language = languageId.map(lang => langMap[lang]);
  892. const isTestCasesHere = /^\/contests\/[^\/]+\/tasks\//.test(location.pathname);
  893. const taskSelector = doc.querySelector("#select-task");
  894. function getTaskURI() {
  895. if (taskSelector)
  896. return `${location.origin}/contests/${unsafeWindow.contestScreenName}/tasks/${taskSelector.value}`;
  897. return `${location.origin}${location.pathname}`;
  898. }
  899. const testcasesCache = {};
  900. if (taskSelector) {
  901. const doFetchTestCases = async () => {
  902. console.log(`Fetching test cases...: ${getTaskURI()}`);
  903. const taskURI = getTaskURI();
  904. const load = !(taskURI in testcasesCache) || testcasesCache[taskURI].state == "error";
  905. if (!load)
  906. return;
  907. try {
  908. testcasesCache[taskURI] = { state: "loading" };
  909. const testcases = await fetchTestCases(taskURI);
  910. testcasesCache[taskURI] = { testcases, state: "loaded" };
  911. }
  912. catch (e) {
  913. testcasesCache[taskURI] = { state: "error" };
  914. }
  915. };
  916. unsafeWindow.$("#select-task").change(doFetchTestCases);
  917. doFetchTestCases();
  918. }
  919. async function fetchTestCases(taskUrl) {
  920. const html = await fetch(taskUrl).then(res => res.text());
  921. const taskDoc = new DOMParser().parseFromString(html, "text/html");
  922. return getTestCases(taskDoc);
  923. }
  924. function getTestCases(doc) {
  925. const selectors = [
  926. ["#task-statement p+pre.literal-block", ".section"],
  927. ["#task-statement pre.source-code-for-copy", ".part"],
  928. ["#task-statement .lang>*:nth-child(1) .div-btn-copy+pre", ".part"],
  929. ["#task-statement .div-btn-copy+pre", ".part"],
  930. ["#task-statement>.part pre.linenums", ".part"],
  931. ["#task-statement>.part section>pre", ".part"],
  932. ["#task-statement>.part:not(.io-style)>h3+section>pre", ".part"],
  933. ["#task-statement pre", ".part"],
  934. ];
  935. for (const [selector, closestSelector] of selectors) {
  936. let e = [...doc.querySelectorAll(selector)];
  937. e = e.filter(e => {
  938. if (e.closest(".io-style"))
  939. return false; // practice2
  940. if (e.querySelector("var"))
  941. return false;
  942. return true;
  943. });
  944. if (e.length == 0)
  945. continue;
  946. return pairs(e).map(([input, output], index) => {
  947. const container = input.closest(closestSelector) || input.parentElement;
  948. return {
  949. selector,
  950. title: `Sample ${index + 1}`,
  951. input: input.textContent,
  952. output: output.textContent,
  953. anchor: container.querySelector(".btn-copy") || container.querySelector("h1,h2,h3,h4,h5,h6"),
  954. };
  955. });
  956. }
  957. { // maximum_cup_2018_d
  958. let e = [...doc.querySelectorAll("#task-statement .div-btn-copy+pre")];
  959. e = e.filter(f => !f.childElementCount);
  960. if (e.length) {
  961. return pairs(e).map(([input, output], index) => ({
  962. selector: "#task-statement .div-btn-copy+pre",
  963. title: `Sample ${index + 1}`,
  964. input: input.textContent,
  965. output: output.textContent,
  966. anchor: (input.closest(".part") || input.parentElement).querySelector(".btn-copy"),
  967. }));
  968. }
  969. }
  970. return [];
  971. }
  972. const atcoder = {
  973. name: "AtCoder",
  974. language,
  975. get sourceCode() {
  976. return unsafeWindow.getSourceCode();
  977. },
  978. set sourceCode(sourceCode) {
  979. doc.querySelector(".plain-textarea").value = sourceCode;
  980. unsafeWindow.$(".editor").data("editor").doc.setValue(sourceCode);
  981. },
  982. submit() {
  983. doc.querySelector("#submit").click();
  984. },
  985. get testButtonContainer() {
  986. return doc.querySelector("#submit").parentElement;
  987. },
  988. get sideButtonContainer() {
  989. return doc.querySelector(".editor-buttons");
  990. },
  991. get bottomMenuContainer() {
  992. return doc.getElementById("main-div");
  993. },
  994. get resultListContainer() {
  995. return doc.querySelector(".form-code-submit");
  996. },
  997. get testCases() {
  998. const taskURI = getTaskURI();
  999. if (taskURI in testcasesCache && testcasesCache[taskURI].state == "loaded")
  1000. return testcasesCache[taskURI].testcases;
  1001. if (isTestCasesHere) {
  1002. const testcases = getTestCases(doc);
  1003. testcasesCache[taskURI] = { testcases, state: "loaded" };
  1004. return testcases;
  1005. }
  1006. else {
  1007. console.error("AtCoder Easy Test v2: Test cases are still not loaded");
  1008. return [];
  1009. }
  1010. },
  1011. get jQuery() {
  1012. return unsafeWindow["jQuery"];
  1013. },
  1014. get taskURI() {
  1015. return getTaskURI();
  1016. },
  1017. };
  1018. return atcoder;
  1019. }
  1020.  
  1021. async function init$4() {
  1022. if (location.host != "yukicoder.me")
  1023. throw "Not yukicoder";
  1024. const $ = unsafeWindow.$;
  1025. const doc = unsafeWindow.document;
  1026. const editor = unsafeWindow.ace.edit("rich_source");
  1027. const eSourceObject = $("#source");
  1028. const eLang = $("#lang");
  1029. const eSamples = $(".sample");
  1030. const langMap = {
  1031. "cpp14": "C++ C++14 GCC 11.1.0 + Boost 1.77.0",
  1032. "cpp17": "C++ C++17 GCC 11.1.0 + Boost 1.77.0",
  1033. "cpp-clang": "C++ C++17 Clang 10.0.0 + Boost 1.76.0",
  1034. "cpp23": "C++ C++11 GCC 8.4.1",
  1035. "c11": "C++ C++11 GCC 11.1.0",
  1036. "c": "C C90 GCC 8.4.1",
  1037. "java8": "Java Java16 OpenJDK 16.0.1",
  1038. "csharp": "C# CSC 3.9.0",
  1039. "csharp_mono": "C# Mono 6.12.0.147",
  1040. "csharp_dotnet": "C# .NET 5.0",
  1041. "perl": "Perl 5.26.3",
  1042. "raku": "Raku Rakudo v2021-07-2-g74d7ff771",
  1043. "php": "PHP 7.2.24",
  1044. "php7": "PHP 8.0.8",
  1045. "python3": "Python3 3.9.6 + numpy 1.14.5 + scipy 1.1.0",
  1046. "pypy2": "Python PyPy2 7.3.5",
  1047. "pypy3": "Python3 PyPy3 7.3.5",
  1048. "ruby": "Ruby 3.0.2p107",
  1049. "d": "D DMD 2.097.1",
  1050. "go": "Go 1.16.6",
  1051. "haskell": "Haskell 8.10.5",
  1052. "scala": "Scala 2.13.6",
  1053. "nim": "Nim 1.4.8",
  1054. "rust": "Rust 1.53.0",
  1055. "kotlin": "Kotlin 1.5.21",
  1056. "scheme": "Scheme Gauche 0.9.10",
  1057. "crystal": "Crystal 1.1.1",
  1058. "swift": "Swift 5.4.2",
  1059. "ocaml": "OCaml 4.12.0",
  1060. "clojure": "Clojure 1.10.2.790",
  1061. "fsharp": "F# 5.0",
  1062. "elixir": "Elixir 1.7.4",
  1063. "lua": "Lua LuaJIT 2.0.5",
  1064. "fortran": "Fortran gFortran 8.4.1",
  1065. "node": "JavaScript Node.js 15.5.0",
  1066. "typescript": "TypeScript 4.3.5",
  1067. "lisp": "Lisp Common Lisp sbcl 2.1.6",
  1068. "sml": "ML Standard ML MLton 20180207-6",
  1069. "kuin": "Kuin KuinC++ v.2021.7.17",
  1070. "vim": "Vim v8.2",
  1071. "sh": "Bash 4.4.19",
  1072. "nasm": "Assembler nasm 2.13.03",
  1073. "clay": "cLay 20210917-1",
  1074. "bf": "Brainfuck BFI 1.1",
  1075. "Whitespace": "Whitespace 0.3",
  1076. "text": "Text cat 8.3",
  1077. };
  1078. // place anchor elements
  1079. for (const btnCopyInput of doc.querySelectorAll(".copy-sample-input")) {
  1080. btnCopyInput.parentElement.insertBefore(newElement("span", { className: "atcoder-easy-test-anchor" }), btnCopyInput);
  1081. }
  1082. const language = new ObservableValue(langMap[eLang.val()]);
  1083. eLang.on("change", () => {
  1084. language.value = langMap[eLang.val()];
  1085. });
  1086. return {
  1087. name: "yukicoder",
  1088. language,
  1089. get sourceCode() {
  1090. if (eSourceObject.is(":visible"))
  1091. return eSourceObject.val();
  1092. return editor.getSession().getValue();
  1093. },
  1094. set sourceCode(sourceCode) {
  1095. eSourceObject.val(sourceCode);
  1096. editor.getSession().setValue(sourceCode);
  1097. },
  1098. submit() {
  1099. doc.querySelector(`#submit_form input[type="submit"]`).click();
  1100. },
  1101. get testButtonContainer() {
  1102. return doc.querySelector("#submit_form");
  1103. },
  1104. get sideButtonContainer() {
  1105. return doc.querySelector("#toggle_source_editor").parentElement;
  1106. },
  1107. get bottomMenuContainer() {
  1108. return doc.body;
  1109. },
  1110. get resultListContainer() {
  1111. return doc.querySelector("#content");
  1112. },
  1113. get testCases() {
  1114. const testCases = [];
  1115. let sampleId = 1;
  1116. for (let i = 0; i < eSamples.length; i++) {
  1117. const eSample = eSamples.eq(i);
  1118. const [eInput, eOutput] = eSample.find("pre");
  1119. testCases.push({
  1120. title: `Sample ${sampleId++}`,
  1121. input: eInput.textContent,
  1122. output: eOutput.textContent,
  1123. anchor: eSample.find(".atcoder-easy-test-anchor")[0],
  1124. });
  1125. }
  1126. return testCases;
  1127. },
  1128. get jQuery() {
  1129. return $;
  1130. },
  1131. get taskURI() {
  1132. return location.href;
  1133. },
  1134. };
  1135. }
  1136.  
  1137. class Editor {
  1138. _element;
  1139. constructor(lang) {
  1140. this._element = document.createElement("textarea");
  1141. this._element.style.fontFamily = "monospace";
  1142. this._element.style.width = "100%";
  1143. this._element.style.minHeight = "5em";
  1144. }
  1145. get element() {
  1146. return this._element;
  1147. }
  1148. get sourceCode() {
  1149. return this._element.value;
  1150. }
  1151. set sourceCode(sourceCode) {
  1152. this._element.value = sourceCode;
  1153. }
  1154. setLanguage(lang) {
  1155. }
  1156. }
  1157.  
  1158. var langMap = {
  1159. 3: "Delphi 7",
  1160. 4: "Pascal Free Pascal 3.0.2",
  1161. 6: "PHP 7.2.13",
  1162. 7: "Python 2.7.18",
  1163. 9: "C# Mono 6.8",
  1164. 12: "Haskell GHC 8.10.1",
  1165. 13: "Perl 5.20.1",
  1166. 19: "OCaml 4.02.1",
  1167. 20: "Scala 2.12.8",
  1168. 28: "D DMD32 v2.091.0",
  1169. 31: "Python3 3.8.10",
  1170. 32: "Go 1.15.6",
  1171. 34: "JavaScript V8 4.8.0",
  1172. 36: "Java 1.8.0_241",
  1173. 40: "Python PyPy2 2.7 (7.3.0)",
  1174. 41: "Python3 PyPy3 3.7 (7.3.0)",
  1175. 43: "C C11 GCC 5.1.0",
  1176. 48: "Kotlin 1.5.31",
  1177. 49: "Rust 1.49.0",
  1178. 50: "C++ C++14 G++ 6.4.0",
  1179. 51: "Pascal PascalABC.NET 3.4.1",
  1180. 52: "C++ C++17 Clang++",
  1181. 54: "C++ C++17 G++ 7.3.0",
  1182. 55: "JavaScript Node.js 12.6.3",
  1183. 59: "C++ Microsoft Visual C++ 2017",
  1184. 60: "Java 11.0.6",
  1185. 61: "C++ C++17 9.2.0 (64 bit, msys 2)",
  1186. 65: "C# 8, .NET Core 3.1",
  1187. 67: "Ruby 3.0.0",
  1188. 70: "Python3 PyPy 3.7 (7.3.5, 64bit)",
  1189. 72: "Kotlin 1.5.31",
  1190. 73: "C++ GNU G++ 11.2.0 (64 bit, winlibs)",
  1191. };
  1192.  
  1193. config.registerFlag("site.codeforces.showEditor", true, "Show Editor in Codeforces Problem Page");
  1194. async function init$3() {
  1195. if (location.host != "codeforces.com")
  1196. throw "not Codeforces";
  1197. //TODO: m1.codeforces.com, m2.codeforces.com, m3.codeforces.com に対応する
  1198. const doc = unsafeWindow.document;
  1199. const eLang = doc.querySelector("select[name='programTypeId']");
  1200. doc.head.appendChild(newElement("link", {
  1201. rel: "stylesheet",
  1202. href: "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css",
  1203. }));
  1204. doc.head.appendChild(newElement("style", {
  1205. textContent: `
  1206. .atcoder-easy-test-btn-run-case {
  1207. float: right;
  1208. line-height: 1.1rem;
  1209. }
  1210. `,
  1211. }));
  1212. const eButtons = newElement("span");
  1213. doc.querySelector(".submitForm").appendChild(eButtons);
  1214. await loadScript("https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js");
  1215. const jQuery = unsafeWindow["jQuery"].noConflict();
  1216. unsafeWindow["jQuery"] = unsafeWindow["$"];
  1217. unsafeWindow["jQuery11"] = jQuery;
  1218. await loadScript("https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js", null, { jQuery, $: jQuery });
  1219. const language = new ObservableValue(langMap[eLang.value]);
  1220. eLang.addEventListener("change", () => {
  1221. language.value = langMap[eLang.value];
  1222. });
  1223. let _sourceCode = "";
  1224. const eFile = doc.querySelector(".submitForm").elements["sourceFile"];
  1225. eFile.addEventListener("change", async () => {
  1226. if (eFile.files[0]) {
  1227. _sourceCode = await eFile.files[0].text();
  1228. if (editor)
  1229. editor.sourceCode = _sourceCode;
  1230. }
  1231. });
  1232. let editor = null;
  1233. let waitCfFastSubmitCount = 0;
  1234. const waitCfFastSubmit = setInterval(() => {
  1235. if (document.getElementById("editor")) {
  1236. // cf-fast-submit
  1237. if (editor && editor.element)
  1238. editor.element.style.display = "none";
  1239. // 言語セレクトを同期させる
  1240. const eLang2 = doc.querySelector(".submit-form select[name='programTypeId']");
  1241. if (eLang2) {
  1242. eLang.addEventListener("change", () => {
  1243. eLang2.value = eLang.value;
  1244. });
  1245. eLang2.addEventListener("change", () => {
  1246. eLang.value = eLang2.value;
  1247. language.value = langMap[eLang.value];
  1248. });
  1249. }
  1250. // TODO: 選択されたファイルをどうかする
  1251. // エディタを使う
  1252. const aceEditor = unsafeWindow["ace"].edit("editor");
  1253. editor = {
  1254. get sourceCode() {
  1255. return aceEditor.getValue();
  1256. },
  1257. set sourceCode(sourceCode) {
  1258. aceEditor.setValue(sourceCode);
  1259. },
  1260. setLanguage(lang) { },
  1261. };
  1262. // ボタンを追加する
  1263. const buttonContainer = doc.querySelector(".submit-form .submit").parentElement;
  1264. buttonContainer.appendChild(newElement("button", {
  1265. type: "button",
  1266. className: "btn btn-info",
  1267. textContent: "Test & Submit",
  1268. onclick: () => events.trig("testAndSubmit"),
  1269. }));
  1270. buttonContainer.appendChild(newElement("button", {
  1271. type: "button",
  1272. className: "btn btn-default",
  1273. textContent: "Test All Samples",
  1274. onclick: () => events.trig("testAllSamples"),
  1275. }));
  1276. clearInterval(waitCfFastSubmit);
  1277. }
  1278. else {
  1279. waitCfFastSubmitCount++;
  1280. if (waitCfFastSubmitCount >= 100)
  1281. clearInterval(waitCfFastSubmit);
  1282. }
  1283. }, 100);
  1284. if (config.get("site.codeforces.showEditor", true)) {
  1285. editor = new Editor(langMap[eLang.value].split(" ")[0]);
  1286. doc.getElementById("pageContent").appendChild(editor.element);
  1287. language.addListener(lang => {
  1288. editor.setLanguage(lang);
  1289. });
  1290. }
  1291. return {
  1292. name: "Codeforces",
  1293. language,
  1294. get sourceCode() {
  1295. if (editor)
  1296. return editor.sourceCode;
  1297. return _sourceCode;
  1298. },
  1299. set sourceCode(sourceCode) {
  1300. const container = new DataTransfer();
  1301. container.items.add(new File([sourceCode], "prog.txt", { type: "text/plain" }));
  1302. const eFile = doc.querySelector(".submitForm").elements["sourceFile"];
  1303. eFile.files = container.files;
  1304. _sourceCode = sourceCode;
  1305. if (editor)
  1306. editor.sourceCode = sourceCode;
  1307. },
  1308. submit() {
  1309. if (editor)
  1310. _sourceCode = editor.sourceCode;
  1311. this.sourceCode = _sourceCode;
  1312. doc.querySelector(`.submitForm .submit`).click();
  1313. },
  1314. get testButtonContainer() {
  1315. return eButtons;
  1316. },
  1317. get sideButtonContainer() {
  1318. return eButtons;
  1319. },
  1320. get bottomMenuContainer() {
  1321. return doc.body;
  1322. },
  1323. get resultListContainer() {
  1324. return doc.querySelector("#pageContent");
  1325. },
  1326. get testCases() {
  1327. const testcases = [];
  1328. let num = 1;
  1329. for (const eSampleTest of doc.querySelectorAll(".sample-test")) {
  1330. const inputs = eSampleTest.querySelectorAll(".input pre");
  1331. const outputs = eSampleTest.querySelectorAll(".output pre");
  1332. const anchors = eSampleTest.querySelectorAll(".input .title .input-output-copier");
  1333. const count = Math.min(inputs.length, outputs.length, anchors.length);
  1334. for (let i = 0; i < count; i++) {
  1335. let inputText = "";
  1336. for (const node of inputs[i].childNodes) {
  1337. inputText += node.textContent;
  1338. if (node.nodeType == node.ELEMENT_NODE && node.tagName == "DIV") {
  1339. inputText += "\n";
  1340. }
  1341. }
  1342. testcases.push({
  1343. title: `Sample ${num++}`,
  1344. input: inputText,
  1345. output: outputs[i].textContent,
  1346. anchor: anchors[i],
  1347. });
  1348. }
  1349. }
  1350. return testcases;
  1351. },
  1352. get jQuery() {
  1353. return jQuery;
  1354. },
  1355. get taskURI() {
  1356. return location.href;
  1357. },
  1358. };
  1359. }
  1360.  
  1361. config.registerFlag("site.codeforcesMobile.showEditor", true, "Show Editor in Mobile Codeforces (m[1-3].codeforces.com) Problem Page");
  1362. async function init$2() {
  1363. if (!/^m[1-3]\.codeforces\.com$/.test(location.host))
  1364. throw "not Codeforces Mobile";
  1365. const url = /\/contest\/(\d+)\/problem\/([^/]+)/.exec(location.pathname);
  1366. const contestId = url[1];
  1367. const problemId = url[2];
  1368. const doc = unsafeWindow.document;
  1369. const main = doc.querySelector("main");
  1370. doc.head.appendChild(newElement("link", {
  1371. rel: "stylesheet",
  1372. href: "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css",
  1373. }));
  1374. await loadScript("https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js");
  1375. const language = new ObservableValue("");
  1376. let submit = () => { };
  1377. let getSourceCode = () => "";
  1378. let setSourceCode = (_) => { };
  1379. // make Editor
  1380. if (config.get("site.codeforcesMobile.showEditor", true)) {
  1381. const frame = newElement("iframe", {
  1382. src: `/contest/${contestId}/submit`,
  1383. style: {
  1384. display: "none",
  1385. },
  1386. });
  1387. doc.body.appendChild(frame);
  1388. await new Promise(done => frame.onload = done);
  1389. const fdoc = frame.contentDocument;
  1390. const form = fdoc.querySelector("._SubmitPage_submitForm");
  1391. form.elements["problemIndex"].value = problemId;
  1392. form.elements["problemIndex"].readonly = true;
  1393. form.elements["programTypeId"].addEventListener("change", function () {
  1394. language.value = langMap[this.value];
  1395. });
  1396. for (const row of form.children) {
  1397. if (row.tagName != "DIV")
  1398. continue;
  1399. row.classList.add("form-group");
  1400. const control = row.querySelector("*[name]");
  1401. if (control)
  1402. control.classList.add("form-control");
  1403. }
  1404. form.parentElement.removeChild(form);
  1405. main.appendChild(form);
  1406. submit = () => form.submit();
  1407. getSourceCode = () => form.elements["source"].value;
  1408. setSourceCode = sourceCode => {
  1409. form.elements["source"].value = sourceCode;
  1410. };
  1411. }
  1412. return {
  1413. name: "Codeforces",
  1414. language,
  1415. get sourceCode() {
  1416. return getSourceCode();
  1417. },
  1418. set sourceCode(sourceCode) {
  1419. setSourceCode(sourceCode);
  1420. },
  1421. submit,
  1422. get testButtonContainer() {
  1423. return main;
  1424. },
  1425. get sideButtonContainer() {
  1426. return main;
  1427. },
  1428. get bottomMenuContainer() {
  1429. return doc.body;
  1430. },
  1431. get resultListContainer() {
  1432. return main;
  1433. },
  1434. get testCases() {
  1435. const testcases = [];
  1436. let index = 1;
  1437. for (const container of doc.querySelectorAll(".sample-test")) {
  1438. const input = container.querySelector(".input pre.content").textContent;
  1439. const output = container.querySelector(".output pre.content").textContent;
  1440. const anchor = container.querySelector(".input .title");
  1441. testcases.push({
  1442. input, output, anchor,
  1443. title: `Sample ${index++}`,
  1444. });
  1445. }
  1446. return testcases;
  1447. },
  1448. get jQuery() {
  1449. return unsafeWindow["jQuery"];
  1450. },
  1451. get taskURI() {
  1452. return location.href;
  1453. },
  1454. };
  1455. }
  1456.  
  1457. async function init$1() {
  1458. if (location.host != "greatest.deepsurf.us" && !location.href.match(/433152-atcoder-easy-test-v2/))
  1459. throw "Not about page";
  1460. const doc = unsafeWindow.document;
  1461. await loadScript("https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js");
  1462. const jQuery = unsafeWindow["jQuery"];
  1463. await loadScript("https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js", null, { jQuery, $: jQuery });
  1464. const e = newElement("div");
  1465. doc.getElementById("install-area").appendChild(newElement("button", {
  1466. type: "button",
  1467. textContent: "Open config",
  1468. onclick: () => settings.open(),
  1469. }));
  1470. return {
  1471. name: "About Page",
  1472. language: new ObservableValue(""),
  1473. get sourceCode() { return ""; },
  1474. set sourceCode(sourceCode) { },
  1475. submit() { },
  1476. get testButtonContainer() { return e; },
  1477. get sideButtonContainer() { return e; },
  1478. get bottomMenuContainer() { return e; },
  1479. get resultListContainer() { return e; },
  1480. get testCases() { return []; },
  1481. get jQuery() { return jQuery; },
  1482. get taskURI() { return ""; },
  1483. };
  1484. }
  1485.  
  1486. // 設定ページが開けなくなるのを避ける
  1487. const inits = [init$1()];
  1488. config.registerFlag("site.atcoder", true, "Use AtCoder Easy Test in AtCoder");
  1489. if (config.get("site.atcoder", true))
  1490. inits.push(init$5());
  1491. config.registerFlag("site.yukicoder", true, "Use AtCoder Easy Test in yukicoder");
  1492. if (config.get("site.yukicoder", true))
  1493. inits.push(init$4());
  1494. config.registerFlag("site.codeforces", true, "Use AtCoder Easy Test in Codeforces");
  1495. if (config.get("site.codeforces", true))
  1496. inits.push(init$3());
  1497. config.registerFlag("site.codeforcesMobile", true, "Use AtCoder Easy Test in Codeforces Mobile (m[1-3].codeforces.com)");
  1498. if (config.get("site.codeforcesMobile", true))
  1499. inits.push(init$2());
  1500. const site = Promise.any(inits);
  1501. site.catch(() => {
  1502. for (const promise of inits) {
  1503. promise.catch(console.error);
  1504. }
  1505. });
  1506.  
  1507. const runners = {
  1508. "C GCC 9.3.0 Wandbox": new WandboxRunner("gcc-9.3.0-c", "C (GCC 9.3.0)", { "compiler-option-raw": "-march=native\n-std=gnu11\n-O2\n-DONLINE_JUDGE\n-lm" }),
  1509. "C C17 Clang paiza.io": new PaizaIORunner("c", "C (C17 / Clang)"),
  1510. "C++ GCC 10.2.0 + Boost 1.73.0 + ACL Wandbox": new WandboxCppRunner("gcc-10.2.0", "C++ (GCC 10.2.0) + ACL", { "compiler-option-raw": "-march=native\n-std=gnu++17\n-Wall\n-Wextra\n-O2\n-DONLINE_JUDGE\n-I/opt/wandbox/boost-1.75.0-gcc-10.2.0/include\n-I." }),
  1511. "C++ GCC 9.3.0 + Boost 1.73.0 + ACL Wandbox": new WandboxCppRunner("gcc-9.3.0", "C++ (GCC 9.3.0) + ACL", { "compiler-option-raw": "-march=native\n-std=gnu++17\n-Wall\n-Wextra\n-O2\n-DONLINE_JUDGE\n-I/opt/wandbox/boost-1.75.0-gcc-9.3.0/include\n-I." }),
  1512. "C++ Clang 10.0.1 + ACL Wandbox": new WandboxCppRunner("clang-10.0.1", "C++ (Clang 10.0.1) + ACL", { "compiler-option-raw": "-march=native\n-std=c++17\n-stdlib=libc++\n-Wall\n-O2\n-DNDEBUG\n-DONLINE_JUDGE\n-I/opt/wandbox/boost-1.75.0-clang-10.0.1/include\n-I." }),
  1513. "Python3 CPython paiza.io": new PaizaIORunner("python3", "Python3"),
  1514. "Python3 Brython": brythonRunner,
  1515. "Python3 Pyodide": pyodideRunner,
  1516. "Bash paiza.io": new PaizaIORunner("bash", "Bash"),
  1517. "Bash 5.0.17 Wandbox": new WandboxRunner("bash", "Bash (5.0.17(1)-release)"),
  1518. "C# .NET Core 3.1.407 Wandbox": new WandboxRunner("dotnetcore-3.1.407", "C# (.NET Core 3.1.407)"),
  1519. "C# Mono-mcs 6.12.0.122 Wandbox": new WandboxRunner("mono-6.12.0.122", "C# (Mono-mcs 6.12.0.122)"),
  1520. "Clojure paiza.io": new PaizaIORunner("clojure", "Clojure"),
  1521. "Crystal 0.36.1 Wandbox": new WandboxRunner("crystal-0.36.1", "Crystal (0.36.1)"),
  1522. "D LDC paiza.io": new PaizaIORunner("d", "D (LDC)"),
  1523. "D DMD 2.093.1": new WandboxRunner("dmd-2.093.1", "D (DMD 2.093.1)"),
  1524. "D LDC 1.23.0": new WandboxRunner("ldc-1.23.0", "D (LDC 1.23.0)"),
  1525. "Erlang paiza.io": new PaizaIORunner("erlang", "Erlang"),
  1526. "Erlang 22.3.4.16": new WandboxRunner("erlang-22.3.4.16", "Erlang (22.3.4.16)"),
  1527. "Elixir 1.10.4": new WandboxRunner("elixir-1.10.4", "Elixir (1.10.4)"),
  1528. "Elixir paiza.io": new PaizaIORunner("elixir", "Elixir"),
  1529. "F# Interactive paiza.io": new PaizaIORunner("fsharp", "F# (Interactive)"),
  1530. "Go 1.14.15 Wandbox": new WandboxRunner("go-1.14.15", "Go (1.14.15)"),
  1531. "Haskell GHC 8.8.4 Wandbox": new WandboxRunner("ghc-8.8.4", "Haskell (GHC 8.8.4)"),
  1532. "Haskell paiza.io": new PaizaIORunner("haskell", "Haskell"),
  1533. "Java openjdk-jdk-15.0.3+2 Wandbox": new WandboxRunner("openjdk-jdk-15.0.3+2", "Java (JDK 15.0.3+2)"),
  1534. "Java openjdk-jdk-14.0.2+12 Wandbox": new WandboxRunner("openjdk-jdk-14.0.2+12", "Java (JDK 14.0.2+12)"),
  1535. "JavaScript paiza.io": new PaizaIORunner("javascript", "JavaScript"),
  1536. "JavaScript Node.js 12.22.1 Wandbox": new WandboxRunner("nodejs-12.22.1", "JavaScript (Node.js 12.22.1)"),
  1537. "Julia 1.6.1 Wandbox": new WandboxRunner("julia-1.6.1", "Julia (1.6.1)"),
  1538. "Kotlin paiza.io": new PaizaIORunner("kotlin", "Kotlin"),
  1539. "Lua 5.3.6 Wandbox": new WandboxRunner("lua-5.3.6", "Lua (Lua 5.3.6)"),
  1540. "Lua LuaJIT 2.0.5 Wandbox": new WandboxRunner("luajit-2.0.5", "Lua (LuaJIT 2.0.5)"),
  1541. "Nim 1.0.10 Wandbox": new WandboxRunner("nim-1.0.10", "Nim (1.0.10)"),
  1542. "Objective-C paiza.io": new PaizaIORunner("objective-c", "Objective-C"),
  1543. "OCaml 4.10.2 Wandbox": new WandboxRunner("ocaml-4.10.2", "OCaml (4.10.2)"),
  1544. "Pascal FPC 3.0.4 Wandbox": new WandboxRunner("fpc-3.0.4", "Pascal (FPC 3.0.4)"),
  1545. "Perl paiza.io": new PaizaIORunner("perl", "Perl"),
  1546. "Perl 5.30.3 Wandbox": new WandboxRunner("perl-5.30.3", "Perl (5.30.3)"),
  1547. "PHP paiza.io": new PaizaIORunner("php", "PHP"),
  1548. "PHP 7.4.16 Wandbox": new WandboxRunner("php-7.4.16", "PHP (7.4.16)"),
  1549. "Python PyPy 7.3.4 Wandbox": new WandboxRunner("pypy-2.7-v7.3.4", "PyPy2 (7.3.4)"),
  1550. "Python3 PyPy3 7.3.4 Wandbox": new WandboxRunner("pypy-3.7-v7.3.4", "PyPy3 (7.3.4)"),
  1551. "Ruby paiza.io": new PaizaIORunner("ruby", "Ruby"),
  1552. "Ruby 3.1.0 Wandbox": new WandboxRunner("ruby-3.1.0", "Ruby (3.1.0)"),
  1553. "Ruby 2.7.3 Wandbox": new WandboxRunner("ruby-2.7.3", "Ruby (2.7.1)"),
  1554. "Rust 1.42.0 AtCoder": new AtCoderRunner("4050", "Rust (1.42.0)"),
  1555. "Rust 1.50.0 Wandbox": new WandboxRunner("rust-1.50.0", "Rust (1.50.0)"),
  1556. "Rust paiza.io": new PaizaIORunner("rust", "Rust"),
  1557. "Scala paiza": new PaizaIORunner("scala", "Scala"),
  1558. "Scala 2.13.5 Wandbox": new WandboxRunner("scala-2.13.5", "Scala (2.13.5)"),
  1559. "Scheme paiza.io": new PaizaIORunner("scheme", "Scheme"),
  1560. "Swift paiza.io": new PaizaIORunner("swift", "Swift"),
  1561. "Swift 5.3.3 Wandbox": new WandboxRunner("swift-5.3.3", "Swift (5.3.3)"),
  1562. "TypeScript typescript-3.9.9 nodejs 14.16.1 Wandbox": new WandboxRunner("typescript-3.9.9 nodejs 14.16.1", "TypeScript (3.9.9)"),
  1563. "Text local": new CustomRunner("Text", async (sourceCode, input) => {
  1564. return {
  1565. status: "OK",
  1566. exitCode: "0",
  1567. input,
  1568. output: sourceCode,
  1569. };
  1570. }),
  1571. "Basic Visual Basic paiza.io": new PaizaIORunner("vb", "Visual Basic"),
  1572. "COBOL Free paiza.io": new PaizaIORunner("cobol", "COBOL - Free"),
  1573. "COBOL Fixed OpenCOBOL 1.1.0 AtCoder": new AtCoderRunner("4060", "COBOL - Fixed (OpenCOBOL 1.1.0)"),
  1574. "COBOL Free OpenCOBOL 1.1.0 AtCoder": new AtCoderRunner("4061", "COBOL - Free (OpenCOBOL 1.1.0)"),
  1575. };
  1576. site.then(site => {
  1577. if (site.name == "AtCoder") {
  1578. // AtCoderRunner がない場合は、追加する
  1579. for (const e of document.querySelectorAll("#select-lang option[value]")) {
  1580. const m = e.textContent.match(/([^ ]+) \(([^)]+)\)/);
  1581. if (m) {
  1582. const name = `${m[1]} ${m[2]} AtCoder`;
  1583. const languageId = e.value;
  1584. runners[name] = new AtCoderRunner(languageId, e.textContent);
  1585. }
  1586. }
  1587. }
  1588. });
  1589. console.info("AtCoder Easy Test: codeRunner OK");
  1590. config.registerCount("codeRunner.maxRetry", 3, "Max count of retry when IE (Internal Error)");
  1591. var codeRunner = {
  1592. // 指定した環境でコードを実行する
  1593. async run(runnerId, sourceCode, input, expectedOutput, options = { trim: true, split: true }) {
  1594. // CodeRunner が存在しない言語ID
  1595. if (!(runnerId in runners))
  1596. return Promise.reject("Language not supported");
  1597. // 最後に実行したコードを保存
  1598. if (sourceCode.length > 0)
  1599. site.then(site => codeSaver.save(site.taskURI, sourceCode));
  1600. // 実行
  1601. const maxRetry = config.get("codeRunner.maxRetry", 3);
  1602. for (let retry = 0; retry < maxRetry; retry++) {
  1603. try {
  1604. const result = await runners[runnerId].test(sourceCode, input, expectedOutput, options);
  1605. const lang = runnerId.split(" ")[0];
  1606. if (result.status == "IE") {
  1607. console.error(result);
  1608. const runnerIds = Object.keys(runners).filter(runnerId => runnerId.split(" ")[0] == lang);
  1609. const index = runnerIds.indexOf(runnerId);
  1610. runnerId = runnerIds[(index + 1) % runnerIds.length];
  1611. continue;
  1612. }
  1613. return result;
  1614. }
  1615. catch (e) {
  1616. console.error(e);
  1617. }
  1618. }
  1619. },
  1620. // 環境の名前の一覧を取得する
  1621. // @return runnerIdとラベルのペアの配列
  1622. async getEnvironment(languageId) {
  1623. const langs = similarLangs(languageId, Object.keys(runners));
  1624. if (langs.length == 0)
  1625. throw `Undefined language: ${languageId}`;
  1626. return langs.map(runnerId => [runnerId, runners[runnerId].label]);
  1627. },
  1628. };
  1629.  
  1630. var hBottomMenu = "<div id=\"bottom-menu-wrapper\" class=\"navbar navbar-default navbar-fixed-bottom\">\n <div class=\"container\">\n <div class=\"navbar-header\">\n <button id=\"bottom-menu-key\" type=\"button\" class=\"navbar-toggle collapsed glyphicon glyphicon-menu-down\" data-toggle=\"collapse\" data-target=\"#bottom-menu\"></button>\n </div>\n <div id=\"bottom-menu\" class=\"collapse navbar-collapse\">\n <ul id=\"bottom-menu-tabs\" class=\"nav nav-tabs\"></ul>\n <div id=\"bottom-menu-contents\" class=\"tab-content\"></div>\n </div>\n </div>\n</div>";
  1631.  
  1632. var hStyle$1 = "<style>\n#bottom-menu-wrapper {\n background: transparent !important;\n border: none !important;\n pointer-events: none;\n padding: 0;\n}\n\n#bottom-menu-wrapper>.container {\n position: absolute;\n bottom: 0;\n width: 100%;\n padding: 0;\n}\n\n#bottom-menu-wrapper>.container>.navbar-header {\n float: none;\n}\n\n#bottom-menu-key {\n display: block;\n float: none;\n margin: 0 auto;\n padding: 10px 3em;\n border-radius: 5px 5px 0 0;\n background: #000;\n opacity: 0.5;\n color: #FFF;\n cursor: pointer;\n pointer-events: auto;\n text-align: center;\n}\n\n@media screen and (max-width: 767px) {\n #bottom-menu-key {\n opacity: 0.25;\n }\n}\n\n#bottom-menu-key.collapsed:before {\n content: \"\\e260\";\n}\n\n#bottom-menu-tabs {\n padding: 3px 0 0 10px;\n cursor: n-resize;\n}\n\n#bottom-menu-tabs a {\n pointer-events: auto;\n}\n\n#bottom-menu {\n pointer-events: auto;\n background: rgba(0, 0, 0, 0.8);\n color: #fff;\n max-height: unset;\n}\n\n#bottom-menu.collapse:not(.in) {\n display: none !important;\n}\n\n#bottom-menu-tabs>li>a {\n background: rgba(150, 150, 150, 0.5);\n color: #000;\n border: solid 1px #ccc;\n filter: brightness(0.75);\n}\n\n#bottom-menu-tabs>li>a:hover {\n background: rgba(150, 150, 150, 0.5);\n border: solid 1px #ccc;\n color: #111;\n filter: brightness(0.9);\n}\n\n#bottom-menu-tabs>li.active>a {\n background: #eee;\n border: solid 1px #ccc;\n color: #333;\n filter: none;\n}\n\n.bottom-menu-btn-close {\n font-size: 8pt;\n vertical-align: baseline;\n padding: 0 0 0 6px;\n margin-right: -6px;\n}\n\n#bottom-menu-contents {\n padding: 5px 15px;\n max-height: 50vh;\n overflow-y: auto;\n}\n\n#bottom-menu-contents .panel {\n color: #333;\n}\n</style>";
  1633.  
  1634. async function init() {
  1635. const site$1 = await site;
  1636. const style = html2element(hStyle$1);
  1637. const bottomMenu = html2element(hBottomMenu);
  1638. unsafeWindow.document.head.appendChild(style);
  1639. site$1.bottomMenuContainer.appendChild(bottomMenu);
  1640. const bottomMenuKey = bottomMenu.querySelector("#bottom-menu-key");
  1641. const bottomMenuTabs = bottomMenu.querySelector("#bottom-menu-tabs");
  1642. const bottomMenuContents = bottomMenu.querySelector("#bottom-menu-contents");
  1643. // メニューのリサイズ
  1644. {
  1645. let resizeStart = null;
  1646. const onStart = (event) => {
  1647. const target = event.target;
  1648. const pageY = event.pageY;
  1649. if (target.id != "bottom-menu-tabs")
  1650. return;
  1651. resizeStart = { y: pageY, height: bottomMenuContents.getBoundingClientRect().height };
  1652. };
  1653. const onMove = (event) => {
  1654. if (!resizeStart)
  1655. return;
  1656. event.preventDefault();
  1657. bottomMenuContents.style.height = `${resizeStart.height - (event.pageY - resizeStart.y)}px`;
  1658. };
  1659. const onEnd = () => {
  1660. resizeStart = null;
  1661. };
  1662. bottomMenuTabs.addEventListener("mousedown", onStart);
  1663. bottomMenuTabs.addEventListener("mousemove", onMove);
  1664. bottomMenuTabs.addEventListener("mouseup", onEnd);
  1665. bottomMenuTabs.addEventListener("mouseleave", onEnd);
  1666. }
  1667. let tabs = new Set();
  1668. let selectedTab = null;
  1669. /** 下メニューの操作
  1670. * 下メニューはいくつかのタブからなる。タブはそれぞれ tabId, ラベル, 中身を持っている。
  1671. */
  1672. const menuController = {
  1673. /** タブを選択 */
  1674. selectTab(tabId) {
  1675. const tab = site$1.jQuery(`#bottom-menu-tab-${tabId}`);
  1676. if (tab && tab[0]) {
  1677. tab.tab("show"); // Bootstrap 3
  1678. selectedTab = tabId;
  1679. }
  1680. },
  1681. /** 下メニューにタブを追加する */
  1682. addTab(tabId, tabLabel, paneContent, options = {}) {
  1683. console.log(`AtCoder Easy Test: addTab: ${tabLabel} (${tabId})`, paneContent);
  1684. // タブを追加
  1685. const tab = document.createElement("a");
  1686. tab.textContent = tabLabel;
  1687. tab.id = `bottom-menu-tab-${tabId}`;
  1688. tab.href = "#";
  1689. tab.dataset.id = tabId;
  1690. tab.dataset.target = `#bottom-menu-pane-${tabId}`;
  1691. tab.dataset.toggle = "tab";
  1692. tab.addEventListener("click", event => {
  1693. event.preventDefault();
  1694. menuController.selectTab(tabId);
  1695. });
  1696. tabs.add(tab);
  1697. const tabLi = document.createElement("li");
  1698. tabLi.appendChild(tab);
  1699. bottomMenuTabs.appendChild(tabLi);
  1700. // 内容を追加
  1701. const pane = document.createElement("div");
  1702. pane.className = "tab-pane";
  1703. pane.id = `bottom-menu-pane-${tabId}`;
  1704. pane.appendChild(paneContent);
  1705. bottomMenuContents.appendChild(pane);
  1706. const controller = {
  1707. get id() {
  1708. return tabId;
  1709. },
  1710. close() {
  1711. bottomMenuTabs.removeChild(tabLi);
  1712. bottomMenuContents.removeChild(pane);
  1713. tabs.delete(tab);
  1714. if (selectedTab == tabId) {
  1715. selectedTab = null;
  1716. if (tabs.size > 0) {
  1717. menuController.selectTab(tabs.values().next().value.dataset.id);
  1718. }
  1719. }
  1720. },
  1721. show() {
  1722. menuController.show();
  1723. menuController.selectTab(tabId);
  1724. },
  1725. set color(color) {
  1726. tab.style.backgroundColor = color;
  1727. },
  1728. };
  1729. // 閉じるボタン
  1730. if (options.closeButton) {
  1731. const btn = document.createElement("a");
  1732. btn.className = "bottom-menu-btn-close btn btn-link glyphicon glyphicon-remove";
  1733. btn.addEventListener("click", () => {
  1734. controller.close();
  1735. });
  1736. tab.appendChild(btn);
  1737. }
  1738. // 選択されているタブがなければ選択
  1739. if (!selectedTab)
  1740. menuController.selectTab(tabId);
  1741. return controller;
  1742. },
  1743. /** 下メニューを表示する */
  1744. show() {
  1745. if (bottomMenuKey.classList.contains("collapsed"))
  1746. bottomMenuKey.click();
  1747. },
  1748. /** 下メニューの表示/非表示を切り替える */
  1749. toggle() {
  1750. bottomMenuKey.click();
  1751. },
  1752. };
  1753. console.info("AtCoder Easy Test: bottomMenu OK");
  1754. return menuController;
  1755. }
  1756.  
  1757. var hRowTemplate = "<div class=\"atcoder-easy-test-cases-row alert alert-dismissible\">\n <button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">\n <span aria-hidden=\"true\">×</span>\n </button>\n <div class=\"progress\">\n <div class=\"progress-bar\" style=\"width: 0%;\">0 / 0</div>\n </div>\n <div class=\"atcoder-easy-test-cases-row-date\" style=\"font-family: monospace; text-align: right; position: absolute; right: 1em;\"></div>\n</div>";
  1758.  
  1759. class ResultRow {
  1760. _tabs;
  1761. _element;
  1762. _promise;
  1763. constructor(pairs) {
  1764. this._tabs = pairs.map(([_, tab]) => tab);
  1765. this._element = html2element(hRowTemplate);
  1766. this._element.querySelector(".close").addEventListener("click", () => this.remove());
  1767. {
  1768. const date = new Date();
  1769. const h = date.getHours().toString().padStart(2, "0");
  1770. const m = date.getMinutes().toString().padStart(2, "0");
  1771. const s = date.getSeconds().toString().padStart(2, "0");
  1772. this._element.querySelector(".atcoder-easy-test-cases-row-date").textContent = `${h}:${m}:${s}`;
  1773. }
  1774. const numCases = pairs.length;
  1775. let numFinished = 0;
  1776. let numAccepted = 0;
  1777. const progressBar = this._element.querySelector(".progress-bar");
  1778. progressBar.textContent = `${numFinished} / ${numCases}`;
  1779. this._promise = Promise.all(pairs.map(([pResult, tab]) => {
  1780. const button = html2element(`<div class="label label-default" style="margin: 3px; cursor: pointer;">WJ</div>`);
  1781. button.addEventListener("click", async () => {
  1782. (await tab).show();
  1783. });
  1784. this._element.appendChild(button);
  1785. return pResult.then(result => {
  1786. button.textContent = result.status;
  1787. if (result.status == "AC") {
  1788. button.classList.add("label-success");
  1789. }
  1790. else if (result.status != "OK") {
  1791. button.classList.add("label-warning");
  1792. }
  1793. numFinished++;
  1794. if (result.status == "AC")
  1795. numAccepted++;
  1796. progressBar.textContent = `${numFinished} / ${numCases}`;
  1797. progressBar.style.width = `${100 * numFinished / numCases}%`;
  1798. if (numFinished == numCases) {
  1799. if (numAccepted == numCases)
  1800. this._element.classList.add("alert-success");
  1801. else
  1802. this._element.classList.add("alert-warning");
  1803. }
  1804. }).catch(reason => {
  1805. button.textContent = "IE";
  1806. button.classList.add("label-danger");
  1807. console.error(reason);
  1808. });
  1809. }));
  1810. }
  1811. get element() {
  1812. return this._element;
  1813. }
  1814. onFinish(listener) {
  1815. this._promise.then(listener);
  1816. }
  1817. remove() {
  1818. for (const pTab of this._tabs)
  1819. pTab.then(tab => tab.close());
  1820. const parent = this._element.parentElement;
  1821. if (parent)
  1822. parent.removeChild(this._element);
  1823. }
  1824. }
  1825.  
  1826. var hResultList = "<div class=\"row\"></div>";
  1827.  
  1828. const eResultList = html2element(hResultList);
  1829. site.then(site => site.resultListContainer.appendChild(eResultList));
  1830. const resultList = {
  1831. addResult(pairs) {
  1832. const result = new ResultRow(pairs);
  1833. eResultList.insertBefore(result.element, eResultList.firstChild);
  1834. return result;
  1835. },
  1836. };
  1837.  
  1838. const version = {
  1839. currentProperty: new ObservableValue("2.11.5"),
  1840. get current() {
  1841. return this.currentProperty.value;
  1842. },
  1843. latestProperty: new ObservableValue(config.get("version.latest", "2.11.5")),
  1844. get latest() {
  1845. return this.latestProperty.value;
  1846. },
  1847. lastCheckProperty: new ObservableValue(config.get("version.lastCheck", 0)),
  1848. get lastCheck() {
  1849. return this.lastCheckProperty.value;
  1850. },
  1851. get hasUpdate() {
  1852. return this.compare(this.current, this.latest) < 0;
  1853. },
  1854. compare(a, b) {
  1855. const x = a.split(".").map((s) => parseInt(s, 10));
  1856. const y = b.split(".").map((s) => parseInt(s, 10));
  1857. for (let i = 0; i < 3; i++) {
  1858. if (x[i] < y[i]) {
  1859. return -1;
  1860. }
  1861. else if (x[i] > y[i]) {
  1862. return 1;
  1863. }
  1864. }
  1865. return 0;
  1866. },
  1867. async checkUpdate(force = false) {
  1868. const now = Date.now();
  1869. if (!force && now - version.lastCheck < config.get("version.checkInterval", aDay)) {
  1870. return this.current;
  1871. }
  1872. const packageJson = await fetch("https://raw.githubusercontent.com/magurofly/atcoder-easy-test/main/v2/package.json").then(r => r.json());
  1873. console.log(packageJson);
  1874. const latest = packageJson["version"];
  1875. this.latestProperty.value = latest;
  1876. config.set("version.latest", latest);
  1877. this.lastCheckProperty.value = now;
  1878. config.set("version.lastCheck", now);
  1879. return latest;
  1880. },
  1881. };
  1882. // 更新チェック
  1883. const aDay = 24 * 60 * 60 * 1e3;
  1884. config.registerCount("version.checkInterval", aDay, "Interval [ms] of checking for new version");
  1885. config.get("version.checkInterval", aDay);
  1886. setInterval(() => {
  1887. version.checkUpdate(false);
  1888. }, 60e3);
  1889. settings.add("version", (win) => {
  1890. const root = newElement("div");
  1891. const text = win.document.createTextNode.bind(win.document);
  1892. const textAuto = (property) => {
  1893. const t = text(property.value);
  1894. property.addListener(value => {
  1895. t.textContent = value;
  1896. });
  1897. return t;
  1898. };
  1899. const tCurrent = textAuto(version.currentProperty);
  1900. const tLatest = textAuto(version.latestProperty);
  1901. const tLastCheck = textAuto(version.lastCheckProperty.map(time => new Date(time).toLocaleString()));
  1902. root.appendChild(newElement("p", {}, [
  1903. text("AtCoder Easy Test v"),
  1904. tCurrent,
  1905. ]));
  1906. const updateButton = newElement("a", {
  1907. className: "btn btn-info",
  1908. textContent: "Install",
  1909. href: "https://github.com/magurofly/atcoder-easy-test/raw/main/v2/atcoder-easy-test.user.js",
  1910. target: "_blank",
  1911. });
  1912. const showButton = () => {
  1913. if (version.hasUpdate)
  1914. updateButton.style.display = "inline";
  1915. else
  1916. updateButton.style.display = "none";
  1917. };
  1918. showButton();
  1919. version.lastCheckProperty.addListener(showButton);
  1920. root.appendChild(newElement("p", {}, [
  1921. text("Latest: v"),
  1922. tLatest,
  1923. text(" (Last Check: "),
  1924. tLastCheck,
  1925. text(") "),
  1926. updateButton,
  1927. ]));
  1928. root.appendChild(newElement("p", {}, [
  1929. newElement("a", {
  1930. className: "btn btn-primary",
  1931. textContent: "Check Update",
  1932. onclick() {
  1933. version.checkUpdate(true);
  1934. },
  1935. }),
  1936. ]));
  1937. return root;
  1938. });
  1939.  
  1940. var hTabTemplate = "<div class=\"atcoder-easy-test-result container\">\n <div class=\"row\">\n <div class=\"atcoder-easy-test-result-col-input col-xs-12\" data-if-expected-output=\"col-sm-6 col-sm-push-6\">\n <div class=\"form-group\">\n <label class=\"control-label col-xs-12\">\n Standard Input\n <div class=\"col-xs-12\">\n <textarea class=\"atcoder-easy-test-result-input form-control\" rows=\"3\" readonly=\"readonly\"></textarea>\n </div>\n </label>\n </div>\n </div>\n <div class=\"atcoder-easy-test-result-col-expected-output col-xs-12 col-sm-6 hidden\" data-if-expected-output=\"!hidden col-sm-pull-6\">\n <div class=\"form-group\">\n <label class=\"control-label col-xs-12\">\n Expected Output\n <div class=\"col-xs-12\">\n <textarea class=\"atcoder-easy-test-result-expected-output form-control\" rows=\"3\" readonly=\"readonly\"></textarea>\n </div>\n </label>\n </div>\n </div>\n </div>\n <div class=\"row\"><div class=\"col-sm-6 col-sm-offset-3\">\n <div class=\"panel panel-default\">\n <table class=\"table table-condensed\">\n <tbody>\n <tr>\n <th class=\"text-center\">Exit Code</th>\n <th class=\"text-center\">Exec Time</th>\n <th class=\"text-center\">Memory</th>\n </tr>\n <tr>\n <td class=\"atcoder-easy-test-result-exit-code text-center\"></td>\n <td class=\"atcoder-easy-test-result-exec-time text-center\"></td>\n <td class=\"atcoder-easy-test-result-memory text-center\"></td>\n </tr>\n </tbody>\n </table>\n </div>\n </div></div>\n <div class=\"row\">\n <div class=\"atcoder-easy-test-result-col-output col-xs-12\" data-if-error=\"col-md-6\">\n <div class=\"form-group\">\n <label class=\"control-label col-xs-12\">\n Standard Output\n <div class=\"col-xs-12\">\n <textarea class=\"atcoder-easy-test-result-output form-control\" rows=\"5\" readonly=\"readonly\"></textarea>\n </div>\n </label>\n </div>\n </div>\n <div class=\"atcoder-easy-test-result-col-error col-xs-12 col-md-6 hidden\" data-if-error=\"!hidden\">\n <div class=\"form-group\">\n <label class=\"control-label col-xs-12\">\n Standard Error\n <div class=\"col-xs-12\">\n <textarea class=\"atcoder-easy-test-result-error form-control\" rows=\"5\" readonly=\"readonly\"></textarea>\n </div>\n </label>\n </div>\n </div>\n </div>\n</div>";
  1941.  
  1942. function setClassFromData(element, name) {
  1943. const classes = element.dataset[name].split(/\s+/);
  1944. for (let className of classes) {
  1945. let flag = true;
  1946. if (className[0] == "!") {
  1947. className = className.slice(1);
  1948. flag = false;
  1949. }
  1950. element.classList.toggle(className, flag);
  1951. }
  1952. }
  1953. class ResultTabContent {
  1954. _title;
  1955. _uid;
  1956. _element;
  1957. _result;
  1958. constructor() {
  1959. this._uid = Date.now().toString(16) + Math.floor(Math.random() * 256).toString(16);
  1960. this._result = null;
  1961. this._element = html2element(hTabTemplate);
  1962. this._element.id = `atcoder-easy-test-result-${this._uid}`;
  1963. }
  1964. set result(result) {
  1965. this._result = result;
  1966. if (result.status == "AC") {
  1967. this.outputStyle.backgroundColor = "#dff0d8";
  1968. }
  1969. else if (result.status != "OK") {
  1970. this.outputStyle.backgroundColor = "#fcf8e3";
  1971. }
  1972. this.input = result.input;
  1973. if ("expectedOutput" in result)
  1974. this.expectedOutput = result.expectedOutput;
  1975. this.exitCode = result.exitCode;
  1976. if ("execTime" in result)
  1977. this.execTime = `${result.execTime} ms`;
  1978. if ("memory" in result)
  1979. this.memory = `${result.memory} KB`;
  1980. if ("output" in result)
  1981. this.output = result.output;
  1982. if (result.error)
  1983. this.error = result.error;
  1984. }
  1985. get result() {
  1986. return this._result;
  1987. }
  1988. get uid() {
  1989. return this._uid;
  1990. }
  1991. get element() {
  1992. return this._element;
  1993. }
  1994. set title(title) {
  1995. this._title = title;
  1996. }
  1997. get title() {
  1998. return this._title;
  1999. }
  2000. set input(input) {
  2001. this._get("input").value = input;
  2002. }
  2003. get inputStyle() {
  2004. return this._get("input").style;
  2005. }
  2006. set expectedOutput(output) {
  2007. this._get("expected-output").value = output;
  2008. setClassFromData(this._get("col-input"), "ifExpectedOutput");
  2009. setClassFromData(this._get("col-expected-output"), "ifExpectedOutput");
  2010. }
  2011. get expectedOutputStyle() {
  2012. return this._get("expected-output").style;
  2013. }
  2014. set output(output) {
  2015. this._get("output").value = output;
  2016. }
  2017. get outputStyle() {
  2018. return this._get("output").style;
  2019. }
  2020. set error(error) {
  2021. this._get("error").value = error;
  2022. setClassFromData(this._get("col-output"), "ifError");
  2023. setClassFromData(this._get("col-error"), "ifError");
  2024. }
  2025. set exitCode(code) {
  2026. const element = this._get("exit-code");
  2027. element.textContent = code;
  2028. const isSuccess = code == "0";
  2029. element.classList.toggle("bg-success", isSuccess);
  2030. element.classList.toggle("bg-danger", !isSuccess);
  2031. }
  2032. set execTime(time) {
  2033. this._get("exec-time").textContent = time;
  2034. }
  2035. set memory(memory) {
  2036. this._get("memory").textContent = memory;
  2037. }
  2038. _get(name) {
  2039. return this._element.querySelector(`.atcoder-easy-test-result-${name}`);
  2040. }
  2041. }
  2042.  
  2043. var hRoot = "<form id=\"atcoder-easy-test-container\" class=\"form-horizontal\">\n <div class=\"row\">\n <div class=\"col-xs-12 col-lg-8\">\n <div class=\"form-group\">\n <label class=\"control-label col-sm-2\">Test Environment</label>\n <div class=\"col-sm-10\">\n <select class=\"form-control\" id=\"atcoder-easy-test-language\"></select>\n </div>\n </div>\n <div class=\"form-group\">\n <label class=\"control-label col-sm-2\" for=\"atcoder-easy-test-input\">Standard Input</label>\n <div class=\"col-sm-10\">\n <textarea id=\"atcoder-easy-test-input\" name=\"input\" class=\"form-control\" rows=\"3\"></textarea>\n </div>\n </div>\n </div>\n <div class=\"col-xs-12 col-lg-4\">\n <details close>\n <summary>Expected Output</summary>\n <div class=\"form-group\">\n <label class=\"control-label col-sm-2\" for=\"atcoder-easy-test-allowable-error-check\">Allowable Error</label>\n <div class=\"col-sm-10\">\n <div class=\"input-group\">\n <span class=\"input-group-addon\">\n <input id=\"atcoder-easy-test-allowable-error-check\" type=\"checkbox\" checked=\"checked\">\n </span>\n <input id=\"atcoder-easy-test-allowable-error\" type=\"text\" class=\"form-control\" value=\"1e-6\">\n </div>\n </div>\n </div>\n <div class=\"form-group\">\n <label class=\"control-label col-sm-2\" for=\"atcoder-easy-test-output\">Expected Output</label>\n <div class=\"col-sm-10\">\n <textarea id=\"atcoder-easy-test-output\" name=\"output\" class=\"form-control\" rows=\"3\"></textarea>\n </div>\n </div>\n </details>\n </div>\n <div class=\"col-xs-12 col-md-6\">\n <div class=\"col-xs-11 col-xs-offset=1\">\n <div class=\"form-group\">\n <a id=\"atcoder-easy-test-run\" class=\"btn btn-primary\">Run</a>\n </div>\n </div>\n </div>\n <div class=\"col-xs-12 col-md-6\">\n <div class=\"col-xs-11 col-xs-offset=1\">\n <div class=\"form-group text-right\">\n <small>AtCoder Easy Test v<span id=\"atcoder-easy-test-version\"></span></small>\n <a id=\"atcoder-easy-test-setting\" class=\"btn btn-xs btn-default\">Setting</a>\n </div>\n </div>\n </div>\n </div>\n <style>\n #atcoder-easy-test-language {\n border: none;\n background: transparent;\n font: inherit;\n color: #fff;\n }\n #atcoder-easy-test-language option {\n border: none;\n color: #333;\n font: inherit;\n }\n </style>\n</form>";
  2044.  
  2045. var hStyle = "<style>\n.atcoder-easy-test-result textarea {\n font-family: monospace;\n font-weight: normal;\n}\n</style>";
  2046.  
  2047. var hRunButton = "<button type=\"button\" class=\"btn btn-primary btn-sm atcoder-easy-test-btn-run-case\" style=\"vertical-align: top; margin-left: 0.5em\">Run</button>";
  2048.  
  2049. var hTestAndSubmit = "<button type=\"button\" id=\"atcoder-easy-test-btn-test-and-submit\" class=\"btn btn-info btn\" style=\"margin-left: 1rem\" title=\"Ctrl+Enter\" data-toggle=\"tooltip\">Test &amp; Submit</button>";
  2050.  
  2051. var hTestAllSamples = "<button type=\"button\" id=\"atcoder-easy-test-btn-test-all\" class=\"btn btn-default btn-sm\" style=\"margin-left: 1rem\" title=\"Alt+Enter\" data-toggle=\"tooltip\">Test All Samples</button>";
  2052.  
  2053. (async () => {
  2054. const site$1 = await site;
  2055. const doc = unsafeWindow.document;
  2056. // init bottomMenu
  2057. const pBottomMenu = init();
  2058. pBottomMenu.then(bottomMenu => {
  2059. unsafeWindow.bottomMenu = bottomMenu;
  2060. });
  2061. await doneOrFail(pBottomMenu);
  2062. // external interfaces
  2063. unsafeWindow.codeRunner = codeRunner;
  2064. doc.head.appendChild(html2element(hStyle));
  2065. // interface
  2066. const atCoderEasyTest = {
  2067. version,
  2068. site: site$1,
  2069. config,
  2070. codeSaver,
  2071. enableButtons() {
  2072. events.trig("enable");
  2073. },
  2074. disableButtons() {
  2075. events.trig("disable");
  2076. },
  2077. runCount: 0,
  2078. runTest(title, language, sourceCode, input, output = null, options = { trim: true, split: true, }) {
  2079. this.disableButtons();
  2080. const content = new ResultTabContent();
  2081. const pTab = pBottomMenu.then(bottomMenu => bottomMenu.addTab("easy-test-result-" + content.uid, `#${++this.runCount} ${title}`, content.element, { active: true, closeButton: true }));
  2082. const pResult = codeRunner.run(language, sourceCode, input, output, options);
  2083. pResult.then(result => {
  2084. content.result = result;
  2085. if (result.status == "AC") {
  2086. pTab.then(tab => tab.color = "#dff0d8");
  2087. }
  2088. else if (result.status != "OK") {
  2089. pTab.then(tab => tab.color = "#fcf8e3");
  2090. }
  2091. }).finally(() => {
  2092. this.enableButtons();
  2093. });
  2094. return [pResult, pTab];
  2095. }
  2096. };
  2097. unsafeWindow.atCoderEasyTest = atCoderEasyTest;
  2098. // place "Easy Test" tab
  2099. {
  2100. // declare const hRoot: string;
  2101. const root = html2element(hRoot);
  2102. const E = (id) => root.querySelector(`#atcoder-easy-test-${id}`);
  2103. const eLanguage = E("language");
  2104. const eInput = E("input");
  2105. const eAllowableErrorCheck = E("allowable-error-check");
  2106. const eAllowableError = E("allowable-error");
  2107. const eOutput = E("output");
  2108. const eRun = E("run");
  2109. const eSetting = E("setting");
  2110. const eVersion = E("version");
  2111. eVersion.textContent = atCoderEasyTest.version.current;
  2112. events.on("enable", () => {
  2113. eRun.classList.remove("disabled");
  2114. });
  2115. events.on("disable", () => {
  2116. eRun.classList.add("disabled");
  2117. });
  2118. eSetting.addEventListener("click", () => {
  2119. settings.open();
  2120. });
  2121. // バージョン確認
  2122. {
  2123. let button = null;
  2124. const showButton = () => {
  2125. if (!version.hasUpdate)
  2126. return;
  2127. if (button) {
  2128. button.textContent = `Update to v${version.latest}`;
  2129. return;
  2130. }
  2131. console.info(`AtCoder Easy Test: New version available: v${version}`);
  2132. button = newElement("a", {
  2133. href: "https://github.com/magurofly/atcoder-easy-test/raw/main/v2/atcoder-easy-test.user.js",
  2134. target: "_blank",
  2135. className: "btn btn-xs btn-info",
  2136. textContent: `Update to v${version.latest}`,
  2137. });
  2138. eVersion.insertAdjacentElement("afterend", button);
  2139. };
  2140. version.latestProperty.addListener(showButton);
  2141. showButton();
  2142. }
  2143. // 言語選択関係
  2144. {
  2145. eLanguage.addEventListener("change", async () => {
  2146. const langSelection = config.get("langSelection", {});
  2147. langSelection[site$1.language.value] = eLanguage.value;
  2148. config.set("langSelection", langSelection);
  2149. });
  2150. async function setLanguage() {
  2151. const languageId = site$1.language.value;
  2152. while (eLanguage.firstChild)
  2153. eLanguage.removeChild(eLanguage.firstChild);
  2154. try {
  2155. const langs = await codeRunner.getEnvironment(languageId);
  2156. console.log(`language: ${langs[1]} (${langs[0]})`);
  2157. // add <option>
  2158. for (const [languageId, label] of langs) {
  2159. const option = document.createElement("option");
  2160. option.value = languageId;
  2161. option.textContent = label;
  2162. eLanguage.appendChild(option);
  2163. }
  2164. // load
  2165. const langSelection = config.get("langSelection", {});
  2166. if (languageId in langSelection) {
  2167. const prev = langSelection[languageId];
  2168. const [lang, _] = langs.find(([lang, label]) => lang == prev);
  2169. if (lang)
  2170. eLanguage.value = lang;
  2171. }
  2172. events.trig("enable");
  2173. }
  2174. catch (error) {
  2175. console.log(`language: ? (${languageId})`);
  2176. console.error(error);
  2177. const option = document.createElement("option");
  2178. option.className = "fg-danger";
  2179. option.textContent = error;
  2180. eLanguage.appendChild(option);
  2181. events.trig("disable");
  2182. }
  2183. }
  2184. site$1.language.addListener(() => setLanguage());
  2185. eAllowableError.disabled = !eAllowableErrorCheck.checked;
  2186. eAllowableErrorCheck.addEventListener("change", event => {
  2187. eAllowableError.disabled = !eAllowableErrorCheck.checked;
  2188. });
  2189. }
  2190. // テスト実行
  2191. function runTest(title, input, output = null) {
  2192. const options = { trim: true, split: true, };
  2193. if (eAllowableErrorCheck.checked) {
  2194. options.allowableError = parseFloat(eAllowableError.value);
  2195. }
  2196. return atCoderEasyTest.runTest(title, eLanguage.value, site$1.sourceCode, input, output, options);
  2197. }
  2198. function runAllCases(testcases) {
  2199. const pairs = testcases.map(testcase => runTest(testcase.title, testcase.input, testcase.output));
  2200. resultList.addResult(pairs);
  2201. return Promise.all(pairs.map(([pResult, _]) => pResult.then(result => {
  2202. if (result.status == "AC")
  2203. return Promise.resolve(result);
  2204. else
  2205. return Promise.reject(result);
  2206. })));
  2207. }
  2208. eRun.addEventListener("click", _ => {
  2209. const title = "Run";
  2210. const input = eInput.value;
  2211. const output = eOutput.value;
  2212. runTest(title, input, output || null);
  2213. });
  2214. await doneOrFail(pBottomMenu.then(bottomMenu => bottomMenu.addTab("easy-test", "Easy Test", root)));
  2215. // place "Run" button on each sample
  2216. for (const testCase of site$1.testCases) {
  2217. const eRunButton = html2element(hRunButton);
  2218. eRunButton.addEventListener("click", async () => {
  2219. const [pResult, pTab] = runTest(testCase.title, testCase.input, testCase.output);
  2220. await pResult;
  2221. (await pTab).show();
  2222. });
  2223. testCase.anchor.insertAdjacentElement("afterend", eRunButton);
  2224. events.on("disable", () => {
  2225. eRunButton.classList.add("disabled");
  2226. });
  2227. events.on("enable", () => {
  2228. eRunButton.classList.remove("disabled");
  2229. });
  2230. }
  2231. // place "Test & Submit" button
  2232. {
  2233. const button = html2element(hTestAndSubmit);
  2234. site$1.testButtonContainer.appendChild(button);
  2235. const testAndSubmit = async () => {
  2236. await runAllCases(site$1.testCases);
  2237. site$1.submit();
  2238. };
  2239. button.addEventListener("click", testAndSubmit);
  2240. events.on("testAndSubmit", testAndSubmit);
  2241. events.on("disable", () => button.classList.add("disabled"));
  2242. events.on("enable", () => button.classList.remove("disabled"));
  2243. }
  2244. // place "Test All Samples" button
  2245. {
  2246. const button = html2element(hTestAllSamples);
  2247. site$1.testButtonContainer.appendChild(button);
  2248. const testAllSamples = () => runAllCases(site$1.testCases);
  2249. button.addEventListener("click", testAllSamples);
  2250. events.on("testAllSamples", testAllSamples);
  2251. events.on("disable", () => button.classList.add("disabled"));
  2252. events.on("enable", () => button.classList.remove("disabled"));
  2253. }
  2254. }
  2255. // place "Restore Last Play" button
  2256. try {
  2257. const restoreButton = doc.createElement("a");
  2258. restoreButton.className = "btn btn-danger btn-sm";
  2259. restoreButton.textContent = "Restore Last Play";
  2260. restoreButton.addEventListener("click", async () => {
  2261. try {
  2262. const lastCode = await codeSaver.restore(site$1.taskURI);
  2263. if (site$1.sourceCode.length == 0 || confirm("Your current code will be replaced. Are you sure?")) {
  2264. site$1.sourceCode = lastCode;
  2265. }
  2266. }
  2267. catch (reason) {
  2268. alert(reason);
  2269. }
  2270. });
  2271. site$1.sideButtonContainer.appendChild(restoreButton);
  2272. }
  2273. catch (e) {
  2274. console.error(e);
  2275. }
  2276. // キーボードショートカット
  2277. config.registerFlag("ui.useKeyboardShortcut", true, "Use Keyboard Shortcuts");
  2278. unsafeWindow.addEventListener("keydown", (event) => {
  2279. if (config.get("ui.useKeyboardShortcut", true)) {
  2280. if (event.key == "Enter" && event.ctrlKey) {
  2281. events.trig("testAndSubmit");
  2282. }
  2283. else if (event.key == "Enter" && event.altKey) {
  2284. events.trig("testAllSamples");
  2285. }
  2286. else if (event.key == "Escape" && event.altKey) {
  2287. pBottomMenu.then(bottomMenu => bottomMenu.toggle());
  2288. }
  2289. }
  2290. });
  2291. })();
  2292. })();