AtCoder Easy Test v2

Make testing sample cases easy

  1. // ==UserScript==
  2. // @name AtCoder Easy Test v2
  3. // @namespace https://atcoder.jp/
  4. // @version 2.13.0
  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://greasyfork.org/*/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, options);
  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. const ce_groups = new Set();
  458. class AtCoderRunner extends CodeRunner {
  459. languageId;
  460. constructor(languageId, label) {
  461. super(label, "AtCoder");
  462. this.languageId = languageId;
  463. }
  464. async run(sourceCode, input, options = {}) {
  465. const promise = this.submit(sourceCode, input, options);
  466. waitAtCoderCustomTest = promise;
  467. return await promise;
  468. }
  469. async submit(sourceCode, input, options = {}) {
  470. try {
  471. await waitAtCoderCustomTest;
  472. }
  473. catch (error) {
  474. console.error(error);
  475. }
  476. // 同じグループで CE なら実行を省略し CE を返す
  477. if ("runGroupId" in options && ce_groups.has(options.runGroupId)) {
  478. return {
  479. status: "CE",
  480. input,
  481. };
  482. }
  483. const error = await fetch(AtCoderCustomTestSubmitAPI, {
  484. method: "POST",
  485. credentials: "include",
  486. headers: {
  487. "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
  488. },
  489. body: buildParams({
  490. "data.LanguageId": String(this.languageId),
  491. sourceCode,
  492. input,
  493. csrf_token: unsafeWindow.csrfToken,
  494. }),
  495. }).then(r => r.text());
  496. if (error) {
  497. throw new Error(error);
  498. }
  499. await sleep(100);
  500. for (;;) {
  501. const data = await fetch(AtCoderCustomTestResultAPI, {
  502. method: "GET",
  503. credentials: "include",
  504. }).then(r => r.json());
  505. if (!("Result" in data))
  506. continue;
  507. const result = data.Result;
  508. if ("Interval" in data) {
  509. await sleep(data.Interval);
  510. continue;
  511. }
  512. const status = (result.ExitCode == 0) ? "OK" : (result.TimeConsumption == -1) ? "CE" : "RE";
  513. if (status == "CE" && "runGroupId" in options) {
  514. ce_groups.add(options.runGroupId);
  515. }
  516. return {
  517. status,
  518. exitCode: result.ExitCode,
  519. execTime: result.TimeConsumption,
  520. memory: result.MemoryConsumption,
  521. input,
  522. output: data.Stdout,
  523. error: data.Stderr,
  524. };
  525. }
  526. }
  527. }
  528.  
  529. class PaizaIORunner extends CodeRunner {
  530. name;
  531. constructor(name, label) {
  532. super(label, "PaizaIO");
  533. this.name = name;
  534. }
  535. async run(sourceCode, input, options = {}) {
  536. let id, status, error;
  537. try {
  538. const res = await fetch("https://api.paiza.io/runners/create?" + buildParams({
  539. source_code: sourceCode,
  540. language: this.name,
  541. input,
  542. longpoll: "true",
  543. longpoll_timeout: "10",
  544. api_key: "guest",
  545. }), {
  546. method: "POST",
  547. mode: "cors",
  548. }).then(r => r.json());
  549. id = res.id;
  550. status = res.status;
  551. error = res.error;
  552. }
  553. catch (error) {
  554. return {
  555. status: "IE",
  556. input,
  557. error: String(error),
  558. };
  559. }
  560. while (status == "running") {
  561. const res = await fetch("https://api.paiza.io/runners/get_status?" + buildParams({
  562. id,
  563. api_key: "guest",
  564. }), {
  565. mode: "cors",
  566. }).then(res => res.json());
  567. status = res.status;
  568. error = res.error;
  569. }
  570. const res = await fetch("https://api.paiza.io/runners/get_details?" + buildParams({
  571. id,
  572. api_key: "guest",
  573. }), {
  574. mode: "cors",
  575. }).then(r => r.json());
  576. const result = {
  577. status: "OK",
  578. exitCode: String(res.exit_code),
  579. execTime: +res.time * 1e3,
  580. memory: +res.memory * 1e-3,
  581. input,
  582. };
  583. if (res.build_result == "failure") {
  584. result.status = "CE";
  585. result.exitCode = res.build_exit_code;
  586. result.output = res.build_stdout;
  587. result.error = res.build_stderr;
  588. }
  589. else {
  590. result.status = (res.result == "timeout") ? "TLE" : (res.result == "failure") ? "RE" : "OK";
  591. result.exitCode = res.exit_code;
  592. result.output = res.stdout;
  593. result.error = res.stderr;
  594. }
  595. return result;
  596. }
  597. }
  598.  
  599. async function loadPyodide() {
  600. const script = await fetch("https://cdn.jsdelivr.net/pyodide/v0.24.0/full/pyodide.js").then((res) => res.text());
  601. unsafeWindow["Function"](script)();
  602. const pyodide = await unsafeWindow["loadPyodide"]({
  603. indexURL: "https://cdn.jsdelivr.net/pyodide/v0.24.0/full/",
  604. });
  605. await pyodide.runPythonAsync(`
  606. import contextlib, io, platform
  607. class __redirect_stdin(contextlib._RedirectStream):
  608. _stream = "stdin"
  609. `);
  610. return pyodide;
  611. }
  612. let _pyodide = Promise.reject("Pyodide is not yet loaded");
  613. let _serial = Promise.resolve();
  614. const pyodideRunner = new CustomRunner("Pyodide", (sourceCode, input, options = {}) => new Promise((resolve, reject) => {
  615. _serial = _serial.finally(async () => {
  616. const pyodide = await (_pyodide = _pyodide.catch(loadPyodide));
  617. const code = `
  618. def __run():
  619. global __stdout, __stderr, __stdin, __code
  620. with __redirect_stdin(io.StringIO(__stdin)):
  621. with contextlib.redirect_stdout(io.StringIO()) as __stdout:
  622. with contextlib.redirect_stderr(io.StringIO()) as __stderr:
  623. try:
  624. pass
  625. ` +
  626. sourceCode
  627. .split("\n")
  628. .map((line) => " " + line)
  629. .join("\n") +
  630. `
  631. except SystemExit as e:
  632. __code = e.code
  633. `;
  634. let status = "OK";
  635. let exitCode = "0";
  636. let stdout = "";
  637. let stderr = "";
  638. let startTime = -Infinity;
  639. let endTime = Infinity;
  640. pyodide.globals.set("__stdin", input);
  641. try {
  642. pyodide.globals.set("__code", null);
  643. await pyodide.loadPackagesFromImports(code);
  644. await pyodide.runPythonAsync(code);
  645. startTime = Date.now();
  646. pyodide.runPython("__run()");
  647. endTime = Date.now();
  648. stdout = pyodide.globals.get("__stdout").getvalue();
  649. stderr = pyodide.globals.get("__stderr").getvalue();
  650. const __code = pyodide.globals.get("__code");
  651. if (typeof __code == "number") {
  652. exitCode = String(__code);
  653. if (__code != 0)
  654. status = "RE";
  655. }
  656. }
  657. catch (error) {
  658. status = "RE";
  659. exitCode = "-1";
  660. stderr += error.toString();
  661. }
  662. resolve({
  663. status,
  664. exitCode,
  665. execTime: endTime - startTime,
  666. input,
  667. output: stdout,
  668. error: stderr,
  669. });
  670. });
  671. }));
  672.  
  673. function pairs(list) {
  674. const pairs = [];
  675. const len = list.length >> 1;
  676. for (let i = 0; i < len; i++)
  677. pairs.push([list[i * 2], list[i * 2 + 1]]);
  678. return pairs;
  679. }
  680. async function init$5() {
  681. if (location.host != "atcoder.jp")
  682. throw "Not AtCoder";
  683. const doc = unsafeWindow.document;
  684. // "言語名 その他の説明..." となっている
  685. // 注意:
  686. // * 言語名にはスペースが入ってはいけない(スペース以降は説明とみなされる)
  687. // * Python2 の言語名は「Python」、 Python3 の言語名は「Python3」
  688. const langMap = {
  689. 4001: "C GCC 9.2.1",
  690. 4002: "C Clang 10.0.0",
  691. 4003: "C++ GCC 9.2.1",
  692. 4004: "C++ Clang 10.0.0",
  693. 4005: "Java OpenJDK 11.0.6",
  694. 4006: "Python3 CPython 3.8.2",
  695. 4007: "Bash 5.0.11",
  696. 4008: "bc 1.07.1",
  697. 4009: "Awk GNU Awk 4.1.4",
  698. 4010: "C# .NET Core 3.1.201",
  699. 4011: "C# Mono-mcs 6.8.0.105",
  700. 4012: "C# Mono-csc 3.5.0",
  701. 4013: "Clojure 1.10.1.536",
  702. 4014: "Crystal 0.33.0",
  703. 4015: "D DMD 2.091.0",
  704. 4016: "D GDC 9.2.1",
  705. 4017: "D LDC 1.20.1",
  706. 4018: "Dart 2.7.2",
  707. 4019: "dc 1.4.1",
  708. 4020: "Erlang 22.3",
  709. 4021: "Elixir 1.10.2",
  710. 4022: "F# .NET Core 3.1.201",
  711. 4023: "F# Mono 10.2.3",
  712. 4024: "Forth gforth 0.7.3",
  713. 4025: "Fortran GNU Fortran 9.2.1",
  714. 4026: "Go 1.14.1",
  715. 4027: "Haskell GHC 8.8.3",
  716. 4028: "Haxe 4.0.3",
  717. 4029: "Haxe 4.0.3",
  718. 4030: "JavaScript Node.js 12.16.1",
  719. 4031: "Julia 1.4.0",
  720. 4032: "Kotlin 1.3.71",
  721. 4033: "Lua Lua 5.3.5",
  722. 4034: "Lua LuaJIT 2.1.0",
  723. 4035: "Dash 0.5.8",
  724. 4036: "Nim 1.0.6",
  725. 4037: "Objective-C Clang 10.0.0",
  726. 4038: "Lisp SBCL 2.0.3",
  727. 4039: "OCaml 4.10.0",
  728. 4040: "Octave 5.2.0",
  729. 4041: "Pascal FPC 3.0.4",
  730. 4042: "Perl 5.26.1",
  731. 4043: "Raku Rakudo 2020.02.1",
  732. 4044: "PHP 7.4.4",
  733. 4045: "Prolog SWI-Prolog 8.0.3",
  734. 4046: "Python PyPy2 7.3.0",
  735. 4047: "Python3 PyPy3 7.3.0",
  736. 4048: "Racket 7.6",
  737. 4049: "Ruby 2.7.1",
  738. 4050: "Rust 1.42.0",
  739. 4051: "Scala 2.13.1",
  740. 4052: "Java OpenJDK 1.8.0",
  741. 4053: "Scheme Gauche 0.9.9",
  742. 4054: "ML MLton 20130715",
  743. 4055: "Swift 5.2.1",
  744. 4056: "Text cat 8.28",
  745. 4057: "TypeScript 3.8",
  746. 4058: "Basic .NET Core 3.1.101",
  747. 4059: "Zsh 5.4.2",
  748. 4060: "COBOL Fixed OpenCOBOL 1.1.0",
  749. 4061: "COBOL Free OpenCOBOL 1.1.0",
  750. 4062: "Brainfuck bf 20041219",
  751. 4063: "Ada Ada2012 GNAT 9.2.1",
  752. 4064: "Unlambda 2.0.0",
  753. 4065: "Cython 0.29.16",
  754. 4066: "Sed 4.4",
  755. 4067: "Vim 8.2.0460",
  756. // newjudge-2308
  757. 5001: "C++ 20 gcc 12.2",
  758. 5002: "Go 1.20.6",
  759. 5003: "C# 11.0 .NET 7.0.7",
  760. 5004: "Kotlin 1.8.20",
  761. 5005: "Java OpenJDK 17",
  762. 5006: "Nim 1.6.14",
  763. 5007: "V 0.4",
  764. 5008: "Zig 0.10.1",
  765. 5009: "JavaScript Node.js 18.16.1",
  766. 5010: "JavaScript Deno 1.35.1",
  767. 5011: "R GNU R 4.2.1",
  768. 5012: "D DMD 2.104.0",
  769. 5013: "D LDC 1.32.2",
  770. 5014: "Swift 5.8.1",
  771. 5015: "Dart 3.0.5",
  772. 5016: "PHP 8.2.8",
  773. 5017: "C GCC 12.2.0",
  774. 5018: "Ruby 3.2.2",
  775. 5019: "Crystal 1.9.1",
  776. 5020: "Brainfuck bf 20041219",
  777. 5021: "F# 7.0 .NET 7.0.7",
  778. 5022: "Julia 1.9.2",
  779. 5023: "Bash 5.2.2",
  780. 5024: "Text cat 8.32",
  781. 5025: "Haskell GHC 9.4.5",
  782. 5026: "Fortran GNU Fortran 12.2",
  783. 5027: "Lua LuaJIT 2.1.0-beta3",
  784. 5028: "C++ 23 gcc 12.2",
  785. 5029: "CommonLisp SBCL 2.3.6",
  786. 5030: "COBOL Free GnuCOBOL 3.1.2",
  787. 5031: "C++ 23 Clang 16.0.5",
  788. 5032: "Zsh Zsh 5.9",
  789. 5033: "SageMath SageMath 9.5",
  790. 5034: "Sed GNU sed 4.8",
  791. 5035: "bc bc 1.07.1",
  792. 5036: "dc dc 1.07.1",
  793. 5037: "Perl perl 5.34",
  794. 5038: "AWK GNU Awk 5.0.1",
  795. 5039: "なでしこ cnako3 3.4.20",
  796. 5040: "Assembly x64 NASM 2.15.05",
  797. 5041: "Pascal fpc 3.2.2",
  798. 5042: "C# 11.0 AOT .NET 7.0.7",
  799. 5043: "Lua Lua 5.4.6",
  800. 5044: "Prolog SWI-Prolog 9.0.4",
  801. 5045: "PowerShell PowerShell 7.3.1",
  802. 5046: "Scheme Gauche 0.9.12",
  803. 5047: "Scala 3.3.0 Scala Native 0.4.14",
  804. 5048: "Visual Basic 16.9 .NET 7.0.7",
  805. 5049: "Forth gforth 0.7.3",
  806. 5050: "Clojure babashka 1.3.181",
  807. 5051: "Erlang Erlang 26.0.2",
  808. 5052: "TypeScript 5.1 Deno 1.35.1",
  809. 5053: "C++ 17 gcc 12.2",
  810. 5054: "Rust rustc 1.70.0",
  811. 5055: "Python3 CPython 3.11.4",
  812. 5056: "Scala Dotty 3.3.0",
  813. 5057: "Koka koka 2.4.0",
  814. 5058: "TypeScript 5.1 Node.js 18.16.1",
  815. 5059: "OCaml ocamlopt 5.0.0",
  816. 5060: "Raku Rakudo 2023.06",
  817. 5061: "Vim vim 9.0.0242",
  818. 5062: "Emacs Lisp Native Compile GNU Emacs 28.2",
  819. 5063: "Python3 Mambaforge / CPython 3.10.10",
  820. 5064: "Clojure clojure 1.11.1",
  821. 5065: "プロデル mono版プロデル 1.9.1182",
  822. 5066: "ECLiPSe ECLiPSe 7.1_13",
  823. 5067: "Nibbles literate form nibbles 1.01",
  824. 5068: "Ada GNAT 12.2",
  825. 5069: "jq jq 1.6",
  826. 5070: "Cyber Cyber v0.2-Latest",
  827. 5071: "Carp Carp 0.5.5",
  828. 5072: "C++ 17 Clang 16.0.5",
  829. 5073: "C++ 20 Clang 16.0.5",
  830. 5074: "LLVM IR Clang 16.0.5",
  831. 5075: "Emacs Lisp Byte Compile GNU Emacs 28.2",
  832. 5076: "Factor Factor 0.98",
  833. 5077: "D GDC 12.2",
  834. 5078: "Python3 PyPy 3.10-v7.3.12",
  835. 5079: "Whitespace whitespacers 1.0.0",
  836. 5080: "><> fishr 0.1.0",
  837. 5081: "ReasonML reason 3.9.0",
  838. 5082: "Python Cython 0.29.34",
  839. 5083: "Octave GNU Octave 8.2.0",
  840. 5084: "Haxe JVM Haxe 4.3.1",
  841. 5085: "Elixir Elixir 1.15.2",
  842. 5086: "Mercury Mercury 22.01.6",
  843. 5087: "Seed7 Seed7 3.2.1",
  844. 5088: "Emacs Lisp No Compile GNU Emacs 28.2",
  845. 5089: "Unison Unison M5b",
  846. 5090: "COBOL GnuCOBOLFixed 3.1.2",
  847. };
  848. const languageId = new ObservableValue(unsafeWindow.$("#select-lang select.current").val());
  849. unsafeWindow.$("#select-lang select").change(() => {
  850. languageId.value = unsafeWindow.$("#select-lang select.current").val();
  851. });
  852. const language = languageId.map(lang => langMap[lang]);
  853. const isTestCasesHere = /^\/contests\/[^\/]+\/tasks\//.test(location.pathname);
  854. const taskSelector = doc.querySelector("#select-task");
  855. function getTaskURI() {
  856. if (taskSelector)
  857. return `${location.origin}/contests/${unsafeWindow.contestScreenName}/tasks/${taskSelector.value}`;
  858. return `${location.origin}${location.pathname}`;
  859. }
  860. const testcasesCache = {};
  861. if (taskSelector) {
  862. const doFetchTestCases = async () => {
  863. console.log(`Fetching test cases...: ${getTaskURI()}`);
  864. const taskURI = getTaskURI();
  865. const load = !(taskURI in testcasesCache) || testcasesCache[taskURI].state == "error";
  866. if (!load)
  867. return;
  868. try {
  869. testcasesCache[taskURI] = { state: "loading" };
  870. const testcases = await fetchTestCases(taskURI);
  871. testcasesCache[taskURI] = { testcases, state: "loaded" };
  872. }
  873. catch (e) {
  874. testcasesCache[taskURI] = { state: "error" };
  875. }
  876. };
  877. unsafeWindow.$("#select-task").change(doFetchTestCases);
  878. doFetchTestCases();
  879. }
  880. async function fetchTestCases(taskUrl) {
  881. const html = await fetch(taskUrl).then(res => res.text());
  882. const taskDoc = new DOMParser().parseFromString(html, "text/html");
  883. return getTestCases(taskDoc);
  884. }
  885. function getTestCases(doc) {
  886. const selectors = [
  887. ["#task-statement p+pre.literal-block", ".section"],
  888. ["#task-statement pre.source-code-for-copy", ".part"],
  889. ["#task-statement .lang>*:nth-child(1) .div-btn-copy+pre", ".part"],
  890. ["#task-statement .div-btn-copy+pre", ".part"],
  891. ["#task-statement>.part pre.linenums", ".part"],
  892. ["#task-statement>.part section>pre", ".part"],
  893. ["#task-statement>.part:not(.io-style)>h3+section>pre", ".part"],
  894. ["#task-statement pre", ".part"],
  895. ];
  896. for (const [selector, closestSelector] of selectors) {
  897. let e = [...doc.querySelectorAll(selector)];
  898. e = e.filter(e => {
  899. if (e.closest(".io-style"))
  900. return false; // practice2
  901. if (e.querySelector("var"))
  902. return false;
  903. return true;
  904. });
  905. if (e.length == 0)
  906. continue;
  907. return pairs(e).map(([input, output], index) => {
  908. const container = input.closest(closestSelector) || input.parentElement;
  909. return {
  910. selector,
  911. title: `Sample ${index + 1}`,
  912. input: input.textContent,
  913. output: output.textContent,
  914. anchor: container.querySelector(".btn-copy") || container.querySelector("h1,h2,h3,h4,h5,h6"),
  915. };
  916. });
  917. }
  918. { // maximum_cup_2018_d
  919. let e = [...doc.querySelectorAll("#task-statement .div-btn-copy+pre")];
  920. e = e.filter(f => !f.childElementCount);
  921. if (e.length) {
  922. return pairs(e).map(([input, output], index) => ({
  923. selector: "#task-statement .div-btn-copy+pre",
  924. title: `Sample ${index + 1}`,
  925. input: input.textContent,
  926. output: output.textContent,
  927. anchor: (input.closest(".part") || input.parentElement).querySelector(".btn-copy"),
  928. }));
  929. }
  930. }
  931. return [];
  932. }
  933. const atcoder = {
  934. name: "AtCoder",
  935. language,
  936. langMap,
  937. get sourceCode() {
  938. const $ = unsafeWindow.document.querySelector.bind(unsafeWindow.document);
  939. if (typeof unsafeWindow["ace"] != "undefined") {
  940. if (!$(".btn-toggle-editor").classList.contains("active")) {
  941. return unsafeWindow["ace"].edit($("#editor")).getValue();
  942. }
  943. else {
  944. return $("#plain-textarea").value;
  945. }
  946. }
  947. else {
  948. return unsafeWindow.getSourceCode();
  949. }
  950. },
  951. set sourceCode(sourceCode) {
  952. const $ = unsafeWindow.document.querySelector.bind(unsafeWindow.document);
  953. if (typeof unsafeWindow["ace"] != "undefined") {
  954. unsafeWindow["ace"].edit($("#editor")).setValue(sourceCode);
  955. $("#plain-textarea").value = sourceCode;
  956. }
  957. else {
  958. doc.querySelector(".plain-textarea").value = sourceCode;
  959. unsafeWindow.$(".editor").data("editor").doc.setValue(sourceCode);
  960. }
  961. },
  962. submit() {
  963. doc.querySelector("#submit").click();
  964. },
  965. get testButtonContainer() {
  966. return doc.querySelector("#submit").parentElement;
  967. },
  968. get sideButtonContainer() {
  969. return doc.querySelector(".editor-buttons");
  970. },
  971. get bottomMenuContainer() {
  972. return doc.getElementById("main-div");
  973. },
  974. get resultListContainer() {
  975. return doc.querySelector(".form-code-submit");
  976. },
  977. get testCases() {
  978. const taskURI = getTaskURI();
  979. if (taskURI in testcasesCache && testcasesCache[taskURI].state == "loaded")
  980. return testcasesCache[taskURI].testcases;
  981. if (isTestCasesHere) {
  982. const testcases = getTestCases(doc);
  983. testcasesCache[taskURI] = { testcases, state: "loaded" };
  984. return testcases;
  985. }
  986. else {
  987. console.error("AtCoder Easy Test v2: Test cases are still not loaded");
  988. return [];
  989. }
  990. },
  991. get jQuery() {
  992. return unsafeWindow["jQuery"];
  993. },
  994. get taskURI() {
  995. return getTaskURI();
  996. },
  997. };
  998. return atcoder;
  999. }
  1000.  
  1001. async function init$4() {
  1002. if (location.host != "yukicoder.me")
  1003. throw "Not yukicoder";
  1004. const $ = unsafeWindow.$;
  1005. const doc = unsafeWindow.document;
  1006. const editor = unsafeWindow.ace.edit("rich_source");
  1007. const eSourceObject = $("#source");
  1008. const eLang = $("#lang");
  1009. const eSamples = $(".sample");
  1010. const langMap = {
  1011. "cpp14": "C++ C++14 GCC 11.1.0 + Boost 1.77.0",
  1012. "cpp17": "C++ C++17 GCC 11.1.0 + Boost 1.77.0",
  1013. "cpp-clang": "C++ C++17 Clang 10.0.0 + Boost 1.76.0",
  1014. "cpp23": "C++ C++11 GCC 8.4.1",
  1015. "c11": "C++ C++11 GCC 11.1.0",
  1016. "c": "C C90 GCC 8.4.1",
  1017. "java8": "Java Java16 OpenJDK 16.0.1",
  1018. "csharp": "C# CSC 3.9.0",
  1019. "csharp_mono": "C# Mono 6.12.0.147",
  1020. "csharp_dotnet": "C# .NET 5.0",
  1021. "perl": "Perl 5.26.3",
  1022. "raku": "Raku Rakudo v2021-07-2-g74d7ff771",
  1023. "php": "PHP 7.2.24",
  1024. "php7": "PHP 8.0.8",
  1025. "python3": "Python3 3.9.6 + numpy 1.14.5 + scipy 1.1.0",
  1026. "pypy2": "Python PyPy2 7.3.5",
  1027. "pypy3": "Python3 PyPy3 7.3.5",
  1028. "ruby": "Ruby 3.0.2p107",
  1029. "d": "D DMD 2.097.1",
  1030. "go": "Go 1.16.6",
  1031. "haskell": "Haskell 8.10.5",
  1032. "scala": "Scala 2.13.6",
  1033. "nim": "Nim 1.4.8",
  1034. "rust": "Rust 1.53.0",
  1035. "kotlin": "Kotlin 1.5.21",
  1036. "scheme": "Scheme Gauche 0.9.10",
  1037. "crystal": "Crystal 1.1.1",
  1038. "swift": "Swift 5.4.2",
  1039. "ocaml": "OCaml 4.12.0",
  1040. "clojure": "Clojure 1.10.2.790",
  1041. "fsharp": "F# 5.0",
  1042. "elixir": "Elixir 1.7.4",
  1043. "lua": "Lua LuaJIT 2.0.5",
  1044. "fortran": "Fortran gFortran 8.4.1",
  1045. "node": "JavaScript Node.js 15.5.0",
  1046. "typescript": "TypeScript 4.3.5",
  1047. "lisp": "Lisp Common Lisp sbcl 2.1.6",
  1048. "sml": "ML Standard ML MLton 20180207-6",
  1049. "kuin": "Kuin KuinC++ v.2021.7.17",
  1050. "vim": "Vim v8.2",
  1051. "sh": "Bash 4.4.19",
  1052. "nasm": "Assembler nasm 2.13.03",
  1053. "clay": "cLay 20210917-1",
  1054. "bf": "Brainfuck BFI 1.1",
  1055. "Whitespace": "Whitespace 0.3",
  1056. "text": "Text cat 8.3",
  1057. };
  1058. // place anchor elements
  1059. for (const btnCopyInput of doc.querySelectorAll(".copy-sample-input")) {
  1060. btnCopyInput.parentElement.insertBefore(newElement("span", { className: "atcoder-easy-test-anchor" }), btnCopyInput);
  1061. }
  1062. const language = new ObservableValue(langMap[eLang.val()]);
  1063. eLang.on("change", () => {
  1064. language.value = langMap[eLang.val()];
  1065. });
  1066. return {
  1067. name: "yukicoder",
  1068. language,
  1069. get sourceCode() {
  1070. if (eSourceObject.is(":visible"))
  1071. return eSourceObject.val();
  1072. return editor.getSession().getValue();
  1073. },
  1074. set sourceCode(sourceCode) {
  1075. eSourceObject.val(sourceCode);
  1076. editor.getSession().setValue(sourceCode);
  1077. },
  1078. submit() {
  1079. doc.querySelector(`#submit_form input[type="submit"]`).click();
  1080. },
  1081. get testButtonContainer() {
  1082. return doc.querySelector("#submit_form");
  1083. },
  1084. get sideButtonContainer() {
  1085. return doc.querySelector("#toggle_source_editor").parentElement;
  1086. },
  1087. get bottomMenuContainer() {
  1088. return doc.body;
  1089. },
  1090. get resultListContainer() {
  1091. return doc.querySelector("#content");
  1092. },
  1093. get testCases() {
  1094. const testCases = [];
  1095. let sampleId = 1;
  1096. for (let i = 0; i < eSamples.length; i++) {
  1097. const eSample = eSamples.eq(i);
  1098. const [eInput, eOutput] = eSample.find("pre");
  1099. testCases.push({
  1100. title: `Sample ${sampleId++}`,
  1101. input: eInput.textContent,
  1102. output: eOutput.textContent,
  1103. anchor: eSample.find(".atcoder-easy-test-anchor")[0],
  1104. });
  1105. }
  1106. return testCases;
  1107. },
  1108. get jQuery() {
  1109. return $;
  1110. },
  1111. get taskURI() {
  1112. return location.href;
  1113. },
  1114. };
  1115. }
  1116.  
  1117. class Editor {
  1118. _element;
  1119. constructor(lang) {
  1120. this._element = document.createElement("textarea");
  1121. this._element.style.fontFamily = "monospace";
  1122. this._element.style.width = "100%";
  1123. this._element.style.minHeight = "5em";
  1124. }
  1125. get element() {
  1126. return this._element;
  1127. }
  1128. get sourceCode() {
  1129. return this._element.value;
  1130. }
  1131. set sourceCode(sourceCode) {
  1132. this._element.value = sourceCode;
  1133. }
  1134. setLanguage(lang) {
  1135. }
  1136. }
  1137.  
  1138. var langMap = {
  1139. 3: "Delphi 7",
  1140. 4: "Pascal Free Pascal 3.0.2",
  1141. 6: "PHP 7.2.13",
  1142. 7: "Python 2.7.18",
  1143. 9: "C# Mono 6.8",
  1144. 12: "Haskell GHC 8.10.1",
  1145. 13: "Perl 5.20.1",
  1146. 19: "OCaml 4.02.1",
  1147. 20: "Scala 2.12.8",
  1148. 28: "D DMD32 v2.091.0",
  1149. 31: "Python3 3.8.10",
  1150. 32: "Go 1.15.6",
  1151. 34: "JavaScript V8 4.8.0",
  1152. 36: "Java 1.8.0_241",
  1153. 40: "Python PyPy2 2.7 (7.3.0)",
  1154. 41: "Python3 PyPy3 3.7 (7.3.0)",
  1155. 43: "C C11 GCC 5.1.0",
  1156. 48: "Kotlin 1.5.31",
  1157. 49: "Rust 1.49.0",
  1158. 50: "C++ C++14 G++ 6.4.0",
  1159. 51: "Pascal PascalABC.NET 3.4.1",
  1160. 52: "C++ C++17 Clang++",
  1161. 54: "C++ C++17 G++ 7.3.0",
  1162. 55: "JavaScript Node.js 12.6.3",
  1163. 59: "C++ Microsoft Visual C++ 2017",
  1164. 60: "Java 11.0.6",
  1165. 61: "C++ C++17 9.2.0 (64 bit, msys 2)",
  1166. 65: "C# 8, .NET Core 3.1",
  1167. 67: "Ruby 3.0.0",
  1168. 70: "Python3 PyPy 3.7 (7.3.5, 64bit)",
  1169. 72: "Kotlin 1.5.31",
  1170. 73: "C++ GNU G++ 11.2.0 (64 bit, winlibs)",
  1171. 75: "Rust 1.75.0 (2021)",
  1172. 79: "C# 10, .NET SDK 6.0",
  1173. 83: "Kotlin 1.7.20",
  1174. 87: "Java 21 64bit",
  1175. 88: "Kotlin 1.9.21",
  1176. 89: "C++ GNU G++20 13.2 (64 bit, winlibs)",
  1177. 91: "GNU G++23 14.2 (64 bit, msys2)",
  1178. };
  1179.  
  1180. config.registerFlag("site.codeforces.showEditor", true, "Show Editor in Codeforces Problem Page");
  1181. async function init$3() {
  1182. if (location.host != "codeforces.com")
  1183. throw "not Codeforces";
  1184. //TODO: m1.codeforces.com, m2.codeforces.com, m3.codeforces.com に対応する
  1185. const doc = unsafeWindow.document;
  1186. const eLang = doc.querySelector("select[name='programTypeId']");
  1187. doc.head.appendChild(newElement("link", {
  1188. rel: "stylesheet",
  1189. href: "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css",
  1190. }));
  1191. doc.head.appendChild(newElement("style", {
  1192. textContent: `
  1193. .atcoder-easy-test-btn-run-case {
  1194. float: right;
  1195. line-height: 1.1rem;
  1196. }
  1197. `,
  1198. }));
  1199. const eButtons = newElement("span");
  1200. doc.querySelector(".submitForm").appendChild(eButtons);
  1201. await loadScript("https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js");
  1202. const jQuery = unsafeWindow["jQuery"].noConflict();
  1203. unsafeWindow["jQuery"] = unsafeWindow["$"];
  1204. unsafeWindow["jQuery11"] = jQuery;
  1205. await loadScript("https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js", null, { jQuery, $: jQuery });
  1206. const language = new ObservableValue(langMap[eLang.value]);
  1207. eLang.addEventListener("change", () => {
  1208. language.value = langMap[eLang.value];
  1209. });
  1210. let _sourceCode = "";
  1211. const eFile = doc.querySelector(".submitForm").elements["sourceFile"];
  1212. eFile.addEventListener("change", async () => {
  1213. if (eFile.files[0]) {
  1214. _sourceCode = await eFile.files[0].text();
  1215. if (editor)
  1216. editor.sourceCode = _sourceCode;
  1217. }
  1218. });
  1219. let editor = null;
  1220. let waitCfFastSubmitCount = 0;
  1221. const waitCfFastSubmit = setInterval(() => {
  1222. if (document.getElementById("editor")) {
  1223. // cf-fast-submit
  1224. if (editor && editor.element)
  1225. editor.element.style.display = "none";
  1226. // 言語セレクトを同期させる
  1227. const eLang2 = doc.querySelector(".submit-form select[name='programTypeId']");
  1228. if (eLang2) {
  1229. eLang.addEventListener("change", () => {
  1230. eLang2.value = eLang.value;
  1231. });
  1232. eLang2.addEventListener("change", () => {
  1233. eLang.value = eLang2.value;
  1234. language.value = langMap[eLang.value];
  1235. });
  1236. }
  1237. // TODO: 選択されたファイルをどうかする
  1238. // エディタを使う
  1239. const aceEditor = unsafeWindow["ace"].edit("editor");
  1240. editor = {
  1241. get sourceCode() {
  1242. return aceEditor.getValue();
  1243. },
  1244. set sourceCode(sourceCode) {
  1245. aceEditor.setValue(sourceCode);
  1246. },
  1247. setLanguage(lang) { },
  1248. };
  1249. // ボタンを追加する
  1250. const buttonContainer = doc.querySelector(".submit-form .submit").parentElement;
  1251. buttonContainer.appendChild(newElement("button", {
  1252. type: "button",
  1253. className: "btn btn-info",
  1254. textContent: "Test & Submit",
  1255. onclick: () => events.trig("testAndSubmit"),
  1256. }));
  1257. buttonContainer.appendChild(newElement("button", {
  1258. type: "button",
  1259. className: "btn btn-default",
  1260. textContent: "Test All Samples",
  1261. onclick: () => events.trig("testAllSamples"),
  1262. }));
  1263. clearInterval(waitCfFastSubmit);
  1264. }
  1265. else {
  1266. waitCfFastSubmitCount++;
  1267. if (waitCfFastSubmitCount >= 100)
  1268. clearInterval(waitCfFastSubmit);
  1269. }
  1270. }, 100);
  1271. if (config.get("site.codeforces.showEditor", true)) {
  1272. editor = new Editor(langMap[eLang.value].split(" ")[0]);
  1273. doc.getElementById("pageContent").appendChild(editor.element);
  1274. language.addListener(lang => {
  1275. editor.setLanguage(lang);
  1276. });
  1277. }
  1278. return {
  1279. name: "Codeforces",
  1280. language,
  1281. get sourceCode() {
  1282. if (editor)
  1283. return editor.sourceCode;
  1284. return _sourceCode;
  1285. },
  1286. set sourceCode(sourceCode) {
  1287. const container = new DataTransfer();
  1288. container.items.add(new File([sourceCode], "prog.txt", { type: "text/plain" }));
  1289. const eFile = doc.querySelector(".submitForm").elements["sourceFile"];
  1290. eFile.files = container.files;
  1291. _sourceCode = sourceCode;
  1292. if (editor)
  1293. editor.sourceCode = sourceCode;
  1294. },
  1295. submit() {
  1296. if (editor)
  1297. _sourceCode = editor.sourceCode;
  1298. this.sourceCode = _sourceCode;
  1299. doc.querySelector(`.submitForm .submit`).click();
  1300. },
  1301. get testButtonContainer() {
  1302. return eButtons;
  1303. },
  1304. get sideButtonContainer() {
  1305. return eButtons;
  1306. },
  1307. get bottomMenuContainer() {
  1308. return doc.body;
  1309. },
  1310. get resultListContainer() {
  1311. return doc.querySelector("#pageContent");
  1312. },
  1313. get testCases() {
  1314. const testcases = [];
  1315. let num = 1;
  1316. for (const eSampleTest of doc.querySelectorAll(".sample-test")) {
  1317. const inputs = eSampleTest.querySelectorAll(".input pre");
  1318. const outputs = eSampleTest.querySelectorAll(".output pre");
  1319. const anchors = eSampleTest.querySelectorAll(".input .title .input-output-copier");
  1320. const count = Math.min(inputs.length, outputs.length, anchors.length);
  1321. for (let i = 0; i < count; i++) {
  1322. let inputText = "";
  1323. for (const node of inputs[i].childNodes) {
  1324. inputText += node.textContent;
  1325. if (node.nodeType == node.ELEMENT_NODE && (node.tagName == "DIV" || node.tagName == "BR")) {
  1326. inputText += "\n";
  1327. }
  1328. }
  1329. testcases.push({
  1330. title: `Sample ${num++}`,
  1331. input: inputText,
  1332. output: outputs[i].textContent,
  1333. anchor: anchors[i],
  1334. });
  1335. }
  1336. }
  1337. return testcases;
  1338. },
  1339. get jQuery() {
  1340. return jQuery;
  1341. },
  1342. get taskURI() {
  1343. return location.href;
  1344. },
  1345. };
  1346. }
  1347.  
  1348. config.registerFlag("site.codeforcesMobile.showEditor", true, "Show Editor in Mobile Codeforces (m[1-3].codeforces.com) Problem Page");
  1349. async function init$2() {
  1350. if (!/^m[1-3]\.codeforces\.com$/.test(location.host))
  1351. throw "not Codeforces Mobile";
  1352. const url = /\/contest\/(\d+)\/problem\/([^/]+)/.exec(location.pathname);
  1353. const contestId = url[1];
  1354. const problemId = url[2];
  1355. const doc = unsafeWindow.document;
  1356. const main = doc.querySelector("main");
  1357. doc.head.appendChild(newElement("link", {
  1358. rel: "stylesheet",
  1359. href: "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css",
  1360. }));
  1361. await loadScript("https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js");
  1362. const language = new ObservableValue("");
  1363. let submit = () => { };
  1364. let getSourceCode = () => "";
  1365. let setSourceCode = (_) => { };
  1366. // make Editor
  1367. if (config.get("site.codeforcesMobile.showEditor", true)) {
  1368. const frame = newElement("iframe", {
  1369. src: `/contest/${contestId}/submit`,
  1370. style: {
  1371. display: "none",
  1372. },
  1373. });
  1374. doc.body.appendChild(frame);
  1375. await new Promise(done => frame.onload = done);
  1376. const fdoc = frame.contentDocument;
  1377. const form = fdoc.querySelector("._SubmitPage_submitForm");
  1378. form.elements["problemIndex"].value = problemId;
  1379. form.elements["problemIndex"].readonly = true;
  1380. form.elements["programTypeId"].addEventListener("change", function () {
  1381. language.value = langMap[this.value];
  1382. });
  1383. for (const row of form.children) {
  1384. if (row.tagName != "DIV")
  1385. continue;
  1386. row.classList.add("form-group");
  1387. const control = row.querySelector("*[name]");
  1388. if (control)
  1389. control.classList.add("form-control");
  1390. }
  1391. form.parentElement.removeChild(form);
  1392. main.appendChild(form);
  1393. submit = () => form.submit();
  1394. getSourceCode = () => form.elements["source"].value;
  1395. setSourceCode = sourceCode => {
  1396. form.elements["source"].value = sourceCode;
  1397. };
  1398. }
  1399. return {
  1400. name: "Codeforces",
  1401. language,
  1402. get sourceCode() {
  1403. return getSourceCode();
  1404. },
  1405. set sourceCode(sourceCode) {
  1406. setSourceCode(sourceCode);
  1407. },
  1408. submit,
  1409. get testButtonContainer() {
  1410. return main;
  1411. },
  1412. get sideButtonContainer() {
  1413. return main;
  1414. },
  1415. get bottomMenuContainer() {
  1416. return doc.body;
  1417. },
  1418. get resultListContainer() {
  1419. return main;
  1420. },
  1421. get testCases() {
  1422. const testcases = [];
  1423. let index = 1;
  1424. for (const container of doc.querySelectorAll(".sample-test")) {
  1425. const input = container.querySelector(".input pre.content").textContent;
  1426. const output = container.querySelector(".output pre.content").textContent;
  1427. const anchor = container.querySelector(".input .title");
  1428. testcases.push({
  1429. input, output, anchor,
  1430. title: `Sample ${index++}`,
  1431. });
  1432. }
  1433. return testcases;
  1434. },
  1435. get jQuery() {
  1436. return unsafeWindow["jQuery"];
  1437. },
  1438. get taskURI() {
  1439. return location.href;
  1440. },
  1441. };
  1442. }
  1443.  
  1444. async function init$1() {
  1445. if (location.host != "greasyfork.org" && !location.href.match(/433152-atcoder-easy-test-v2/))
  1446. throw "Not about page";
  1447. const doc = unsafeWindow.document;
  1448. await loadScript("https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js");
  1449. const jQuery = unsafeWindow["jQuery"];
  1450. await loadScript("https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js", null, { jQuery, $: jQuery });
  1451. const e = newElement("div");
  1452. doc.getElementById("install-area").appendChild(newElement("button", {
  1453. type: "button",
  1454. textContent: "Open config",
  1455. onclick: () => settings.open(),
  1456. }));
  1457. return {
  1458. name: "About Page",
  1459. language: new ObservableValue(""),
  1460. get sourceCode() { return ""; },
  1461. set sourceCode(sourceCode) { },
  1462. submit() { },
  1463. get testButtonContainer() { return e; },
  1464. get sideButtonContainer() { return e; },
  1465. get bottomMenuContainer() { return e; },
  1466. get resultListContainer() { return e; },
  1467. get testCases() { return []; },
  1468. get jQuery() { return jQuery; },
  1469. get taskURI() { return ""; },
  1470. };
  1471. }
  1472.  
  1473. // 設定ページが開けなくなるのを避ける
  1474. const inits = [init$1()];
  1475. config.registerFlag("site.atcoder", true, "Use AtCoder Easy Test in AtCoder");
  1476. if (config.get("site.atcoder", true))
  1477. inits.push(init$5());
  1478. config.registerFlag("site.yukicoder", true, "Use AtCoder Easy Test in yukicoder");
  1479. if (config.get("site.yukicoder", true))
  1480. inits.push(init$4());
  1481. config.registerFlag("site.codeforces", true, "Use AtCoder Easy Test in Codeforces");
  1482. if (config.get("site.codeforces", true))
  1483. inits.push(init$3());
  1484. config.registerFlag("site.codeforcesMobile", true, "Use AtCoder Easy Test in Codeforces Mobile (m[1-3].codeforces.com)");
  1485. if (config.get("site.codeforcesMobile", true))
  1486. inits.push(init$2());
  1487. const site = Promise.any(inits);
  1488. site.catch(() => {
  1489. for (const promise of inits) {
  1490. promise.catch(console.error);
  1491. }
  1492. });
  1493.  
  1494. class WandboxRunner extends CodeRunner {
  1495. name;
  1496. options;
  1497. constructor(name, label, options = {}) {
  1498. super(label, "Wandbox");
  1499. this.name = name;
  1500. this.options = options;
  1501. }
  1502. getOptions(sourceCode, input) {
  1503. if (typeof this.options == "function")
  1504. return this.options(sourceCode, input);
  1505. return this.options;
  1506. }
  1507. run(sourceCode, input, options = {}) {
  1508. return this.request(Object.assign({
  1509. compiler: this.name,
  1510. code: sourceCode,
  1511. stdin: input,
  1512. }, Object.assign(options, this.getOptions(sourceCode, input))));
  1513. }
  1514. async request(body) {
  1515. const startTime = Date.now();
  1516. let res;
  1517. try {
  1518. res = await fetch("https://wandbox.org/api/compile.json", {
  1519. method: "POST",
  1520. mode: "cors",
  1521. headers: {
  1522. "Content-Type": "application/json",
  1523. },
  1524. body: JSON.stringify(body),
  1525. }).then(r => r.json());
  1526. }
  1527. catch (error) {
  1528. console.error(error);
  1529. return {
  1530. status: "IE",
  1531. input: body.stdin,
  1532. error: String(error),
  1533. };
  1534. }
  1535. const endTime = Date.now();
  1536. const result = {
  1537. status: "OK",
  1538. exitCode: String(res.status),
  1539. execTime: endTime - startTime,
  1540. input: body.stdin,
  1541. output: String(res.program_output || ""),
  1542. error: String(res.program_error || ""),
  1543. };
  1544. // 正常終了以外の場合
  1545. if (res.status != 0) {
  1546. if (res.signal) {
  1547. result.exitCode += ` (${res.signal})`;
  1548. }
  1549. result.output = String(res.compiler_output || "") + String(result.output || "");
  1550. result.error = String(res.compiler_error || "") + String(result.error || "");
  1551. if (res.compiler_output || res.compiler_error) {
  1552. result.status = "CE";
  1553. }
  1554. else {
  1555. result.status = "RE";
  1556. }
  1557. }
  1558. return result;
  1559. }
  1560. }
  1561.  
  1562. class WandboxCppRunner extends WandboxRunner {
  1563. async run(sourceCode, input, options = {}) {
  1564. // ACL を結合する
  1565. const ACLBase = "https://cdn.jsdelivr.net/gh/atcoder/ac-library/";
  1566. const files = new Map();
  1567. const includeHeader = async (source) => {
  1568. const pattern = /^#\s*include\s*[<"]atcoder\/([^>"]+)[>"]/gm;
  1569. const loaded = [];
  1570. let match;
  1571. while (match = pattern.exec(source)) {
  1572. const file = "atcoder/" + match[1];
  1573. if (files.has(file))
  1574. continue;
  1575. files.set(file, null);
  1576. loaded.push([file, fetch(ACLBase + file, { mode: "cors", cache: "force-cache", }).then(r => r.text())]);
  1577. }
  1578. const included = await Promise.all(loaded.map(async ([file, r]) => {
  1579. const source = await r;
  1580. files.set(file, source);
  1581. return source;
  1582. }));
  1583. for (const source of included) {
  1584. await includeHeader(source);
  1585. }
  1586. };
  1587. await includeHeader(sourceCode);
  1588. const codes = [];
  1589. for (const [file, code] of files) {
  1590. codes.push({ file, code, });
  1591. }
  1592. return await this.request(Object.assign({
  1593. compiler: this.name,
  1594. code: sourceCode,
  1595. stdin: input,
  1596. codes,
  1597. }, Object.assign(options, this.getOptions(sourceCode, input))));
  1598. }
  1599. }
  1600.  
  1601. // 設定項目を定義
  1602. config.registerCount("wandboxAPI.cacheLifetime", 24 * 60 * 60 * 1000, "lifetime [ms] of Wandbox compiler list cache");
  1603. async function fetchWandboxCompilers() {
  1604. // キャッシュが有効な場合はキャッシュを使う
  1605. const cached = config.get("wandboxAPI.cachedCompilerList", { value: null, lastModified: -Infinity });
  1606. if (Date.now() - cached.lastModified <= config.get("wandboxAPI.cacheLifetime", 24 * 60 * 60 * 1000)) {
  1607. return cached.value;
  1608. }
  1609. // キャッシュが無効な場合は fetch
  1610. const response = await fetch("https://wandbox.org/api/list.json");
  1611. const compilers = await response.json();
  1612. config.set("wandboxAPI.cachedCompilerList", { value: compilers, lastModified: Date.now() });
  1613. config.save();
  1614. return compilers;
  1615. }
  1616. function getOptimizationOption(compiler) {
  1617. // Optimizationという名前のSwitchから、最適化のオプションを取得する
  1618. return compiler.switches.find((sw) => sw["display-name"] === "Optimization")
  1619. ?.name;
  1620. }
  1621. function toRunner(compiler) {
  1622. const optimizationOption = getOptimizationOption(compiler);
  1623. if (compiler.language == "C++") {
  1624. return new WandboxCppRunner(compiler.name, compiler.language + " " + compiler.name + " + ACL", {
  1625. "compiler-option-raw": "-I.",
  1626. options: optimizationOption,
  1627. });
  1628. }
  1629. else {
  1630. return new WandboxRunner(compiler.name, compiler.language + " " + compiler.name, {
  1631. options: optimizationOption,
  1632. });
  1633. }
  1634. }
  1635.  
  1636. // runners[key] = runner; key = language + " " + environmentInfo
  1637. const runners = {
  1638. "C C17 Clang paiza.io": new PaizaIORunner("c", "C (C17 / Clang)"),
  1639. "Python3 CPython paiza.io": new PaizaIORunner("python3", "Python3"),
  1640. "Python3 Pyodide": pyodideRunner,
  1641. "Bash paiza.io": new PaizaIORunner("bash", "Bash"),
  1642. "Clojure paiza.io": new PaizaIORunner("clojure", "Clojure"),
  1643. "D LDC paiza.io": new PaizaIORunner("d", "D (LDC)"),
  1644. "Erlang paiza.io": new PaizaIORunner("erlang", "Erlang"),
  1645. "Elixir paiza.io": new PaizaIORunner("elixir", "Elixir"),
  1646. "F# Interactive paiza.io": new PaizaIORunner("fsharp", "F# (Interactive)"),
  1647. "Haskell paiza.io": new PaizaIORunner("haskell", "Haskell"),
  1648. "JavaScript paiza.io": new PaizaIORunner("javascript", "JavaScript"),
  1649. "Kotlin paiza.io": new PaizaIORunner("kotlin", "Kotlin"),
  1650. "Objective-C paiza.io": new PaizaIORunner("objective-c", "Objective-C"),
  1651. "Perl paiza.io": new PaizaIORunner("perl", "Perl"),
  1652. "PHP paiza.io": new PaizaIORunner("php", "PHP"),
  1653. "Ruby paiza.io": new PaizaIORunner("ruby", "Ruby"),
  1654. "Rust 1.42.0 AtCoder": new AtCoderRunner("4050", "Rust (1.42.0)"),
  1655. "Rust paiza.io": new PaizaIORunner("rust", "Rust"),
  1656. "Scala paiza": new PaizaIORunner("scala", "Scala"),
  1657. "Scheme paiza.io": new PaizaIORunner("scheme", "Scheme"),
  1658. "Swift paiza.io": new PaizaIORunner("swift", "Swift"),
  1659. "Text local": new CustomRunner("Text", async (sourceCode, input) => {
  1660. return {
  1661. status: "OK",
  1662. exitCode: "0",
  1663. input,
  1664. output: sourceCode,
  1665. };
  1666. }),
  1667. "Basic Visual Basic paiza.io": new PaizaIORunner("vb", "Visual Basic"),
  1668. "COBOL Free paiza.io": new PaizaIORunner("cobol", "COBOL - Free"),
  1669. "COBOL Fixed OpenCOBOL 1.1.0 AtCoder": new AtCoderRunner("4060", "COBOL - Fixed (OpenCOBOL 1.1.0)"),
  1670. "COBOL Free OpenCOBOL 1.1.0 AtCoder": new AtCoderRunner("4061", "COBOL - Free (OpenCOBOL 1.1.0)"),
  1671. };
  1672. // wandboxの環境を追加
  1673. const wandboxPromise = fetchWandboxCompilers().then((compilers) => {
  1674. for (const compiler of compilers) {
  1675. let language = compiler.language;
  1676. if (compiler.language === "Python" && /python-3\./.test(compiler.version)) {
  1677. language = "Python3";
  1678. }
  1679. const key = language + " " + compiler.name;
  1680. runners[key] = toRunner(compiler);
  1681. console.log("wandbox", key, runners[key]);
  1682. }
  1683. });
  1684. site.then(site => {
  1685. if (site.name == "AtCoder") {
  1686. // AtCoderRunner がない場合は、追加する
  1687. for (const [languageId, descriptor] of Object.entries(site.langMap)) {
  1688. const m = descriptor.match(/([^ ]+)(.*)/);
  1689. if (m) {
  1690. const name = `${m[1]} ${m[2].slice(1)} AtCoder`;
  1691. runners[name] = new AtCoderRunner(languageId, descriptor);
  1692. }
  1693. }
  1694. }
  1695. });
  1696. console.info("AtCoder Easy Test: codeRunner OK");
  1697. config.registerCount("codeRunner.maxRetry", 3, "Max count of retry when IE (Internal Error)");
  1698. var codeRunner = {
  1699. // 指定した環境でコードを実行する
  1700. async run(runnerId, sourceCode, input, expectedOutput, options = { trim: true, split: true }) {
  1701. // CodeRunner が存在しない言語ID
  1702. if (!(runnerId in runners))
  1703. return Promise.reject("Language not supported");
  1704. // 最後に実行したコードを保存
  1705. if (sourceCode.length > 0)
  1706. site.then(site => codeSaver.save(site.taskURI, sourceCode));
  1707. // 実行
  1708. const maxRetry = config.get("codeRunner.maxRetry", 3);
  1709. for (let retry = 0; retry < maxRetry; retry++) {
  1710. try {
  1711. const result = await runners[runnerId].test(sourceCode, input, expectedOutput, options);
  1712. const lang = runnerId.split(" ")[0];
  1713. if (result.status == "IE") {
  1714. console.error(result);
  1715. const runnerIds = Object.keys(runners).filter(runnerId => runnerId.split(" ")[0] == lang);
  1716. const index = runnerIds.indexOf(runnerId);
  1717. runnerId = runnerIds[(index + 1) % runnerIds.length];
  1718. continue;
  1719. }
  1720. return result;
  1721. }
  1722. catch (e) {
  1723. console.error(e);
  1724. }
  1725. }
  1726. },
  1727. // 環境の名前の一覧を取得する
  1728. // @return runnerIdとラベルのペアの配列
  1729. async getEnvironment(languageId) {
  1730. await wandboxPromise; // wandboxAPI がコンパイラ情報を取ってくるのを待つ
  1731. const langs = similarLangs(languageId, Object.keys(runners));
  1732. if (langs.length == 0)
  1733. throw `Undefined language: ${languageId}`;
  1734. return langs.map(runnerId => [runnerId, runners[runnerId].label]);
  1735. },
  1736. };
  1737.  
  1738. 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>";
  1739.  
  1740. 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>";
  1741.  
  1742. async function init() {
  1743. const site$1 = await site;
  1744. const style = html2element(hStyle$1);
  1745. const bottomMenu = html2element(hBottomMenu);
  1746. unsafeWindow.document.head.appendChild(style);
  1747. site$1.bottomMenuContainer.appendChild(bottomMenu);
  1748. const bottomMenuKey = bottomMenu.querySelector("#bottom-menu-key");
  1749. const bottomMenuTabs = bottomMenu.querySelector("#bottom-menu-tabs");
  1750. const bottomMenuContents = bottomMenu.querySelector("#bottom-menu-contents");
  1751. // メニューのリサイズ
  1752. {
  1753. let resizeStart = null;
  1754. const onStart = (event) => {
  1755. const target = event.target;
  1756. const pageY = event.pageY;
  1757. if (target.id != "bottom-menu-tabs")
  1758. return;
  1759. resizeStart = { y: pageY, height: bottomMenuContents.getBoundingClientRect().height };
  1760. };
  1761. const onMove = (event) => {
  1762. if (!resizeStart)
  1763. return;
  1764. event.preventDefault();
  1765. bottomMenuContents.style.height = `${resizeStart.height - (event.pageY - resizeStart.y)}px`;
  1766. };
  1767. const onEnd = () => {
  1768. resizeStart = null;
  1769. };
  1770. bottomMenuTabs.addEventListener("mousedown", onStart);
  1771. bottomMenuTabs.addEventListener("mousemove", onMove);
  1772. bottomMenuTabs.addEventListener("mouseup", onEnd);
  1773. bottomMenuTabs.addEventListener("mouseleave", onEnd);
  1774. }
  1775. let tabs = new Set();
  1776. let selectedTab = null;
  1777. /** 下メニューの操作
  1778. * 下メニューはいくつかのタブからなる。タブはそれぞれ tabId, ラベル, 中身を持っている。
  1779. */
  1780. const menuController = {
  1781. /** タブを選択 */
  1782. selectTab(tabId) {
  1783. const tab = site$1.jQuery(`#bottom-menu-tab-${tabId}`);
  1784. if (tab && tab[0]) {
  1785. tab.tab("show"); // Bootstrap 3
  1786. selectedTab = tabId;
  1787. }
  1788. },
  1789. /** 下メニューにタブを追加する */
  1790. addTab(tabId, tabLabel, paneContent, options = {}) {
  1791. console.log(`AtCoder Easy Test: addTab: ${tabLabel} (${tabId})`, paneContent);
  1792. // タブを追加
  1793. const tab = document.createElement("a");
  1794. tab.textContent = tabLabel;
  1795. tab.id = `bottom-menu-tab-${tabId}`;
  1796. tab.href = "#";
  1797. tab.dataset.id = tabId;
  1798. tab.dataset.target = `#bottom-menu-pane-${tabId}`;
  1799. tab.dataset.toggle = "tab";
  1800. tab.addEventListener("click", event => {
  1801. event.preventDefault();
  1802. menuController.selectTab(tabId);
  1803. });
  1804. tabs.add(tab);
  1805. const tabLi = document.createElement("li");
  1806. tabLi.appendChild(tab);
  1807. bottomMenuTabs.appendChild(tabLi);
  1808. // 内容を追加
  1809. const pane = document.createElement("div");
  1810. pane.className = "tab-pane";
  1811. pane.id = `bottom-menu-pane-${tabId}`;
  1812. pane.appendChild(paneContent);
  1813. bottomMenuContents.appendChild(pane);
  1814. const controller = {
  1815. get id() {
  1816. return tabId;
  1817. },
  1818. close() {
  1819. bottomMenuTabs.removeChild(tabLi);
  1820. bottomMenuContents.removeChild(pane);
  1821. tabs.delete(tab);
  1822. if (selectedTab == tabId) {
  1823. selectedTab = null;
  1824. if (tabs.size > 0) {
  1825. menuController.selectTab(tabs.values().next().value.dataset.id);
  1826. }
  1827. }
  1828. },
  1829. show() {
  1830. menuController.show();
  1831. menuController.selectTab(tabId);
  1832. },
  1833. set color(color) {
  1834. tab.style.backgroundColor = color;
  1835. },
  1836. };
  1837. // 閉じるボタン
  1838. if (options.closeButton) {
  1839. const btn = document.createElement("a");
  1840. btn.className = "bottom-menu-btn-close btn btn-link glyphicon glyphicon-remove";
  1841. btn.addEventListener("click", () => {
  1842. controller.close();
  1843. });
  1844. tab.appendChild(btn);
  1845. }
  1846. // 選択されているタブがなければ選択
  1847. if (!selectedTab)
  1848. menuController.selectTab(tabId);
  1849. return controller;
  1850. },
  1851. /** 下メニューを表示する */
  1852. show() {
  1853. if (bottomMenuKey.classList.contains("collapsed"))
  1854. bottomMenuKey.click();
  1855. },
  1856. /** 下メニューの表示/非表示を切り替える */
  1857. toggle() {
  1858. bottomMenuKey.click();
  1859. },
  1860. };
  1861. console.info("AtCoder Easy Test: bottomMenu OK");
  1862. return menuController;
  1863. }
  1864.  
  1865. 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>";
  1866.  
  1867. class ResultRow {
  1868. _tabs;
  1869. _element;
  1870. _promise;
  1871. constructor(pairs) {
  1872. this._tabs = pairs.map(([_, tab]) => tab);
  1873. this._element = html2element(hRowTemplate);
  1874. this._element.querySelector(".close").addEventListener("click", () => this.remove());
  1875. {
  1876. const date = new Date();
  1877. const h = date.getHours().toString().padStart(2, "0");
  1878. const m = date.getMinutes().toString().padStart(2, "0");
  1879. const s = date.getSeconds().toString().padStart(2, "0");
  1880. this._element.querySelector(".atcoder-easy-test-cases-row-date").textContent = `${h}:${m}:${s}`;
  1881. }
  1882. const numCases = pairs.length;
  1883. let numFinished = 0;
  1884. let numAccepted = 0;
  1885. const progressBar = this._element.querySelector(".progress-bar");
  1886. progressBar.textContent = `${numFinished} / ${numCases}`;
  1887. this._promise = Promise.all(pairs.map(([pResult, tab]) => {
  1888. const button = html2element(`<div class="label label-default" style="margin: 3px; cursor: pointer;">WJ</div>`);
  1889. button.addEventListener("click", async () => {
  1890. (await tab).show();
  1891. });
  1892. this._element.appendChild(button);
  1893. return pResult.then(result => {
  1894. button.textContent = result.status;
  1895. if (result.status == "AC") {
  1896. button.classList.add("label-success");
  1897. }
  1898. else if (result.status != "OK") {
  1899. button.classList.add("label-warning");
  1900. }
  1901. numFinished++;
  1902. if (result.status == "AC")
  1903. numAccepted++;
  1904. progressBar.textContent = `${numFinished} / ${numCases}`;
  1905. progressBar.style.width = `${100 * numFinished / numCases}%`;
  1906. if (numFinished == numCases) {
  1907. if (numAccepted == numCases)
  1908. this._element.classList.add("alert-success");
  1909. else
  1910. this._element.classList.add("alert-warning");
  1911. }
  1912. }).catch(reason => {
  1913. button.textContent = "IE";
  1914. button.classList.add("label-danger");
  1915. console.error(reason);
  1916. });
  1917. }));
  1918. }
  1919. get element() {
  1920. return this._element;
  1921. }
  1922. onFinish(listener) {
  1923. this._promise.then(listener);
  1924. }
  1925. remove() {
  1926. for (const pTab of this._tabs)
  1927. pTab.then(tab => tab.close());
  1928. const parent = this._element.parentElement;
  1929. if (parent)
  1930. parent.removeChild(this._element);
  1931. }
  1932. }
  1933.  
  1934. var hResultList = "<div class=\"row\"></div>";
  1935.  
  1936. const eResultList = html2element(hResultList);
  1937. site.then(site => site.resultListContainer.appendChild(eResultList));
  1938. const resultList = {
  1939. addResult(pairs) {
  1940. const result = new ResultRow(pairs);
  1941. eResultList.insertBefore(result.element, eResultList.firstChild);
  1942. return result;
  1943. },
  1944. };
  1945.  
  1946. const version = {
  1947. currentProperty: new ObservableValue("2.13.0"),
  1948. get current() {
  1949. return this.currentProperty.value;
  1950. },
  1951. latestProperty: new ObservableValue(config.get("version.latest", "2.13.0")),
  1952. get latest() {
  1953. return this.latestProperty.value;
  1954. },
  1955. lastCheckProperty: new ObservableValue(config.get("version.lastCheck", 0)),
  1956. get lastCheck() {
  1957. return this.lastCheckProperty.value;
  1958. },
  1959. get hasUpdate() {
  1960. return this.compare(this.current, this.latest) < 0;
  1961. },
  1962. compare(a, b) {
  1963. const x = a.split(".").map((s) => parseInt(s, 10));
  1964. const y = b.split(".").map((s) => parseInt(s, 10));
  1965. for (let i = 0; i < 3; i++) {
  1966. if (x[i] < y[i]) {
  1967. return -1;
  1968. }
  1969. else if (x[i] > y[i]) {
  1970. return 1;
  1971. }
  1972. }
  1973. return 0;
  1974. },
  1975. async checkUpdate(force = false) {
  1976. const now = Date.now();
  1977. if (!force && now - version.lastCheck < config.get("version.checkInterval", aDay)) {
  1978. return this.current;
  1979. }
  1980. const packageJson = await fetch("https://raw.githubusercontent.com/magurofly/atcoder-easy-test/main/v2/package.json").then(r => r.json());
  1981. console.log(packageJson);
  1982. const latest = packageJson["version"];
  1983. this.latestProperty.value = latest;
  1984. config.set("version.latest", latest);
  1985. this.lastCheckProperty.value = now;
  1986. config.set("version.lastCheck", now);
  1987. return latest;
  1988. },
  1989. };
  1990. // 更新チェック
  1991. const aDay = 24 * 60 * 60 * 1e3;
  1992. config.registerCount("version.checkInterval", aDay, "Interval [ms] of checking for new version");
  1993. config.get("version.checkInterval", aDay);
  1994. setInterval(() => {
  1995. version.checkUpdate(false);
  1996. }, 60e3);
  1997. settings.add("version", (win) => {
  1998. const root = newElement("div");
  1999. const text = win.document.createTextNode.bind(win.document);
  2000. const textAuto = (property) => {
  2001. const t = text(property.value);
  2002. property.addListener(value => {
  2003. t.textContent = value;
  2004. });
  2005. return t;
  2006. };
  2007. const tCurrent = textAuto(version.currentProperty);
  2008. const tLatest = textAuto(version.latestProperty);
  2009. const tLastCheck = textAuto(version.lastCheckProperty.map(time => new Date(time).toLocaleString()));
  2010. root.appendChild(newElement("p", {}, [
  2011. text("AtCoder Easy Test v"),
  2012. tCurrent,
  2013. ]));
  2014. const updateButton = newElement("a", {
  2015. className: "btn btn-info",
  2016. textContent: "Install",
  2017. href: "https://github.com/magurofly/atcoder-easy-test/raw/main/v2/atcoder-easy-test.user.js",
  2018. target: "_blank",
  2019. });
  2020. const showButton = () => {
  2021. if (version.hasUpdate)
  2022. updateButton.style.display = "inline";
  2023. else
  2024. updateButton.style.display = "none";
  2025. };
  2026. showButton();
  2027. version.lastCheckProperty.addListener(showButton);
  2028. root.appendChild(newElement("p", {}, [
  2029. text("Latest: v"),
  2030. tLatest,
  2031. text(" (Last Check: "),
  2032. tLastCheck,
  2033. text(") "),
  2034. updateButton,
  2035. ]));
  2036. root.appendChild(newElement("p", {}, [
  2037. newElement("a", {
  2038. className: "btn btn-primary",
  2039. textContent: "Check Update",
  2040. onclick() {
  2041. version.checkUpdate(true);
  2042. },
  2043. }),
  2044. ]));
  2045. return root;
  2046. });
  2047.  
  2048. 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>";
  2049.  
  2050. function setClassFromData(element, name) {
  2051. const classes = element.dataset[name].split(/\s+/);
  2052. for (let className of classes) {
  2053. let flag = true;
  2054. if (className[0] == "!") {
  2055. className = className.slice(1);
  2056. flag = false;
  2057. }
  2058. element.classList.toggle(className, flag);
  2059. }
  2060. }
  2061. class ResultTabContent {
  2062. _title;
  2063. _uid;
  2064. _element;
  2065. _result;
  2066. constructor() {
  2067. this._uid = Date.now().toString(16) + Math.floor(Math.random() * 256).toString(16);
  2068. this._result = null;
  2069. this._element = html2element(hTabTemplate);
  2070. this._element.id = `atcoder-easy-test-result-${this._uid}`;
  2071. }
  2072. set result(result) {
  2073. this._result = result;
  2074. if (result.status == "AC") {
  2075. this.outputStyle.backgroundColor = "#dff0d8";
  2076. }
  2077. else if (result.status != "OK") {
  2078. this.outputStyle.backgroundColor = "#fcf8e3";
  2079. }
  2080. this.input = result.input;
  2081. if ("expectedOutput" in result)
  2082. this.expectedOutput = result.expectedOutput;
  2083. this.exitCode = result.exitCode;
  2084. if ("execTime" in result)
  2085. this.execTime = `${result.execTime} ms`;
  2086. if ("memory" in result)
  2087. this.memory = `${result.memory} KB`;
  2088. if ("output" in result)
  2089. this.output = result.output;
  2090. if (result.error)
  2091. this.error = result.error;
  2092. }
  2093. get result() {
  2094. return this._result;
  2095. }
  2096. get uid() {
  2097. return this._uid;
  2098. }
  2099. get element() {
  2100. return this._element;
  2101. }
  2102. set title(title) {
  2103. this._title = title;
  2104. }
  2105. get title() {
  2106. return this._title;
  2107. }
  2108. set input(input) {
  2109. this._get("input").value = input;
  2110. }
  2111. get inputStyle() {
  2112. return this._get("input").style;
  2113. }
  2114. set expectedOutput(output) {
  2115. this._get("expected-output").value = output;
  2116. setClassFromData(this._get("col-input"), "ifExpectedOutput");
  2117. setClassFromData(this._get("col-expected-output"), "ifExpectedOutput");
  2118. }
  2119. get expectedOutputStyle() {
  2120. return this._get("expected-output").style;
  2121. }
  2122. set output(output) {
  2123. this._get("output").value = output;
  2124. }
  2125. get outputStyle() {
  2126. return this._get("output").style;
  2127. }
  2128. set error(error) {
  2129. this._get("error").value = error;
  2130. setClassFromData(this._get("col-output"), "ifError");
  2131. setClassFromData(this._get("col-error"), "ifError");
  2132. }
  2133. set exitCode(code) {
  2134. const element = this._get("exit-code");
  2135. element.textContent = code;
  2136. const isSuccess = code == "0";
  2137. element.classList.toggle("bg-success", isSuccess);
  2138. element.classList.toggle("bg-danger", !isSuccess);
  2139. }
  2140. set execTime(time) {
  2141. this._get("exec-time").textContent = time;
  2142. }
  2143. set memory(memory) {
  2144. this._get("memory").textContent = memory;
  2145. }
  2146. _get(name) {
  2147. return this._element.querySelector(`.atcoder-easy-test-result-${name}`);
  2148. }
  2149. }
  2150.  
  2151. 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\" style=\"width: 100% !important\"></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>";
  2152.  
  2153. var hStyle = "<style>\n.atcoder-easy-test-result textarea {\n font-family: monospace;\n font-weight: normal;\n}\n</style>";
  2154.  
  2155. 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>";
  2156.  
  2157. 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>";
  2158.  
  2159. 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>";
  2160.  
  2161. (async () => {
  2162. const site$1 = await site;
  2163. const doc = unsafeWindow.document;
  2164. // init bottomMenu
  2165. const pBottomMenu = init();
  2166. pBottomMenu.then(bottomMenu => {
  2167. unsafeWindow.bottomMenu = bottomMenu;
  2168. });
  2169. await doneOrFail(pBottomMenu);
  2170. // external interfaces
  2171. unsafeWindow.codeRunner = codeRunner;
  2172. doc.head.appendChild(html2element(hStyle));
  2173. // interface
  2174. const atCoderEasyTest = {
  2175. version,
  2176. site: site$1,
  2177. config,
  2178. codeSaver,
  2179. enableButtons() {
  2180. events.trig("enable");
  2181. },
  2182. disableButtons() {
  2183. events.trig("disable");
  2184. },
  2185. runCount: 0,
  2186. runTest(title, language, sourceCode, input, output = null, options = { trim: true, split: true, }) {
  2187. this.disableButtons();
  2188. const content = new ResultTabContent();
  2189. const pTab = pBottomMenu.then(bottomMenu => bottomMenu.addTab("easy-test-result-" + content.uid, `#${++this.runCount} ${title}`, content.element, { active: true, closeButton: true }));
  2190. const pResult = codeRunner.run(language, sourceCode, input, output, options);
  2191. pResult.then(result => {
  2192. content.result = result;
  2193. if (result.status == "AC") {
  2194. pTab.then(tab => tab.color = "#dff0d8");
  2195. }
  2196. else if (result.status != "OK") {
  2197. pTab.then(tab => tab.color = "#fcf8e3");
  2198. }
  2199. }).finally(() => {
  2200. this.enableButtons();
  2201. });
  2202. return [pResult, pTab];
  2203. }
  2204. };
  2205. unsafeWindow.atCoderEasyTest = atCoderEasyTest;
  2206. // place "Easy Test" tab
  2207. {
  2208. // declare const hRoot: string;
  2209. const root = html2element(hRoot);
  2210. const E = (id) => root.querySelector(`#atcoder-easy-test-${id}`);
  2211. const eLanguage = E("language");
  2212. const eInput = E("input");
  2213. const eAllowableErrorCheck = E("allowable-error-check");
  2214. const eAllowableError = E("allowable-error");
  2215. const eOutput = E("output");
  2216. const eRun = E("run");
  2217. const eSetting = E("setting");
  2218. const eVersion = E("version");
  2219. eVersion.textContent = atCoderEasyTest.version.current;
  2220. events.on("enable", () => {
  2221. eRun.classList.remove("disabled");
  2222. });
  2223. events.on("disable", () => {
  2224. eRun.classList.add("disabled");
  2225. });
  2226. eSetting.addEventListener("click", () => {
  2227. settings.open();
  2228. });
  2229. // バージョン確認
  2230. {
  2231. let button = null;
  2232. const showButton = () => {
  2233. if (!version.hasUpdate)
  2234. return;
  2235. if (button) {
  2236. button.textContent = `Update to v${version.latest}`;
  2237. return;
  2238. }
  2239. console.info(`AtCoder Easy Test: New version available: v${version}`);
  2240. button = newElement("a", {
  2241. href: "https://github.com/magurofly/atcoder-easy-test/raw/main/v2/atcoder-easy-test.user.js",
  2242. target: "_blank",
  2243. className: "btn btn-xs btn-info",
  2244. textContent: `Update to v${version.latest}`,
  2245. });
  2246. eVersion.insertAdjacentElement("afterend", button);
  2247. };
  2248. version.latestProperty.addListener(showButton);
  2249. showButton();
  2250. }
  2251. // 言語選択関係
  2252. {
  2253. async function onEnvChange() {
  2254. const langSelection = config.get("langSelection", {});
  2255. langSelection[site$1.language.value] = eLanguage.value;
  2256. config.set("langSelection", langSelection);
  2257. config.save();
  2258. }
  2259. if (unsafeWindow["jQuery"] && unsafeWindow["jQuery"].fn.select2) {
  2260. unsafeWindow["jQuery"](eLanguage).on("change", onEnvChange);
  2261. }
  2262. else {
  2263. eLanguage.addEventListener("change", onEnvChange);
  2264. }
  2265. async function setLanguage() {
  2266. const languageId = site$1.language.value;
  2267. while (eLanguage.firstChild)
  2268. eLanguage.removeChild(eLanguage.firstChild);
  2269. try {
  2270. if (!languageId)
  2271. throw new Error("AtCoder Easy Test: language not set");
  2272. const langs = await codeRunner.getEnvironment(languageId);
  2273. console.log(`AtCoder Easy Test: language = ${langs[1]} (${langs[0]})`);
  2274. // add <option>
  2275. for (const [languageId, label] of langs) {
  2276. const option = document.createElement("option");
  2277. option.value = languageId;
  2278. option.textContent = label;
  2279. eLanguage.appendChild(option);
  2280. }
  2281. // load
  2282. const langSelection = config.get("langSelection", {});
  2283. if (languageId in langSelection) {
  2284. const prev = langSelection[languageId];
  2285. if (langs.some(([lang, _]) => lang == prev)) {
  2286. eLanguage.value = prev;
  2287. }
  2288. }
  2289. events.trig("enable");
  2290. }
  2291. catch (error) {
  2292. console.log(`AtCoder Easy Test: language = ? (${languageId})`);
  2293. console.error(error);
  2294. const option = document.createElement("option");
  2295. option.className = "fg-danger";
  2296. option.textContent = error;
  2297. eLanguage.appendChild(option);
  2298. events.trig("disable");
  2299. }
  2300. }
  2301. site$1.language.addListener(() => setLanguage());
  2302. eAllowableError.disabled = !eAllowableErrorCheck.checked;
  2303. eAllowableErrorCheck.addEventListener("change", event => {
  2304. eAllowableError.disabled = !eAllowableErrorCheck.checked;
  2305. });
  2306. }
  2307. // テスト実行
  2308. function runTest(title, input, output = null, options = {}) {
  2309. const opts = Object.assign({ trim: true, split: true, }, options);
  2310. if (eAllowableErrorCheck.checked) {
  2311. opts.allowableError = parseFloat(eAllowableError.value);
  2312. }
  2313. return atCoderEasyTest.runTest(title, eLanguage.value, site$1.sourceCode, input, output, opts);
  2314. }
  2315. function runAllCases(testcases) {
  2316. const runGroupId = uuid();
  2317. const pairs = testcases.map(testcase => runTest(testcase.title, testcase.input, testcase.output, { runGroupId }));
  2318. resultList.addResult(pairs);
  2319. return Promise.all(pairs.map(([pResult, _]) => pResult.then(result => {
  2320. if (result.status == "AC")
  2321. return Promise.resolve(result);
  2322. else
  2323. return Promise.reject(result);
  2324. })));
  2325. }
  2326. eRun.addEventListener("click", _ => {
  2327. const title = "Run";
  2328. const input = eInput.value;
  2329. const output = eOutput.value;
  2330. runTest(title, input, output || null);
  2331. });
  2332. await doneOrFail(pBottomMenu.then(bottomMenu => bottomMenu.addTab("easy-test", "Easy Test", root)));
  2333. // place "Run" button on each sample
  2334. for (const testCase of site$1.testCases) {
  2335. const eRunButton = html2element(hRunButton);
  2336. eRunButton.addEventListener("click", async () => {
  2337. const [pResult, pTab] = runTest(testCase.title, testCase.input, testCase.output);
  2338. await pResult;
  2339. (await pTab).show();
  2340. });
  2341. testCase.anchor.insertAdjacentElement("afterend", eRunButton);
  2342. events.on("disable", () => {
  2343. eRunButton.classList.add("disabled");
  2344. });
  2345. events.on("enable", () => {
  2346. eRunButton.classList.remove("disabled");
  2347. });
  2348. }
  2349. // place "Test & Submit" button
  2350. {
  2351. const button = html2element(hTestAndSubmit);
  2352. site$1.testButtonContainer.appendChild(button);
  2353. const testAndSubmit = async () => {
  2354. await runAllCases(site$1.testCases);
  2355. site$1.submit();
  2356. };
  2357. button.addEventListener("click", testAndSubmit);
  2358. events.on("testAndSubmit", testAndSubmit);
  2359. events.on("disable", () => button.classList.add("disabled"));
  2360. events.on("enable", () => button.classList.remove("disabled"));
  2361. }
  2362. // place "Test All Samples" button
  2363. {
  2364. const button = html2element(hTestAllSamples);
  2365. site$1.testButtonContainer.appendChild(button);
  2366. const testAllSamples = () => runAllCases(site$1.testCases);
  2367. button.addEventListener("click", testAllSamples);
  2368. events.on("testAllSamples", testAllSamples);
  2369. events.on("disable", () => button.classList.add("disabled"));
  2370. events.on("enable", () => button.classList.remove("disabled"));
  2371. }
  2372. }
  2373. // place "Restore Last Play" button
  2374. try {
  2375. const restoreButton = doc.createElement("a");
  2376. restoreButton.className = "btn btn-danger btn-sm";
  2377. restoreButton.textContent = "Restore Last Play";
  2378. restoreButton.addEventListener("click", async () => {
  2379. try {
  2380. const lastCode = await codeSaver.restore(site$1.taskURI);
  2381. if (site$1.sourceCode.length == 0 || confirm("Your current code will be replaced. Are you sure?")) {
  2382. site$1.sourceCode = lastCode;
  2383. }
  2384. }
  2385. catch (reason) {
  2386. alert(reason);
  2387. }
  2388. });
  2389. site$1.sideButtonContainer.appendChild(restoreButton);
  2390. }
  2391. catch (e) {
  2392. console.error(e);
  2393. }
  2394. // キーボードショートカット
  2395. config.registerFlag("ui.useKeyboardShortcut", true, "Use Keyboard Shortcuts");
  2396. unsafeWindow.addEventListener("keydown", (event) => {
  2397. if (config.get("ui.useKeyboardShortcut", true)) {
  2398. if (event.key == "Enter" && event.ctrlKey) {
  2399. events.trig("testAndSubmit");
  2400. }
  2401. else if (event.key == "Enter" && event.altKey) {
  2402. events.trig("testAllSamples");
  2403. }
  2404. else if (event.key == "Escape" && event.altKey) {
  2405. pBottomMenu.then(bottomMenu => bottomMenu.toggle());
  2406. }
  2407. }
  2408. });
  2409. })();
  2410. })();