Greasy Fork 还支持 简体中文。

AtCoder Easy Test v2

Make testing sample cases easy

目前為 2022-02-15 提交的版本,檢視 最新版本

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