AtCoder Easy Test v2

Make testing sample cases easy

Verze ze dne 14. 11. 2021. Zobrazit nejnovější verzi.

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