AtCoder Easy Test v2

Make testing sample cases easy

Verze ze dne 09. 09. 2023. Zobrazit nejnovější verzi.

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