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