Codeforces Better!

Codeforces界面汉化、题目翻译,markdown视图,一键复制题目

当前为 2023-05-20 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Codeforces Better!
  3. // @namespace https://greasyfork.org/users/747162
  4. // @version 1.27
  5. // @description Codeforces界面汉化、题目翻译,markdown视图,一键复制题目
  6. // @author 北极小狐
  7. // @match https://codeforces.com/*
  8. // @connect www2.deepl.com
  9. // @connect m.youdao.com
  10. // @connect openai.api2d.net
  11. // @connect api.openai.com
  12. // @grant GM_xmlhttpRequest
  13. // @grant GM_info
  14. // @connect greasyfork.org
  15. // @icon https://aowuucdn.oss-cn-beijing.aliyuncs.com/codeforces.png
  16. // @require https://cdn.bootcdn.net/ajax/libs/turndown/7.1.2/turndown.js
  17. // @require https://cdnjs.cloudflare.com/ajax/libs/markdown-it/13.0.1/markdown-it.min.js
  18. // @license MIT
  19. // ==/UserScript==
  20. // 样式
  21. function loadCssCode(code) {
  22. var style = document.createElement('style');
  23. style.type = 'text/css';
  24. style.rel = 'stylesheet';
  25. style.appendChild(document.createTextNode(code));
  26. var head = document.getElementsByTagName('head')[0];
  27. head.appendChild(style);
  28. }
  29. loadCssCode(`
  30. span.mdViewContent {
  31. white-space: pre-wrap;
  32. }
  33. /*翻译div*/
  34. .translate-problem-statement {
  35. display: grid;
  36. justify-items: start;
  37. white-space: pre-wrap;
  38. letter-spacing: 1.4px;
  39. border: 1px dashed #00aeeccc;
  40. border-radius: 0.3rem;
  41. padding: 5px;
  42. margin: 10px 0px;
  43. font-size: 13px;
  44. }
  45. .translate-problem-statement a {
  46. color: #4d87c7;
  47. background: 0 0;
  48. text-decoration: none;
  49. }
  50. .translate-problem-statement a:hover {
  51. background-color: #800;
  52. color: #fff;
  53. text-decoration: none;
  54. }
  55. .html2md-panel {
  56. display: flex;
  57. justify-content: flex-end;
  58. }
  59. button.html2mdButton {
  60. cursor: pointer;
  61. background-color: #e6e6e6;
  62. color: #727378;
  63. height: 22px;
  64. width: auto;
  65. font-size: 13px;
  66. border-radius: 0.3rem;
  67. border: none;
  68. padding: 1px 5px;
  69. margin: 5px;
  70. box-shadow: 0 0 1px #0000004d;
  71. }
  72. button.html2mdButton.copied {
  73. background-color: #07e65196;
  74. color: #104f2b;
  75. }
  76. button.html2mdButton.mdViewed {
  77. background-color: #ff980057;
  78. color: #5a3a0c;
  79. }
  80. button.translated {
  81. cursor: not-allowed;
  82. background-color: #2a6dc296;
  83. color: #fffdfd;
  84. }
  85. button.html2mdButton.reTranslation {
  86. background-color: #faebd7;
  87. }
  88. .translate-problem-statement table {
  89. border: 1px #ccc solid;
  90. border-collapse: collapse;
  91. margin: 1.3571em 0 0;
  92. color: #222;
  93. }
  94. .translate-problem-statement table td {
  95. border-right: 1px solid #ccc;
  96. border-top: 1px solid #ccc;
  97. padding: 0.7143em 0.5em;
  98. }
  99. .translate-problem-statement table th {
  100. padding: 0.7143em 0.5em;
  101. }
  102. .translate-problem-statement p:not(:first-child) {
  103. margin: 1.5em 0 0;
  104. }
  105. /*设置面板*/
  106. button.html2mdButton.CFBetter_setting {
  107. float: right;
  108. height: 30px;
  109. background: #60a5fa;
  110. color: white;
  111. box-shadow: 0px 0px 1px 1px #0000004d;
  112. margin: 10px;
  113. }
  114. #CFBetter_setting_menu {
  115. z-index: 9999;
  116. border-radius: 0.5rem;
  117. box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
  118. display: grid;
  119. position: fixed;
  120. top: 50%;
  121. left: 50%;
  122. width: 270px;
  123. transform: translate(-50%, -50%);
  124. border-radius: 16px;
  125. background-color: #ecf0ff;
  126. border: 6px solid #ffffff;
  127. color: #697e91;
  128. padding: 10px 20px 20px 20px;
  129. }
  130.  
  131. /*设置面板-关闭按钮*/
  132. #CFBetter_setting_menu .tool-box {
  133. position: absolute;
  134. display: flex;
  135. align-items: center;
  136. justify-content: center;
  137. width: 2.5rem;
  138. height: 2.5rem;
  139. top: 3px;
  140. right: 3px;
  141. }
  142.  
  143. #CFBetter_setting_menu .btn-close {
  144. display: flex;
  145. align-items: center;
  146. justify-content: center;
  147. text-align: center;
  148. width: 2rem;
  149. height: 2rem;
  150. color: transparent;
  151. font-size: 0;
  152. cursor: pointer;
  153. background-color: #ff000080;
  154. border: none;
  155. border-radius: 10px;
  156. transition: .2s ease all;
  157. }
  158.  
  159. #CFBetter_setting_menu .btn-close:hover {
  160. width: 2rem;
  161. height: 2rem;
  162. font-size: 1rem;
  163. color: #ffffff;
  164. background-color: #ff0000cc;
  165. box-shadow: 0 5px 5px 0 #00000026;
  166. }
  167.  
  168. #CFBetter_setting_menu .btn-close:active {
  169. width: .9rem;
  170. height: .9rem;
  171. font-size: .9rem;
  172. color: #ffffffde;
  173. --shadow-btn-close: 0 3px 3px 0 #00000026;
  174. box-shadow: var(--shadow-btn-close);
  175. }
  176.  
  177. /*设置面板-checkbox*/
  178. #CFBetter_setting_menu input[type=checkbox]:focus {
  179. outline: 0px;
  180. }
  181.  
  182. #CFBetter_setting_menu input[type="checkbox"] {
  183. margin: 0px;
  184. appearance: none;
  185. width: 48px;
  186. height: 24px;
  187. border: 2px solid #6b8092;
  188. border-radius: 20px;
  189. background: #f1e1e1;
  190. position: relative;
  191. box-sizing: border-box;
  192. }
  193.  
  194. #CFBetter_setting_menu input[type="checkbox"]::before {
  195. content: "";
  196. width: 16px;
  197. height: 16px;
  198. background: #6b80927a;
  199. border: 2px solid #6b8092;
  200. border-radius: 50%;
  201. position: absolute;
  202. top: 0;
  203. left: 0;
  204. transform: translate(0%, 0%);
  205. transition: all 0.3s ease-in-out;
  206. }
  207.  
  208. #CFBetter_setting_menu input[type="checkbox"]::after {
  209. content: url("data:image/svg+xml,%3Csvg xmlns='://www.w3.org/2000/svg' width='23' height='23' viewBox='0 0 23 23' fill='none'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M6.55021 5.84315L17.1568 16.4498L16.4497 17.1569L5.84311 6.55026L6.55021 5.84315Z' fill='%23EA0707' fill-opacity='0.89'/%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M17.1567 6.55021L6.55012 17.1568L5.84302 16.4497L16.4496 5.84311L17.1567 6.55021Z' fill='%23EA0707' fill-opacity='0.89'/%3E%3C/svg%3E");
  210. position: absolute;
  211. top: 0;
  212. left: 24px;
  213. }
  214.  
  215. #CFBetter_setting_menu input[type="checkbox"]:checked {
  216. border: 2px solid #02c202;
  217. background: #e2f1e1;
  218. }
  219.  
  220. #CFBetter_setting_menu input[type="checkbox"]:checked::before {
  221. background: rgba(2, 194, 2, 0.5);
  222. border: 2px solid #02c202;
  223. transform: translate(119%, 0%);
  224. transition: all 0.3s ease-in-out;
  225. }
  226.  
  227. #CFBetter_setting_menu input[type="checkbox"]:checked::after {
  228. content: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='15' height='13' viewBox='0 0 15 13' fill='none'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M14.8185 0.114533C15.0314 0.290403 15.0614 0.605559 14.8855 0.818454L5.00187 12.5L0.113036 6.81663C-0.0618274 6.60291 -0.0303263 6.2879 0.183396 6.11304C0.397119 5.93817 0.71213 5.96967 0.886994 6.18339L5.00187 11L14.1145 0.181573C14.2904 -0.0313222 14.6056 -0.0613371 14.8185 0.114533Z' fill='%2302C202' fill-opacity='0.9'/%3E%3C/svg%3E");
  229. position: absolute;
  230. top: 3px;
  231. left: 4px;
  232. }
  233.  
  234. #CFBetter_setting_menu input[type="checkbox"] + label {
  235. margin: 0px 0px 0px 10px !important;
  236. font-size: 16px;
  237. }
  238.  
  239. .CFBetter_setting_list {
  240. display: flex;
  241. align-items: center;
  242. margin-bottom: 18px;
  243. }
  244.  
  245. /*设置面板-radio*/
  246. #CFBetter_setting_menu>label {
  247. display: flex;
  248. list-style-type: none;
  249. padding-inline-start: 0px;
  250. overflow-x: auto;
  251. max-width: 100%;
  252. margin: 0px;
  253. align-items: center;
  254. margin: 3px 0px;
  255. }
  256.  
  257. .CFBetter_setting_menu_label_text {
  258. border: 1px dashed #00aeeccc;
  259. display: block;
  260. height: 20px;
  261. width: 100%;
  262. color: gray;
  263. font-weight: 300;
  264. font-size: 14px;
  265. letter-spacing: 2px;
  266. padding: 7px;
  267. }
  268.  
  269. input[type="radio"]:checked+.CFBetter_setting_menu_label_text {
  270. background: #41e49930;
  271. border: 1px solid green;
  272. color: green;
  273. font-weight: 500;
  274. }
  275.  
  276. #CFBetter_setting_menu>label input[type="radio"] {
  277. -webkit-appearance: none;
  278. appearance: none;
  279. list-style: none;
  280. margin: 0px;
  281. }
  282.  
  283. #CFBetter_setting_menu input[type="text"] {
  284. display: block;
  285. height: 25px;
  286. background-color: #ffffff;
  287. color: #727378;
  288. font-size: 10px;
  289. border-radius: 0.3rem;
  290. padding: 1px 5px;
  291. margin: 5px 0px 5px 0px;
  292. border: 1px solid #00aeeccc;
  293. box-shadow: 0 0 1px #0000004d;
  294. }
  295.  
  296. .CFBetter_setting_menu_input {
  297. width: 100%;
  298. display: grid;
  299. justify-content: start;
  300. }
  301.  
  302. #CFBetter_setting_menu #save {
  303. cursor: pointer;
  304. display: inline-flex;
  305. padding: 0.5rem 1rem;
  306. background-color: #1aa06d;
  307. color: #ffffff;
  308. font-size: 1rem;
  309. line-height: 1.5rem;
  310. font-weight: 500;
  311. justify-content: center;
  312. width: 100%;
  313. border-radius: 0.375rem;
  314. border: none;
  315. box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  316. }
  317.  
  318. #CFBetter_setting_menu span.tip {
  319. color: red;
  320. font-size: 2px;
  321. font-weight: 500;
  322. padding: 0px 0px 10px 0px;
  323. }
  324. /*更新检查*/
  325. div#update_panel {
  326. position: fixed;
  327. top: 50%;
  328. left: 50%;
  329. width: 240px;
  330. transform: translate(-50%, -50%);
  331. background-color: #fdfdfd;
  332. border: 1px solid #00aeeccc;
  333. border-radius: 5px;
  334. box-shadow: 2px 2px 3px 1px #0000004d;
  335. padding: 10px 20px 20px 20px;
  336. color: #444242;
  337. background-color: #ecf0ff;
  338. border: 6px solid #ffffff;
  339. border-radius: 16px;
  340. }
  341. div#update_panel #updating {
  342. cursor: pointer;
  343. display: inline-flex;
  344. padding: 0px;
  345. background-color: #1aa06d;
  346. color: #ffffff;
  347. font-size: 1rem;
  348. line-height: 1.5rem;
  349. font-weight: 500;
  350. justify-content: center;
  351. width: 100%;
  352. border-radius: 0.375rem;
  353. border: none;
  354. box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  355. }
  356. div#update_panel #updating a {
  357. text-decoration: none;
  358. color: white;
  359. display: flex;
  360. position: inherit;
  361. top: 0;
  362. left: 0;
  363. width: 100%;
  364. height: 22px;
  365. font-size: 14px;
  366. justify-content: center;
  367. align-items: center;
  368. }
  369. `);
  370.  
  371. // 更新检查
  372. (function checkScriptVersion() {
  373. function compareVersions(version1 = "0", version2 = "0") {
  374. const v1Array = String(version1).split(".");
  375. const v2Array = String(version2).split(".");
  376. const minLength = Math.min(v1Array.length, v2Array.length);
  377. let result = 0;
  378. for (let i = 0; i < minLength; i++) {
  379. const curV1 = Number(v1Array[i]);
  380. const curV2 = Number(v2Array[i]);
  381. if (curV1 > curV2) {
  382. result = 1;
  383. break;
  384. } else if (curV1 < curV2) {
  385. result = -1;
  386. break;
  387. }
  388. }
  389. if (result === 0 && v1Array.length !== v2Array.length) {
  390. const v1IsBigger = v1Array.length > v2Array.length;
  391. const maxLenArray = v1IsBigger ? v1Array : v2Array;
  392. for (let i = minLength; i < maxLenArray.length; i++) {
  393. const curVersion = Number(maxLenArray[i]);
  394. if (curVersion > 0) {
  395. v1IsBigger ? result = 1 : result = -1;
  396. break;
  397. }
  398. }
  399. }
  400. return result;
  401. }
  402.  
  403. GM_xmlhttpRequest({
  404. method: "GET",
  405. url: "https://greasyfork.org/zh-CN/scripts/465777.json",
  406. timeout: 10 * 1e3,
  407. onload: function (response) {
  408. const scriptData = JSON.parse(response.responseText);
  409. if (scriptData.name === GM_info.script.name && compareVersions(scriptData.version, GM_info.script.version) === 1) {
  410. $("body").append(`
  411. <div id='update_panel'>
  412. <h3>${GM_info.script.name}有新版本!</h3>
  413. <hr>
  414. <div class='update_panel_menu'>
  415. <span class ='tip'>版本信息:${GM_info.script.version} ${scriptData.version}</span>
  416. </div>
  417. <br>
  418. <button id='updating'><a target="_blank" href="${scriptData.url}">更新</a></button>
  419. </div>
  420. `);
  421. }
  422. }
  423. });
  424. })();
  425.  
  426. // 汉化替换
  427. (function () {
  428. if (getCookie("bottomZh_CN") === '') setCookie("bottomZh_CN", "true", 3650);
  429. if (getCookie("bottomZh_CN") != "true") return;
  430. // 设置语言为zh
  431. var htmlTag = document.getElementsByTagName("html")[0];
  432. htmlTag.setAttribute("lang", "zh-CN");
  433.  
  434. // 暴力html替换
  435. const classData = {
  436. '.menu-list.main-menu-list': [
  437. { match: 'Help', replace: '帮助' },
  438. { match: 'Calendar', replace: '日历' },
  439. { match: 'Edu', replace: '培训' },
  440. { match: 'Rating', replace: '积分榜' },
  441. { match: 'Groups', replace: '团体' },
  442. { match: 'Problemset', replace: '题单' },
  443. { match: 'Gym', replace: '训练营(过去的大型比赛)' },
  444. { match: 'Contests', replace: '比赛' },
  445. { match: 'Catalog', replace: '指南目录' },
  446. { match: 'Top', replace: '热门' },
  447. { match: 'Home', replace: '主页' },
  448. ],
  449. '.personal-sidebar ': [
  450. { match: 'Contribution', replace: '贡献' },
  451. { match: 'Settings', replace: '设置' },
  452. { match: 'Blog', replace: '博客' },
  453. { match: 'Teams', replace: '队伍' },
  454. { match: 'Submissions', replace: '提交' },
  455. { match: 'Favourites', replace: '收藏' },
  456. { match: 'Talks', replace: '私信' },
  457. { match: 'Contests', replace: '比赛' },
  458. ],
  459. '.contest-state-phase': [
  460. { match: 'Before contest', replace: '即将进行的比赛' },
  461. { match: 'Contest is running', replace: '比赛进行中' },
  462. ],
  463. '.notice': [
  464. { match: 'has extra registration', replace: '有额外的报名时期' },
  465. { match: 'If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes.', replace: '如果您在比赛开始前5分钟前还未报名,您可以在额外的报名期间稍后报名。额外的报名将在比赛开始后10分钟开放,并持续25分钟。' },
  466. ],
  467. '.act-item': [
  468. { match: 'Submit', replace: '提交' },
  469. ],
  470. '.datatable': [
  471. { match: 'Virtual participation', replace: '参加虚拟重现赛' },
  472. { match: 'Enter', replace: '进入' },
  473. { match: 'Current standings', replace: '当前榜单' },
  474. { match: 'Final standings', replace: '榜单' },
  475. { match: 'School/University/City/Region Championship', replace: '学校/大学/城市/区域比赛' },
  476. { match: 'Official School Contest', replace: '学校官方比赛' },
  477. { match: 'Training Contest', replace: '训练赛' },
  478. { match: 'Training Camp Contest', replace: '训练营比赛' },
  479. { match: 'Official ICPC Contest', replace: 'ICPC官方比赛' },
  480. { match: 'Official International Personal Contest', replace: '官方国际个人赛' },
  481. { match: 'China', replace: '中国' },
  482. { match: 'Statements', replace: '题目描述' },
  483. { match: 'in Chinese', replace: '中文' },
  484. { match: 'Trainings', replace: '训练' },
  485. { match: 'Prepared by', replace: '编写人' },
  486. { match: 'Current or upcoming contests', replace: '当前或即将举行的比赛' },
  487. { match: 'Past contests', replace: '过去的比赛' },
  488. { match: 'Exclusions', replace: '排除' },
  489. { match: 'Before start', replace: '还有' },
  490. { match: 'Before registration', replace: '报名还有' },
  491. { match: 'Until closing ', replace: '结束报名' },
  492. { match: 'Register', replace: '报名' },
  493. { match: 'Registration completed', replace: '已报名' },
  494. ],
  495. '.contests-table': [
  496. { match: 'Contest history', replace: '比赛历史' },
  497. ],
  498. '.roundbox.sidebox.borderTopRound ': [
  499. { match: 'Register now', replace: '现在报名' },
  500. ],
  501. '.icon-eye-close.icon-large': [
  502. { match: 'Add to exclusions', replace: '添加到排除列表' },
  503. ],
  504. '._ContestFilterExclusionsManageFrame_addExclusionLink': [
  505. { match: 'Add to exclusions for gym contests filter', replace: '添加训练营过滤器的排除项' },
  506. ],
  507. '.roundbox.sidebox.sidebar-menu.borderTopRound ': [
  508. { match: 'Announcement', replace: '公告' },
  509. { match: 'Statements', replace: '统计报表' },
  510. { match: 'Tutorial', replace: '题解' },
  511. ],
  512. '.second-level-menu ': [
  513. { match: 'Problems', replace: '问题' },
  514. { match: 'Submit Code', replace: '提交代码' },
  515. { match: 'My Submissions', replace: '我的提交' },
  516. { match: 'Status', replace: '状态' },
  517. { match: 'Standings', replace: '榜单' },
  518. { match: 'Custom Invocation', replace: '自定义调试' },
  519. { match: 'Common standings', replace: '全部排行' },
  520. { match: 'Friends standings', replace: '只看朋友' },
  521. { match: 'Submit', replace: '提交' },
  522. { match: 'Custom test', replace: '自定义测试' },
  523. { match: 'Blog', replace: '博客' },
  524. { match: 'Teams', replace: '队伍' },
  525. { match: 'Submissions', replace: '提交' },
  526. { match: 'Groups', replace: '团体' },
  527. { match: 'Favourites', replace: '收藏' },
  528. { match: 'Contests', replace: '比赛' },
  529. { match: '问题etting', replace: '参与编写的问题' },
  530. { match: 'Gym', replace: '训练营' },
  531. { match: 'Mashups', replace: '组合混搭' },
  532. { match: 'Posts', replace: '帖子' },
  533. { match: '>Comments<', replace: '>回复<' },
  534. { match: 'Main', replace: '主要' },
  535. { match: 'Settings', replace: '设置' },
  536. { match: 'Lists', replace: '列表' },
  537. ],
  538. '.topic-toggle-collapse': [
  539. { match: 'Expand', replace: '展开' },
  540. ],
  541. '.topic-read-more': [
  542. { match: 'Full text and comments', replace: '阅读全文/评论' },
  543. ],
  544. '.toggleEditorCheckboxLabel': [
  545. { match: 'Switch off editor', replace: '关闭编辑器语法高亮' },
  546. ],
  547. '.submit': [
  548. { match: 'Registration for the contest', replace: '比赛报名' },
  549. ],
  550. };
  551. for (const className in classData) {
  552. const elements = document.querySelectorAll(className);
  553. elements.forEach((element) => {
  554. let html = element.outerHTML;
  555. const parent = element.parentNode;
  556. const childIndex = Array.from(parent.children).indexOf(element);
  557. let matched = false;
  558. classData[className].forEach((rule) => {
  559. if (html.match(new RegExp(rule.match, 'g'))) {
  560. matched = true;
  561. html = html.replace(new RegExp(rule.match, 'g'), rule.replace);
  562. const temp = document.createElement('div');
  563. temp.innerHTML = html.trim();
  564. const newElement = element.cloneNode(true);
  565. newElement.innerHTML = temp.firstChild.innerHTML;
  566. parent.replaceChild(newElement, parent.children[childIndex]);
  567. }
  568. });
  569. });
  570. }
  571.  
  572. // 元素选择替换
  573. // 侧栏titled汉化
  574. (function () {
  575. var translations = {
  576. "Pay attention": "→ 注意",
  577. "Top rated": "→ 积分排行",
  578. "Top contributors": "→ 贡献者排行",
  579. "Find user": "→ 查找用户",
  580. "Recent actions": "→ 最近热帖",
  581. "Training filter": "→ 过滤筛选",
  582. "Find training": "→ 搜索比赛/问题",
  583. "Virtual participation": "→ 什么是虚拟参赛",
  584. "Contest materials": "→ 比赛相关资料",
  585. "Settings": "→ 设置",
  586. "Clone Contest to Mashup": "→ Clone比赛到组合混搭",
  587. "Submit": "→ 提交",
  588. "Practice": "→ 练习",
  589. "Problem tags": "→ 问题标签",
  590. "Filter Problems": "→ 过滤问题",
  591. "Attention": "→ 注意",
  592. "About Contest": "→ 关于比赛",
  593. "Last submissions": "→ 上次提交",
  594. "Streams": "→ 直播",
  595. };
  596.  
  597. $(".caption.titled").each(function () {
  598. var tag = $(this).text();
  599. for (var property in translations) {
  600. if (tag.match(property)) {
  601. $(this).addClass(property);
  602. $(this).text(translations[property]);
  603. break;
  604. }
  605. }
  606. });
  607. })();
  608. // 题目Tag汉化
  609. (function () {
  610. var parentElement = $('._FilterByTagsFrame_addTagLabel');
  611. var selectElement = parentElement.find('select');
  612. var translations = {
  613. "*combine tags by OR": "*按逻辑或组合我选择的标签",
  614. "combine-tags-by-or": "*按逻辑或组合我选择的标签(combine-tags-by-or)",
  615. "2-sat": "二分图可满足性问题(2-sat)",
  616. "binary search": "二分搜索(binary search)",
  617. "bitmasks": "位掩码(bitmasks)",
  618. "brute force": "暴力枚举(brute force)",
  619. "chinese remainder theorem": "中国剩余定理(chinese remainder theorem)",
  620. "combinatorics": "组合数学(combinatorics)",
  621. "constructive algorithms": "构造算法(constructive algorithms)",
  622. "data structures": "数据结构(data structures)",
  623. "dfs and similar": "深度优先搜索及其变种(dfs and similar)",
  624. "divide and conquer": "分治算法(divide and conquer)",
  625. "dp": "动态规划(dp)",
  626. "dsu": "并查集(dsu)",
  627. "expression parsing": "表达式解析(expression parsing)",
  628. "fft": "快速傅里叶变换(fft)",
  629. "flows": "流(flows)",
  630. "games": "博弈论(games)",
  631. "geometry": "计算几何(geometry)",
  632. "graph matchings": "图匹配(graph matchings)",
  633. "graphs": "图论(graphs)",
  634. "greedy": "贪心策略(greedy)",
  635. "hashing": "哈希表(hashing)",
  636. "implementation": "实现问题,编程技巧,模拟(implementation)",
  637. "interactive": "交互性问题(interactive)",
  638. "math": "数学(math)",
  639. "matrices": "矩阵(matrices)",
  640. "meet-in-the-middle": "meet-in-the-middle算法(meet-in-the-middle)",
  641. "number theory": "数论(number theory)",
  642. "probabilities": "概率论(probabilities)",
  643. "schedules": "调度算法(schedules)",
  644. "shortest paths": "最短路算法(shortest paths)",
  645. "sortings": "排序算法(sortings)",
  646. "string suffix structures": "字符串后缀结构(string suffix structures)",
  647. "strings": "字符串处理(strings)",
  648. "ternary search": "三分搜索(ternary search)",
  649. "trees": "树形结构(trees)",
  650. "two pointers": "双指针算法(two pointers)"
  651. };
  652. selectElement.find("option").each(function () {
  653. var optionValue = $(this).val();
  654. if (translations[optionValue]) {
  655. $(this).text(translations[optionValue]);
  656. }
  657. });
  658. $("._FilterByTagsFrame_tagBoxCaption").each(function () {
  659. var tag = $(this).text();
  660. if (tag in translations) {
  661. $(this).text(translations[tag]);
  662. }
  663. });
  664. $(".notice").each(function () {
  665. var tag = $(this).text();
  666. if (tag in translations) {
  667. $(this).text(translations[tag]);
  668. }
  669. });
  670. $(".tag-box").each(function () {
  671. var tag = $(this).text();
  672. for (var property in translations) {
  673. property = property.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
  674. if (tag.match(property)) {
  675. $(this).text(translations[property]);
  676. break;
  677. }
  678. }
  679. });
  680. })();
  681. // 题目过滤器选项汉化
  682. (function () {
  683. var parentElement = $('#gym-filter-form');
  684. var selectElement = parentElement.find('div');
  685. var translations = {
  686. "Contest type:": "比赛类型:",
  687. "ICPC region:": "ICPC地区:",
  688. "Contest format:": "比赛形式:",
  689. "Order by:": "排序方式:",
  690. "Secondary order by:": "次要排序方式:",
  691. "Hide, if participated:": "隐藏我参加过的:",
  692. };
  693. selectElement.find("label").each(function () {
  694. var optionValue = $(this).text();
  695. if (translations[optionValue]) {
  696. $(this).text(translations[optionValue]);
  697. }
  698. });
  699. translations = {
  700. "Season:": "时间范围(年度)",
  701. "Duration, hours:": "持续时间(小时):",
  702. "Difficulty:": "难度:"
  703. };
  704. selectElement.each(function () {
  705. var optionValue = $(this).text();
  706. if (translations[optionValue]) {
  707. $(this).text(translations[optionValue]);
  708. }
  709. });
  710. })();
  711. (function () {
  712. var parentElement = $('.setting-value');
  713. var selectElement = parentElement.find('select');
  714. var translations = {
  715. "Official ACM-ICPC Contest": "ICPC官方比赛",
  716. "Official School Contest": "学校官方比赛",
  717. "Opencup Contest": "Opencup比赛",
  718. "School/University/City/Region Championship": "学校/大学/城市/地区锦标赛",
  719. "Training Camp Contest": "训练营比赛",
  720. "Official International Personal Contest": "官方国际个人赛",
  721. "Training Contest": "训练比赛",
  722. "ID_ASC": "创建时间(升序)",
  723. "ID_DESC": "创建时间(降序)",
  724. "RATING_ASC": "评分(升序)",
  725. "RATING_DESC": "评分(降序)",
  726. "DIFFICULTY_ASC": "难度(升序)",
  727. "DIFFICULTY_DESC": "难度(降序)",
  728. "START_TIME_ASC": "开始时间(升序)",
  729. "START_TIME_DESC": "开始时间(降序)",
  730. "DURATION_ASC": "持续时间(升序)",
  731. "DURATION_DESC": "持续时间(降序)",
  732. "POPULARITY_ASC": "热度(升序)",
  733. "POPULARITY_DESC": "热度(降序)",
  734. "UPDATE_TIME_ASC": "更新时间(升序)",
  735. "UPDATE_TIME_DESC": "更新时间(降序)"
  736. };
  737. selectElement.find("option").each(function () {
  738. var optionValue = $(this).val();
  739. if (translations[optionValue]) {
  740. $(this).text(translations[optionValue]);
  741. }
  742. });
  743. parentElement = $('.setting-last-value');
  744. selectElement = parentElement.find('select');
  745. selectElement.find("option").each(function () {
  746. var optionValue = $(this).val();
  747. if (translations[optionValue]) {
  748. $(this).text(translations[optionValue]);
  749. }
  750. });
  751. })();
  752. // 右侧sidebox通用汉化
  753. (function () {
  754. var parentElement = $('.sidebox');
  755. var selectElement = parentElement.find('div');
  756. var translations = {
  757. "Show tags for unsolved problems": "显示未解决问题的标签",
  758. "Hide solved problems": "隐藏已解决的问题",
  759. };
  760. selectElement.find("label").each(function () {
  761. var optionValue = $(this).text();
  762. if (translations[optionValue]) {
  763. $(this).text(translations[optionValue]);
  764. }
  765. });
  766. })();
  767. // 题目提交/报名页汉化
  768. (function () {
  769. var translations = {
  770. "Problem:": "题目:",
  771. "Language:": "语言:",
  772. "Source code:": "源代码:",
  773. "Or choose file:": "或者选择文件:",
  774. "Choose file:": "选择文件:",
  775. "Notice:": "注意:",
  776. "virtual participation:": "虚拟参与:",
  777. "Registration for the contest:": "比赛报名:",
  778. "Terms of agreement:": "协议条款:",
  779. "Take part:": "参与:",
  780. "as individual participant:": "作为个人参与者:",
  781. "as a team member:": "作为团队成员:",
  782. "Virtual start time:": "虚拟开始时间:",
  783. "Complete problemset:": "完整的问题集:",
  784. "Question:": "问题:"
  785. };
  786. $(".field-name").each(function () {
  787. var optionValue = $(this).text();
  788. if (translations[optionValue]) {
  789. $(this).text(translations[optionValue]);
  790. }
  791. });
  792. })();
  793. // 按钮汉化
  794. (function () {
  795. var translations = {
  796. "Register for virtual participation": "报名虚拟参赛"
  797. };
  798. $(".submit").each(function () {
  799. var optionValue = $(this).val();
  800. if (translations[optionValue]) {
  801. $(this).val(translations[optionValue]);
  802. }
  803. });
  804. })();
  805. // 杂项汉化
  806. (function () {
  807. var translations = {
  808. "(standard input\/output)": "标准输入/输出",
  809. };
  810. $("div.notice").each(function () {
  811. var tag = $(this).children().eq(0).text();
  812. for (var property in translations) {
  813. if (tag.match(property)) {
  814. $(this).children().eq(0).text(translations[property]);
  815. break;
  816. }
  817. }
  818. });
  819. })();
  820. (function () {
  821. var translations = {
  822. "Ask a question": "提一个问题",
  823. };
  824. $(".ask-question-link").each(function () {
  825. var optionValue = $(this).text();
  826. if (translations[optionValue]) {
  827. $(this).text(translations[optionValue]);
  828. }
  829. });
  830. })();
  831. })();
  832.  
  833. // 设置面板
  834.  
  835. $("div[class='lang-chooser']").each(function () {
  836. $(this).before(
  837. "<button class='html2mdButton CFBetter_setting'>CodeforcesBetter设置</button>"
  838. );
  839. });
  840. $(document).ready(function () {
  841. $(".CFBetter_setting").click(function () {
  842. $(".CFBetter_setting").attr("disabled", true);
  843. $(".CFBetter_setting").css("background-color", "#e6e6e6");
  844. $(".CFBetter_setting").css("color", "#727378");
  845. $(".CFBetter_setting").css("cursor", "not-allowed");
  846. $("body").append(`
  847. <div id='CFBetter_setting_menu'>
  848. <div class="tool-box">
  849. <button class="btn-close">×</button>
  850. </div>
  851. <h3>基本设置</h3>
  852. <hr>
  853. <div class='CFBetter_setting_list'>
  854. <input type="checkbox" id="bottomZh_CN" name="bottomZh_CN" checked>
  855. <label for="bottomZh_CN">界面汉化</label>
  856. </div>
  857. <h3>翻译设置</h3>
  858. <hr>
  859. <label>
  860. <input type='radio' name='translation' value='deepl'>
  861. <span class='CFBetter_setting_menu_label_text'>deepl翻译</span>
  862. </label>
  863. <label>
  864. <input type='radio' name='translation' value='youdao'>
  865. <span class='CFBetter_setting_menu_label_text'>有道翻译</span>
  866. </label>
  867. <label>
  868. <input type='radio' name='translation' value='openai'>
  869. <span class='CFBetter_setting_menu_label_text'>使用ChatGPT翻译(API)</span>
  870. </label>
  871. <label>
  872. <input type='radio' name='translation' value='api2d'>
  873. <span class='CFBetter_setting_menu_label_text'>使用api2d翻译(API)</span>
  874. </label><br>
  875. <div class='CFBetter_setting_menu_input' id='baidu' style='display: none;'>
  876. <label for='baidu_uid'>APP ID:</label><input type='text' id='baidu_uid'>
  877. <label for='baidu_key'>KEY:</label><input type='text' id='baidu_key'>
  878. </div>
  879. <div class='CFBetter_setting_menu_input' id='openai' style='display: none;'>
  880. <span class ='tip'>提示:<br>请确保你能够正常访问OpenAIapi<br></span>
  881. <span class ='tip'>使用ChatGPT-3.5进行翻译,脚本的所有请求均在本地完成,</span>
  882. <span class ='tip'>你需要输入自己的OpenAI KEY,<a target="_blank" href="https://platform.openai.com/account/usage">官网</a></span>
  883. <label for='openai_key'>KEY:</label><input type='text' id='openai_key'>
  884. </div>
  885. <div class='CFBetter_setting_menu_input' id='api2d' style='display: none;'>
  886. <span class ='tip'>提示:<br>api2d是国内的一家提供代理直连访问OpenAIapi的服务商,相当于OpenAIapi的套壳<br></span>
  887. <span class ='tip'>使用ChatGPT-3.5进行翻译,脚本的所有请求均在本地完成<br></span>
  888. <span class ='tip'>你需要输入自己的api2d KEY,<a target="_blank" href="https://api2d.com/profile">官网</a></span>
  889. <label for='api2d_key'>KEY:</label><input type='text' id='api2d_key'>
  890. </div>
  891. <br>
  892. <button id='save'>保存</button>
  893. </div>
  894. `);
  895. var translation = getCookie("translation");
  896. $("#bottomZh_CN").prop("checked", getCookie("bottomZh_CN") === "true");
  897. if (translation === 'undefined' || translation === '') {
  898. setCookie("translation", "deepl", 3650);
  899. $("input[name='translation'][value='deepl']").prop("checked", true);
  900. } else {
  901. $("input[name='translation'][value='" + translation + "']").prop("checked", true);
  902. $("input[name='translation']").css("color", "gray");
  903. if (translation == "baidu") {
  904. $("#baidu").show();
  905. $("#baidu_uid").val(getCookie("baidu_uid"));
  906. $("#baidu_key").val(getCookie("baidu_key"));
  907. $("#baidu_uid").css("color", "gray");
  908. $("#baidu_key").css("color", "gray");
  909. } else if (translation == "openai") {
  910. $("#openai").show();
  911. $("#openai_key").val(getCookie("openai_key"));
  912. $("#openai_key").css("color", "gray");
  913. } else if (translation == "api2d") {
  914. $("#api2d").show();
  915. $("#api2d_key").val(getCookie("api2d_key"));
  916. $("#api2d_key").css("color", "gray");
  917. }
  918. }
  919.  
  920. // 当单选框被选中时,显示对应的输入框,同时隐藏其他输入框
  921. $("input[name='translation']").change(function () {
  922. var selected = $(this).val(); // 获取当前选中的值
  923. if (selected === 'baidu') {
  924. $("#baidu").show();
  925. $("#baidu_uid").val(getCookie("baidu_uid"));
  926. $("#baidu_key").val(getCookie("baidu_key"));
  927. $("#openai, #api2d").hide();
  928. } else if (selected === 'openai') {
  929. $("#openai").show();
  930. $("#openai_key").val(getCookie("openai_key"));
  931. $("#baidu, #api2d").hide();
  932. } else if (selected === 'api2d') {
  933. $("#api2d").show();
  934. $("#api2d_key").val(getCookie("api2d_key"));
  935. $("#baidu, #openai").hide();
  936. } else {
  937. $("#baidu, #openai, #api2d").hide();
  938. }
  939. });
  940.  
  941. $("#save").click(function () {
  942. var translation = $("input[name='translation']:checked").val();
  943. var baidu_uid = $("#baidu_uid").val();
  944. var baidu_key = $("#baidu_key").val();
  945. var openai_key = $("#openai_key").val();
  946. var api2d_key = $("#api2d_key").val();
  947. setCookie("translation", translation, 3650);
  948. if (translation == "baidu") {
  949. setCookie("baidu_uid", baidu_uid, 3650);
  950. setCookie("baidu_key", baidu_key, 3650);
  951. } else if (translation == "openai") {
  952. setCookie("openai_key", openai_key, 3650);
  953. } else if (translation == "api2d") {
  954. setCookie("api2d_key", api2d_key, 3650);
  955. }
  956. setCookie("bottomZh_CN", $("#bottomZh_CN").prop("checked"), 3650);
  957. location.reload();
  958. /* 切换汉化
  959. if(JSON.parse(getCookie("bottomZh_CN")) != $("#bottomZh_CN").prop("checked")){
  960. setCookie("bottomZh_CN", $("#bottomZh_CN").prop("checked"), 3650);
  961. location.reload();
  962. }else{
  963. $("#CFBetter_setting_menu .btn-close").click();
  964. }*/
  965. });
  966. // 关闭
  967. $("#CFBetter_setting_menu .btn-close").click(function () {
  968. $("#CFBetter_setting_menu").remove();
  969. $(".CFBetter_setting").attr("disabled", false);
  970. $(".CFBetter_setting").css("background-color", "#60a5fa");
  971. $(".CFBetter_setting").css("color", "white");
  972. $(".CFBetter_setting").css("cursor", "pointer");
  973. });
  974. });
  975. });
  976.  
  977. // 是否为旧的latex渲染
  978. var is_oldLatex = false;
  979. if ($('.tex-span').length) {
  980. is_oldLatex = true;
  981. var newElement = $("<div></div>").addClass("alert alert-warning").html(`
  982. 注意:当前页面存在使用非 MathJax 库渲染为 HTML Latex 公式(这通常是一道古老的题目),这导致 CodeforcesBetter 无法将其还原回 Latex,因此当前页面部分功能不适用。
  983. <br>此外当前页面的翻译功能采用了特别的实现方式,因此可能会出现排版错位的情况。
  984. `).css({
  985. "margin": "1em",
  986. "text-align": "center",
  987. "position": "relative"
  988. });
  989. $(".menu-box:first").next().after(newElement);
  990. }
  991.  
  992. // md2html转换/处理规则
  993. var turndownService = new TurndownService({bulletListMarker: '-'});
  994. var turndown = turndownService.turndown;
  995.  
  996. // 保留原始
  997. turndownService.keep(['del']);
  998.  
  999. // 丢弃
  1000. turndownService.addRule('ignore-sample-tests', {
  1001. filter: function (node) {
  1002. return node.classList.contains('sample-tests') || node.classList.contains('header');
  1003. },
  1004. replacement: function (content, node) {
  1005. return "";
  1006. }
  1007. });
  1008. turndownService.addRule('remove-script', {
  1009. filter: function (node, options) {
  1010. return node.tagName.toLowerCase() == "script" && node.type.startsWith("math/tex");
  1011. },
  1012. replacement: function (content, node) {
  1013. return "";
  1014. }
  1015. });
  1016.  
  1017. // inline math
  1018. turndownService.addRule('inline-math', {
  1019. filter: function (node, options) {
  1020. return node.tagName.toLowerCase() == "span" && node.className == "MathJax";
  1021. },
  1022. replacement: function (content, node) {
  1023. return "$ " + $(node).next().text() + " $";
  1024. }
  1025. });
  1026.  
  1027. // block math
  1028. turndownService.addRule('block-math', {
  1029. filter: function (node, options) {
  1030. return node.tagName.toLowerCase() == "div" && node.className == "MathJax_Display";
  1031. },
  1032. replacement: function (content, node) {
  1033. return "\n$$\n" + $(node).next().text() + "\n$$\n";
  1034. }
  1035. });
  1036.  
  1037. // 表格
  1038. turndownService.addRule('bordertable', {
  1039. filter: 'table',
  1040. replacement: function (content, node) {
  1041. if (node.classList.contains('bordertable')) {
  1042. var output = [],
  1043. thead = '',
  1044. trs = node.querySelectorAll('tr');
  1045. if (trs.length > 0) {
  1046. var ths = trs[0].querySelectorAll('th');
  1047. if (ths.length > 0) {
  1048. thead = '| ' + Array.from(ths).map(th => turndownService.turndown(th.innerHTML.trim())).join(' | ') + ' |\n'
  1049. + '| ' + Array.from(ths).map(() => ' --- ').join('|') + ' |\n';
  1050. }
  1051. }
  1052. var rows = node.querySelectorAll('tr');
  1053. Array.from(rows).forEach(function (row, i) {
  1054. if (i > 0) {
  1055. var cells = row.querySelectorAll('td,th');
  1056. var trow = '| ' + Array.from(cells).map(cell => turndownService.turndown(cell.innerHTML.trim())).join(' | ') + ' |';
  1057. output.push(trow);
  1058. }
  1059. });
  1060. return thead + output.join('\n');
  1061. } else {
  1062. return content;
  1063. }
  1064. }
  1065. });
  1066.  
  1067. // 题目markdown转换/翻译面板
  1068. function addButtonPanel(parent, suffix, type, is_simple = false) {
  1069. if (type === "upper_level_2" || type === "problem") {
  1070. $(parent).children(':eq(1)').before(
  1071. "<div class='html2md-panel'> <button class='html2mdButton html2md-view" + suffix + "'>MarkDown视图</button> <button class='html2mdButton html2md-cb" + suffix + "'>Copy</button> <button class='html2mdButton translateButton" + suffix + "'>翻译</button> </div>");
  1072. } else if (is_simple) {
  1073. $(parent).before(
  1074. "<div class='html2md-panel'><button class='html2mdButton translateButton" + suffix + "'>翻译</button> </div>");
  1075. } else {
  1076. $(parent).before(
  1077. "<div class='html2md-panel'> <button class='html2mdButton html2md-view" + suffix + "'>MarkDown视图</button> <button class='html2mdButton html2md-cb" + suffix + "'>Copy</button> <button class='html2mdButton translateButton" + suffix + "'>翻译</button> </div>");
  1078. }
  1079. }
  1080. function addButtonWithHTML2MD(parent, suffix, type) {
  1081. if(is_oldLatex){
  1082. $(".html2md-view" + suffix).css({
  1083. "cursor": "not-allowed",
  1084. "background-color": "#e6e6e638",
  1085. "color": "#72737896",
  1086. });
  1087. $(".html2md-view" + suffix).prop("disabled", true);
  1088. }
  1089. $(".html2md-view" + suffix).click(function () {
  1090. var target, removedChildren;
  1091. if (type === "problem") {
  1092. target = $(parent).children().next().next().get(0);
  1093. } else if (type === "problem_QA") {
  1094. target = $(this).parent().parent().get(0);
  1095. removedChildren = $(this).parent().parent().children().eq(0).detach();
  1096. } else if (type === "upper_level_2") {
  1097. target = parent;
  1098. removedChildren = $(parent).children().slice(0, 2).detach();
  1099. } else {
  1100. target = parent;
  1101. }
  1102. if (target.viewmd) {
  1103. target.viewmd = false;
  1104. $(this).text("MarkDown视图");
  1105. $(this).removeClass("mdViewed");
  1106. $(target).html(target.original_html);
  1107. } else {
  1108. target.viewmd = true;
  1109. if (!target.original_html) {
  1110. target.original_html = $(target).html();
  1111. }
  1112. if (!target.markdown) {
  1113. target.markdown = turndownService.turndown($(target).html());
  1114. }
  1115. $(this).text("原始内容");
  1116. $(this).addClass("mdViewed");
  1117. $(target).html(`<span class="mdViewContent" oninput="$(this).parent().get(0).markdown=this.value;" style="width:auto; height:auto;">${target.markdown}</span>`);
  1118. }
  1119. // 恢复删除的元素
  1120. if (type === "problem_QA" || type === "upper_level_2") $(target).prepend(removedChildren);
  1121. });
  1122. }
  1123.  
  1124. function addButtonWithCopy(parent, suffix, type) {
  1125. if(is_oldLatex){
  1126. $(".html2md-cb" + suffix).css({
  1127. "cursor": "not-allowed",
  1128. "background-color": "#e6e6e638",
  1129. "color": "#72737896",
  1130. });
  1131. $(".html2md-cb" + suffix).prop("disabled", true);
  1132. }
  1133. $(".html2md-cb" + suffix).click(function () {
  1134. var target, removedChildren;
  1135. if (type === "problem") {
  1136. target = $($(parent).children().next().next().get(0)).clone();
  1137. } else if (type === "problem_QA") {
  1138. target = $(this).parent().parent().eq(0).clone();
  1139. $(target).children(':first').remove();
  1140. } else if (type === "upper_level_2") {
  1141. target = $(parent).clone();
  1142. $(target).children(':first').remove(); // 删除前两个元素(标题和按钮面板)
  1143. $(target).children(':first').remove();
  1144. } else {
  1145. target = $(parent).clone();
  1146. }
  1147. if (!target.markdown) {
  1148. target.markdown = turndownService.turndown($(target).html());
  1149. }
  1150. const textarea = document.createElement('textarea');
  1151. textarea.value = target.markdown;
  1152. document.body.appendChild(textarea);
  1153. textarea.select();
  1154. document.execCommand('copy');
  1155. document.body.removeChild(textarea);
  1156. $(this).addClass("copied");
  1157. $(this).text("Copied");
  1158. // 更新复制按钮文本
  1159. setTimeout(() => {
  1160. $(this).removeClass("copied");
  1161. $(this).text("Copy");
  1162. }, 2000);
  1163. $(target).remove();
  1164. });
  1165. }
  1166.  
  1167. function addButtonWithTranslation(parent, suffix, type) {
  1168. $(".translateButton" + suffix).click(async function () {
  1169. var target, removedChildren;
  1170. if (type === "problem") {
  1171. target = $($(parent).children().next().next().get(0)).clone();
  1172. } else if (type === "problem_QA") {
  1173. target = $(this).parent().parent().eq(0).clone();
  1174. $(target).children(':first').remove();
  1175. } else if (type === "upper_level_2") {
  1176. target = $(parent).clone();
  1177. $(target).children(':first').remove(); // 删除前两个元素(标题和按钮面板)
  1178. $(target).children(':first').remove();
  1179. } else {
  1180. target = $(parent).clone();
  1181. }
  1182. if (is_oldLatex) {
  1183. target.markdown = $(target).html();
  1184. } else if (!target.markdown) {
  1185. target.markdown = turndownService.turndown($(target).html());
  1186. }
  1187. const textarea = document.createElement('textarea');
  1188. textarea.value = target.markdown;
  1189. // 翻译处理
  1190. $(this).removeClass("translated");
  1191. $(this).text("翻译中");
  1192. $(this).css("cursor", "not-allowed");
  1193. var element_node;
  1194. if (type === "problem") {
  1195. element_node = $(parent).children()[2]; // 题面特殊处理
  1196. } else if (type === "problem_QA") {
  1197. element_node = $(parent).children().last().get(0);
  1198. } else {
  1199. element_node = parent;
  1200. }
  1201. var translateDiv = await translateProblemStatement(textarea.value, element_node);
  1202. //
  1203. $(this).addClass("translated");
  1204. $(this).text("已翻译");
  1205. $(this).prop("disabled", true);
  1206. $(target).remove();
  1207. // 重新翻译
  1208. if ($(this).next('.reTranslation').length === 0) {
  1209. const reTranslateBtn = $('<button>').addClass('html2mdButton reTranslation').html('&circlearrowright;').attr('title', '重新翻译');
  1210. reTranslateBtn.on('click', function() {
  1211. $(translateDiv).remove();
  1212. $(this).prev().click();
  1213. });
  1214. $(this).after(reTranslateBtn);
  1215. }else {
  1216. const reTranslateBtn = $(this).next('.reTranslation');
  1217. reTranslateBtn.off('click').on('click', function() {
  1218. $(translateDiv).remove();
  1219. $(this).prev().click();
  1220. });
  1221. }
  1222. });
  1223. }
  1224.  
  1225.  
  1226. window.onload = function () {
  1227. // 添加按钮到题面部分
  1228. $("div[class='problem-statement']").each(function () {
  1229. var problem_id = "_comment_" + getRandomNumber(8);
  1230. addButtonPanel(this, problem_id, "problem");
  1231. addButtonWithHTML2MD(this, problem_id, "problem");
  1232. addButtonWithCopy(this, problem_id, "problem");
  1233. addButtonWithTranslation(this, problem_id, "problem");
  1234. });
  1235.  
  1236. // 添加按钮到input部分
  1237. $("div[class='input-specification']").each(function () {
  1238. var id = "_" + getRandomNumber(8);
  1239. addButtonPanel(this, id, "upper_level_2");
  1240. addButtonWithHTML2MD(this, id, "upper_level_2");
  1241. addButtonWithCopy(this, id, "upper_level_2");
  1242. addButtonWithTranslation(this, id, "upper_level_2");
  1243. });
  1244.  
  1245. // 添加按钮到output部分
  1246. $("div[class='output-specification']").each(function () {
  1247. var id = "_" + getRandomNumber(8);
  1248. addButtonPanel(this, id, "upper_level_2");
  1249. addButtonWithHTML2MD(this, id, "upper_level_2");
  1250. addButtonWithCopy(this, id, "upper_level_2");
  1251. addButtonWithTranslation(this, id, "upper_level_2");
  1252. });
  1253.  
  1254. // 添加按钮到note部分
  1255. $("div[class='note']").each(function () {
  1256. var id = "_" + getRandomNumber(8);
  1257. addButtonPanel(this, id, "upper_level_2");
  1258. addButtonWithHTML2MD(this, id, "upper_level_2");
  1259. addButtonWithCopy(this, id, "upper_level_2");
  1260. addButtonWithTranslation(this, id, "upper_level_2");
  1261. });
  1262.  
  1263. // 添加按钮到ttypography部分
  1264. $(".ttypography").each(function () {
  1265. // 题目页特判
  1266. if (!$(this).parent().hasClass('problemindexholder')) {
  1267. var comment_id = "_comment_" + getRandomNumber(8);
  1268. addButtonPanel(this, comment_id, "this_level");
  1269. addButtonWithHTML2MD(this, comment_id, "this_level");
  1270. addButtonWithCopy(this, comment_id, "this_level");
  1271. addButtonWithTranslation(this, comment_id, "this_level");
  1272. }
  1273. });
  1274.  
  1275. // 添加按钮到titled部分
  1276. (function () {
  1277. var elements = [".Virtual.participation", ".Attention", ".Practice"];//只为部分titled添加
  1278. $.each(elements, function (index, value) {
  1279. $(value).each(function () {
  1280. var titled_id = "_titled_" + getRandomNumber(8);
  1281. var $nextDiv = $(this).next().get(0);
  1282. addButtonPanel($nextDiv, titled_id, "this_level", true);
  1283. addButtonWithTranslation($nextDiv, titled_id, "this_level");
  1284. });
  1285. });
  1286. })();
  1287.  
  1288. // 添加按钮到比赛QA部分
  1289. $(".question-requestText-td").each(function () {
  1290. var $nextDiv = $(this).children().get(0);
  1291. var question_id = "_question_" + getRandomNumber(8);
  1292. addButtonPanel($nextDiv, question_id, "problem_QA", true);
  1293. addButtonWithTranslation(this, question_id, "problem_QA");
  1294. });
  1295. };
  1296.  
  1297. // 翻译框/翻译处理器
  1298. var translatedText = "";
  1299. async function translateProblemStatement(text, element_node) {
  1300. let id = Math.floor(Date.now() / 1000);
  1301. let matches = [];
  1302. let replacements = {};
  1303. // 创建元素并放在element_node的后面
  1304. const translateDiv = document.createElement('div');
  1305. translateDiv.setAttribute('id', id);
  1306. translateDiv.classList.add('translate-problem-statement');
  1307. const spanElement = document.createElement('span');
  1308. translateDiv.appendChild(spanElement);
  1309. element_node.insertAdjacentElement('afterend', translateDiv);
  1310. // 替换latex公式
  1311. if (is_oldLatex) {
  1312. //去除开头结尾的<p>标签
  1313. text = text.replace(/^<p>/i, "");
  1314. text = text.replace(/<\/p>$/i, "");
  1315. //
  1316. let i = 0;
  1317. let regex = /<span\s+class="tex-span">.*?<\/span>/gi;
  1318. matches = text.match(regex);
  1319. try {
  1320. for (i; i < matches.length; i++) {
  1321. let match = matches[i];
  1322. text = text.replace(match, `【${i + 1}】`);
  1323. replacements[`【${i + 1}】`] = match;
  1324. }
  1325. } catch (e) { }
  1326. } else if (getCookie("translation") != "api2d" && getCookie("translation") != "openai") {
  1327. // 使用GPT翻译时不必替换latex公式
  1328. let i = 0;
  1329. // 块公式
  1330. matches = matches.concat(text.match(/\$\$([\s\S]*?)\$\$/g));
  1331. try {
  1332. for (i; i < matches.length; i++) {
  1333. let match = matches[i];
  1334. text = text.replace(match, `【${i + 1}】`);
  1335. replacements[`【${i + 1}】`] = match;
  1336. }
  1337. } catch (e) { }
  1338. // 行内公式
  1339. matches = matches.concat(text.match(/\$(.*?)\$/g));
  1340. try {
  1341. for (i; i < matches.length; i++) {
  1342. let match = matches[i];
  1343. text = text.replace(match, `【${i + 1}】`);
  1344. replacements[`【${i + 1}】`] = match;
  1345. }
  1346. } catch (e) { }
  1347. }
  1348. // 翻译
  1349. var translation = getCookie("translation");
  1350. if (translation === 'undefined' || translation === '') {
  1351. setCookie("translation", "deepl", 3650);
  1352. translation = "deepl";
  1353. }
  1354. if (translation == "deepl") {
  1355. translateDiv.textContent = "正在翻译中……请耐心等待,\n\n如果长时间无变化,请尝试刷新页面重试或者查看控制台的报错信息";
  1356. translatedText = await translate_deepl(text);
  1357. } else if (translation == "youdao") {
  1358. translateDiv.textContent = "正在翻译中……请耐心等待,\n\n如果长时间无变化,请尝试刷新页面重试或者查看控制台的报错信息";
  1359. translatedText = await translate_youdao_mobile(text);
  1360. } else if (translation == "baidu") {
  1361. var baidu_appid = getCookie("baidu_uid");
  1362. var baidu_key = getCookie("baidu_key");
  1363. } else if (translation == "openai") {
  1364. translateDiv.textContent = "正在翻译中……请稍等\n\n使用GPT(ChatGPT/api2d)进行翻译通常需要很长的时间,请耐心等待\n\n如果长时间无变化,请尝试刷新页面重试或者查看控制台的报错信息";
  1365. translatedText = await translate_openai(text);
  1366. } else if (translation == "api2d") {
  1367. translateDiv.textContent = "正在翻译中……请稍等\n\n使用GPT(ChatGPT/api2d)进行翻译通常需要很长的时间,请耐心等待\n\n如果长时间无变化,请尝试刷新页面重试或者查看控制台的报错信息";
  1368. translatedText = await translate_api2d(text);
  1369. }
  1370. // 还原latex公式
  1371. if (is_oldLatex) {
  1372. translatedText = "<p>" + translatedText;
  1373. translatedText += "</p>";
  1374. try {
  1375. for (let i = 0; i < matches.length; i++) {
  1376. let match = matches[i];
  1377. let replacement = replacements[`【${i + 1}】`];
  1378. translatedText = translatedText.replace(`【${i + 1}】`, replacement);
  1379. }
  1380. } catch (e) { }
  1381. }
  1382. else if (getCookie("translation") != "api2d" && getCookie("translation") != "openai") {
  1383. try {
  1384. for (let i = 0; i < matches.length; i++) {
  1385. let match = matches[i];
  1386. let replacement = replacements[`【${i + 1}】`];
  1387. translatedText = translatedText.replace(`【${i + 1}】`, replacement);
  1388. }
  1389. } catch (e) { }
  1390. }
  1391. // 使符合mathjx的转换语法
  1392. translatedText = translatedText.replace(/(\$\$)/g, "");
  1393. translatedText = translatedText.replace(/(?<!\$)\$(?!\$)/g, "$$$$$");
  1394. // 更新
  1395. if (is_oldLatex) {
  1396. // oldlatex
  1397. translatedText = $.parseHTML(translatedText);
  1398. $(translateDiv).empty().append($(translatedText));
  1399. } else {
  1400. translateDiv.innerHTML = translatedText;
  1401. // 渲染MarkDown
  1402. var md = window.markdownit();
  1403. var html = md.render(translateDiv.innerText);
  1404. translateDiv.innerHTML = html;
  1405. // 渲染Latex
  1406. MathJax.Hub.Queue(["Typeset", MathJax.Hub, document.getElementById(id)]);
  1407. }
  1408. return translateDiv;
  1409. }
  1410.  
  1411. // ChatGPT
  1412. async function translate_openai(raw) {
  1413. var openai_key = getCookie("openai_key");
  1414. var openai_retext = "";
  1415. var data;
  1416. if (is_oldLatex) {
  1417. data = {
  1418. prompt: "(You:请帮我将下面的文本翻译为中文,这是一个编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的【】、HTML标签本身以及其中的内容不翻译不变动,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n" + raw + ")",
  1419. max_tokens: 2048,
  1420. model: "text-davinci-003",
  1421. };
  1422. } else {
  1423. data = {
  1424. prompt: "(You:请帮我将下面的文本翻译为中文,这是一个编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的latex公式不翻译,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n" + raw + ")",
  1425. max_tokens: 2048,
  1426. model: "text-davinci-003",
  1427. };
  1428. };
  1429. return new Promise(function (resolve, reject) {
  1430. GM_xmlhttpRequest({
  1431. method: 'POST',
  1432. url: 'https://api.openai.com/v1/completions',
  1433. data: JSON.stringify(data),
  1434. headers: {
  1435. 'Content-Type': 'application/json',
  1436. 'Authorization': 'Bearer ' + getCookie("openai_key") + ''
  1437. },
  1438. responseType: 'json',
  1439. onload: function (res) {
  1440. if (res.status === 200) {
  1441. openai_retext = res.response.choices[0].text;
  1442. openai_retext = openai_retext.replace(/^\s+/, '');
  1443. resolve(openai_retext);
  1444. }
  1445. else {
  1446. console.error(res.statusText);
  1447. reject(res.statusText);
  1448. }
  1449. }
  1450. });
  1451. });
  1452. }
  1453.  
  1454. // api2d
  1455. async function translate_api2d(raw) {
  1456. var api2d_key = getCookie("api2d_key");
  1457. var api2d_retext = "";
  1458. var postData;
  1459. if (is_oldLatex) {
  1460. postData = JSON.stringify({
  1461. model: 'gpt-3.5-turbo',
  1462. messages: [{ role: 'user', content: '请帮我将下面的文本翻译为中文,这是一个编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的【】、HTML标签本身以及其中的内容不翻译不变动,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n' + raw }],
  1463. });
  1464. } else {
  1465. postData = JSON.stringify({
  1466. model: 'gpt-3.5-turbo',
  1467. messages: [{ role: 'user', content: '请帮我将下面的文本翻译为中文,这是一个编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的latex公式不翻译,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n' + raw }],
  1468. });
  1469. }
  1470. const options = {
  1471. method: 'POST',
  1472. headers: {
  1473. 'Content-Type': 'application/json',
  1474. Authorization: 'Bearer ' + api2d_key,
  1475. },
  1476. data: postData,
  1477. };
  1478.  
  1479. return new Promise(function (resolve, reject) {
  1480. GM_xmlhttpRequest({
  1481. method: options.method,
  1482. url: `https://openai.api2d.net/v1/chat/completions`,
  1483. headers: options.headers,
  1484. data: options.data,
  1485. responseType: 'json',
  1486. onload: function (response) {
  1487. api2d_retext = response.response.choices[0].message.content;
  1488. resolve(api2d_retext);
  1489. },
  1490. onerror: function (response) {
  1491. console.error(response.statusText);
  1492. reject(response.statusText);
  1493. },
  1494. });
  1495. });
  1496. }
  1497. //
  1498.  
  1499. //--有道翻译m--start
  1500. async function translate_youdao_mobile(raw) {
  1501. const options = {
  1502. method: "POST",
  1503. url: 'http://m.youdao.com/translate',
  1504. data: "inputtext=" + encodeURIComponent(raw) + "&type=AUTO",
  1505. anonymous: true,
  1506. headers: {
  1507. "Content-Type": "application/x-www-form-urlencoded"
  1508. }
  1509. }
  1510. return await BaseTranslate('有道翻译mobile', raw, options, res => /id="translateResult">\s*?<li>([\s\S]*?)<\/li>\s*?<\/ul/.exec(res)[1])
  1511. }
  1512. //--有道翻译m--end
  1513.  
  1514. //--Deepl翻译--start
  1515. function getTimeStamp(iCount) {
  1516. const ts = Date.now();
  1517. if (iCount !== 0) {
  1518. iCount = iCount + 1;
  1519. return ts - (ts % iCount) + iCount;
  1520. } else {
  1521. return ts;
  1522. }
  1523. }
  1524.  
  1525. async function translate_deepl(raw) {
  1526. const id = (Math.floor(Math.random() * 99999) + 100000) * 1000;
  1527. const data = {
  1528. jsonrpc: '2.0',
  1529. method: 'LMT_handle_texts',
  1530. id,
  1531. params: {
  1532. splitting: 'newlines',
  1533. lang: {
  1534. source_lang_user_selected: 'auto',
  1535. target_lang: 'ZH',
  1536. },
  1537. texts: [{
  1538. text: raw,
  1539. requestAlternatives: 3
  1540. }],
  1541. timestamp: getTimeStamp(raw.split('i').length - 1)
  1542. }
  1543. }
  1544. let postData = JSON.stringify(data);
  1545. if ((id + 5) % 29 === 0 || (id + 3) % 13 === 0) {
  1546. postData = postData.replace('"method":"', '"method" : "');
  1547. } else {
  1548. postData = postData.replace('"method":"', '"method": "');
  1549. }
  1550. const options = {
  1551. method: 'POST',
  1552. url: 'https://www2.deepl.com/jsonrpc',
  1553. data: postData,
  1554. headers: {
  1555. 'Content-Type': 'application/json',
  1556. 'Host': 'www.deepl.com',
  1557. 'Origin': 'https://www.deepl.com',
  1558. 'Referer': 'https://www.deepl.com/'
  1559. },
  1560. anonymous: true,
  1561. nocache: true,
  1562. }
  1563. return await BaseTranslate('Deepl翻译', raw, options, res => JSON.parse(res).result.texts[0].text)
  1564. }
  1565.  
  1566. //--Deepl翻译--end
  1567.  
  1568. // Cookie Get/Set
  1569. function setCookie(cname, cvalue, exdays) {
  1570. var d = new Date();
  1571. d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
  1572. var expires = "expires=" + d.toUTCString();
  1573. document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
  1574. }
  1575.  
  1576. function getCookie(cname) {
  1577. var name = cname + "=";
  1578. var decodedCookie = decodeURIComponent(document.cookie);
  1579. var ca = decodedCookie.split(';');
  1580. for (var i = 0; i < ca.length; i++) {
  1581. var c = ca[i];
  1582. while (c.charAt(0) == ' ') {
  1583. c = c.substring(1);
  1584. }
  1585. if (c.indexOf(name) == 0) {
  1586. return c.substring(name.length, c.length);
  1587. }
  1588. }
  1589. return "";
  1590. }
  1591.  
  1592.  
  1593. //--异步请求包装工具--start
  1594. async function PromiseRetryWrap(task, options, ...values) {
  1595. const { RetryTimes, ErrProcesser } = options || {};
  1596. let retryTimes = RetryTimes || 5;
  1597. const usedErrProcesser = ErrProcesser || (err => { throw err });
  1598. if (!task) return;
  1599. while (true) {
  1600. try {
  1601. return await task(...values);
  1602. } catch (err) {
  1603. if (!--retryTimes) {
  1604. console.log(err);
  1605. return usedErrProcesser(err);
  1606. }
  1607. }
  1608. }
  1609. }
  1610.  
  1611. async function BaseTranslate(name, raw, options, processer) {
  1612. const toDo = async () => {
  1613. var tmp;
  1614. try {
  1615. const data = await Request(options);
  1616. tmp = data.responseText;
  1617. const result = await processer(tmp);
  1618. if (result) sessionStorage.setItem(name + '-' + raw, result);
  1619. return result
  1620. } catch (err) {
  1621. throw {
  1622. responseText: tmp,
  1623. err: err
  1624. }
  1625. }
  1626. }
  1627. return await PromiseRetryWrap(toDo, { RetryTimes: 3, ErrProcesser: () => "翻译出错" })
  1628. }
  1629.  
  1630. function Request(options) {
  1631. return new Promise((reslove, reject) => GM_xmlhttpRequest({ ...options, onload: reslove, onerror: reject }))
  1632. }
  1633.  
  1634. //--异步请求包装工具--end
  1635.  
  1636. // 随机数生成
  1637. function getRandomNumber(numDigits) {
  1638. let min = Math.pow(10, numDigits - 1);
  1639. let max = Math.pow(10, numDigits) - 1;
  1640. return Math.floor(Math.random() * (max - min + 1)) + min;
  1641. }