Codeforces Better!

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

目前为 2023-05-20 提交的版本。查看 最新版本

  1. // ==UserScript==
  2. // @name Codeforces Better!
  3. // @namespace https://gf.qytechs.cn/users/747162
  4. // @version 1.26
  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 gf.qytechs.cn
  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://gf.qytechs.cn/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: 'Final standings', replace: '榜单' },
  474. { match: 'School/University/City/Region Championship', replace: '学校/大学/城市/区域比赛' },
  475. { match: 'Official School Contest', replace: '学校官方比赛' },
  476. { match: 'Training Contest', replace: '训练赛' },
  477. { match: 'Training Camp Contest', replace: '训练营比赛' },
  478. { match: 'Official ICPC Contest', replace: 'ICPC官方比赛' },
  479. { match: 'Official International Personal Contest', replace: '官方国际个人赛' },
  480. { match: 'China', replace: '中国' },
  481. { match: 'Statements', replace: '题目描述' },
  482. { match: 'in Chinese', replace: '中文' },
  483. { match: 'Trainings', replace: '训练' },
  484. { match: 'Prepared by', replace: '编写人' },
  485. { match: 'Current or upcoming contests', replace: '当前或即将举行的比赛' },
  486. { match: 'Past contests', replace: '过去的比赛' },
  487. { match: 'Exclusions', replace: '排除' },
  488. { match: 'Before start', replace: '还有' },
  489. { match: 'Before registration', replace: '报名还有' },
  490. { match: 'Until closing ', replace: '结束报名' },
  491. { match: 'Register', replace: '报名' },
  492. { match: 'Registration completed', replace: '已报名' },
  493. ],
  494. '.contests-table': [
  495. { match: 'Contest history', replace: '比赛历史' },
  496. ],
  497. '.roundbox.sidebox.borderTopRound ': [
  498. { match: 'Register now', replace: '现在报名' },
  499. ],
  500. '.icon-eye-close.icon-large': [
  501. { match: 'Add to exclusions', replace: '添加到排除列表' },
  502. ],
  503. '._ContestFilterExclusionsManageFrame_addExclusionLink': [
  504. { match: 'Add to exclusions for gym contests filter', replace: '添加训练营过滤器的排除项' },
  505. ],
  506. '.roundbox.sidebox.sidebar-menu.borderTopRound ': [
  507. { match: 'Announcement', replace: '公告' },
  508. { match: 'Statements', replace: '统计报表' },
  509. { match: 'Tutorial', replace: '题解' },
  510. ],
  511. '.second-level-menu ': [
  512. { match: 'Problems', replace: '问题' },
  513. { match: 'Submit Code', replace: '提交代码' },
  514. { match: 'My Submissions', replace: '我的提交' },
  515. { match: 'Status', replace: '状态' },
  516. { match: 'Standings', replace: '榜单' },
  517. { match: 'Custom Invocation', replace: '自定义调试' },
  518. { match: 'Common standings', replace: '全部排行' },
  519. { match: 'Friends standings', replace: '只看朋友' },
  520. { match: 'Submit', replace: '提交' },
  521. { match: 'Custom test', replace: '自定义测试' },
  522. { match: 'Blog', replace: '博客' },
  523. { match: 'Teams', replace: '队伍' },
  524. { match: 'Submissions', replace: '提交' },
  525. { match: 'Groups', replace: '团体' },
  526. { match: 'Favourites', replace: '收藏' },
  527. { match: 'Contests', replace: '比赛' },
  528. { match: '问题etting', replace: '参与编写的问题' },
  529. { match: 'Gym', replace: '训练营' },
  530. { match: 'Mashups', replace: '组合混搭' },
  531. { match: 'Posts', replace: '帖子' },
  532. { match: '>Comments<', replace: '>回复<' },
  533. { match: 'Main', replace: '主要' },
  534. { match: 'Settings', replace: '设置' },
  535. { match: 'Lists', replace: '列表' },
  536. ],
  537. '.topic-toggle-collapse': [
  538. { match: 'Expand', replace: '展开' },
  539. ],
  540. '.topic-read-more': [
  541. { match: 'Full text and comments', replace: '阅读全文/评论' },
  542. ],
  543. '.toggleEditorCheckboxLabel': [
  544. { match: 'Switch off editor', replace: '关闭编辑器语法高亮' },
  545. ],
  546. '.submit': [
  547. { match: 'Registration for the contest', replace: '比赛报名' },
  548. ],
  549. };
  550. for (const className in classData) {
  551. const elements = document.querySelectorAll(className);
  552. elements.forEach((element) => {
  553. let html = element.outerHTML;
  554. const parent = element.parentNode;
  555. const childIndex = Array.from(parent.children).indexOf(element);
  556. let matched = false;
  557. classData[className].forEach((rule) => {
  558. if (html.match(new RegExp(rule.match, 'g'))) {
  559. matched = true;
  560. html = html.replace(new RegExp(rule.match, 'g'), rule.replace);
  561. const temp = document.createElement('div');
  562. temp.innerHTML = html.trim();
  563. const newElement = element.cloneNode(true);
  564. newElement.innerHTML = temp.firstChild.innerHTML;
  565. parent.replaceChild(newElement, parent.children[childIndex]);
  566. }
  567. });
  568. });
  569. }
  570.  
  571. // 元素选择替换
  572. // 侧栏titled汉化
  573. (function () {
  574. var translations = {
  575. "Pay attention": "→ 注意",
  576. "Top rated": "→ 积分排行",
  577. "Top contributors": "→ 贡献者排行",
  578. "Find user": "→ 查找用户",
  579. "Recent actions": "→ 最近热帖",
  580. "Training filter": "→ 过滤筛选",
  581. "Find training": "→ 搜索比赛/问题",
  582. "Virtual participation": "→ 什么是虚拟参赛",
  583. "Contest materials": "→ 比赛相关资料",
  584. "Settings": "→ 设置",
  585. "Clone Contest to Mashup": "→ Clone比赛到组合混搭",
  586. "Submit": "→ 提交",
  587. "Practice": "→ 练习",
  588. "Problem tags": "→ 问题标签",
  589. "Filter Problems": "→ 过滤问题",
  590. "Attention": "→ 注意",
  591. "About Contest": "→ 关于比赛",
  592. "Last submissions": "→ 上次提交",
  593. "Streams": "→ 直播",
  594. };
  595.  
  596. $(".caption.titled").each(function () {
  597. var tag = $(this).text();
  598. for (var property in translations) {
  599. if (tag.match(property)) {
  600. $(this).addClass(property);
  601. $(this).text(translations[property]);
  602. break;
  603. }
  604. }
  605. });
  606. })();
  607. // 题目Tag汉化
  608. (function () {
  609. var parentElement = $('._FilterByTagsFrame_addTagLabel');
  610. var selectElement = parentElement.find('select');
  611. var translations = {
  612. "*combine tags by OR": "*按逻辑或组合我选择的标签",
  613. "combine-tags-by-or": "*按逻辑或组合我选择的标签(combine-tags-by-or)",
  614. "2-sat": "二分图可满足性问题(2-sat)",
  615. "binary search": "二分搜索(binary search)",
  616. "bitmasks": "位掩码(bitmasks)",
  617. "brute force": "暴力枚举(brute force)",
  618. "chinese remainder theorem": "中国剩余定理(chinese remainder theorem)",
  619. "combinatorics": "组合数学(combinatorics)",
  620. "constructive algorithms": "构造算法(constructive algorithms)",
  621. "data structures": "数据结构(data structures)",
  622. "dfs and similar": "深度优先搜索及其变种(dfs and similar)",
  623. "divide and conquer": "分治算法(divide and conquer)",
  624. "dp": "动态规划(dp)",
  625. "dsu": "并查集(dsu)",
  626. "expression parsing": "表达式解析(expression parsing)",
  627. "fft": "快速傅里叶变换(fft)",
  628. "flows": "流(flows)",
  629. "games": "博弈论(games)",
  630. "geometry": "计算几何(geometry)",
  631. "graph matchings": "图匹配(graph matchings)",
  632. "graphs": "图论(graphs)",
  633. "greedy": "贪心策略(greedy)",
  634. "hashing": "哈希表(hashing)",
  635. "implementation": "实现问题,编程技巧,模拟(implementation)",
  636. "interactive": "交互性问题(interactive)",
  637. "math": "数学(math)",
  638. "matrices": "矩阵(matrices)",
  639. "meet-in-the-middle": "meet-in-the-middle算法(meet-in-the-middle)",
  640. "number theory": "数论(number theory)",
  641. "probabilities": "概率论(probabilities)",
  642. "schedules": "调度算法(schedules)",
  643. "shortest paths": "最短路算法(shortest paths)",
  644. "sortings": "排序算法(sortings)",
  645. "string suffix structures": "字符串后缀结构(string suffix structures)",
  646. "strings": "字符串处理(strings)",
  647. "ternary search": "三分搜索(ternary search)",
  648. "trees": "树形结构(trees)",
  649. "two pointers": "双指针算法(two pointers)"
  650. };
  651. selectElement.find("option").each(function () {
  652. var optionValue = $(this).val();
  653. if (translations[optionValue]) {
  654. $(this).text(translations[optionValue]);
  655. }
  656. });
  657. $("._FilterByTagsFrame_tagBoxCaption").each(function () {
  658. var tag = $(this).text();
  659. if (tag in translations) {
  660. $(this).text(translations[tag]);
  661. }
  662. });
  663. $(".notice").each(function () {
  664. var tag = $(this).text();
  665. if (tag in translations) {
  666. $(this).text(translations[tag]);
  667. }
  668. });
  669. $(".tag-box").each(function () {
  670. var tag = $(this).text();
  671. for (var property in translations) {
  672. property = property.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
  673. if (tag.match(property)) {
  674. $(this).text(translations[property]);
  675. break;
  676. }
  677. }
  678. });
  679. })();
  680. // 题目过滤器选项汉化
  681. (function () {
  682. var parentElement = $('#gym-filter-form');
  683. var selectElement = parentElement.find('div');
  684. var translations = {
  685. "Contest type:": "比赛类型:",
  686. "ICPC region:": "ICPC地区:",
  687. "Contest format:": "比赛形式:",
  688. "Order by:": "排序方式:",
  689. "Secondary order by:": "次要排序方式:",
  690. "Hide, if participated:": "隐藏我参加过的:",
  691. };
  692. selectElement.find("label").each(function () {
  693. var optionValue = $(this).text();
  694. if (translations[optionValue]) {
  695. $(this).text(translations[optionValue]);
  696. }
  697. });
  698. translations = {
  699. "Season:": "时间范围(年度)",
  700. "Duration, hours:": "持续时间(小时):",
  701. "Difficulty:": "难度:"
  702. };
  703. selectElement.each(function () {
  704. var optionValue = $(this).text();
  705. if (translations[optionValue]) {
  706. $(this).text(translations[optionValue]);
  707. }
  708. });
  709. })();
  710. (function () {
  711. var parentElement = $('.setting-value');
  712. var selectElement = parentElement.find('select');
  713. var translations = {
  714. "Official ACM-ICPC Contest": "ICPC官方比赛",
  715. "Official School Contest": "学校官方比赛",
  716. "Opencup Contest": "Opencup比赛",
  717. "School/University/City/Region Championship": "学校/大学/城市/地区锦标赛",
  718. "Training Camp Contest": "训练营比赛",
  719. "Official International Personal Contest": "官方国际个人赛",
  720. "Training Contest": "训练比赛",
  721. "ID_ASC": "创建时间(升序)",
  722. "ID_DESC": "创建时间(降序)",
  723. "RATING_ASC": "评分(升序)",
  724. "RATING_DESC": "评分(降序)",
  725. "DIFFICULTY_ASC": "难度(升序)",
  726. "DIFFICULTY_DESC": "难度(降序)",
  727. "START_TIME_ASC": "开始时间(升序)",
  728. "START_TIME_DESC": "开始时间(降序)",
  729. "DURATION_ASC": "持续时间(升序)",
  730. "DURATION_DESC": "持续时间(降序)",
  731. "POPULARITY_ASC": "热度(升序)",
  732. "POPULARITY_DESC": "热度(降序)",
  733. "UPDATE_TIME_ASC": "更新时间(升序)",
  734. "UPDATE_TIME_DESC": "更新时间(降序)"
  735. };
  736. selectElement.find("option").each(function () {
  737. var optionValue = $(this).val();
  738. if (translations[optionValue]) {
  739. $(this).text(translations[optionValue]);
  740. }
  741. });
  742. parentElement = $('.setting-last-value');
  743. selectElement = parentElement.find('select');
  744. selectElement.find("option").each(function () {
  745. var optionValue = $(this).val();
  746. if (translations[optionValue]) {
  747. $(this).text(translations[optionValue]);
  748. }
  749. });
  750. })();
  751. // 右侧sidebox通用汉化
  752. (function () {
  753. var parentElement = $('.sidebox');
  754. var selectElement = parentElement.find('div');
  755. var translations = {
  756. "Show tags for unsolved problems": "显示未解决问题的标签",
  757. "Hide solved problems": "隐藏已解决的问题",
  758. };
  759. selectElement.find("label").each(function () {
  760. var optionValue = $(this).text();
  761. if (translations[optionValue]) {
  762. $(this).text(translations[optionValue]);
  763. }
  764. });
  765. })();
  766. // 题目提交/报名页汉化
  767. (function () {
  768. var translations = {
  769. "Problem:": "题目:",
  770. "Language:": "语言:",
  771. "Source code:": "源代码:",
  772. "Or choose file:": "或者选择文件:",
  773. "Choose file:": "选择文件:",
  774. "Notice:": "注意:",
  775. "virtual participation:": "虚拟参与:",
  776. "Registration for the contest:": "比赛报名:",
  777. "Terms of agreement:": "协议条款:",
  778. "Take part:": "参与:",
  779. "as individual participant:": "作为个人参与者:",
  780. "as a team member:": "作为团队成员:",
  781. "Virtual start time:": "虚拟开始时间:",
  782. "Complete problemset:": "完整的问题集:",
  783. "Question:": "问题:"
  784. };
  785. $(".field-name").each(function () {
  786. var optionValue = $(this).text();
  787. if (translations[optionValue]) {
  788. $(this).text(translations[optionValue]);
  789. }
  790. });
  791. })();
  792. // 按钮汉化
  793. (function () {
  794. var translations = {
  795. "Register for virtual participation": "报名虚拟参赛"
  796. };
  797. $(".submit").each(function () {
  798. var optionValue = $(this).val();
  799. if (translations[optionValue]) {
  800. $(this).val(translations[optionValue]);
  801. }
  802. });
  803. })();
  804. // 杂项汉化
  805. (function () {
  806. var translations = {
  807. "(standard input\/output)": "标准输入/输出",
  808. };
  809. $("div.notice").each(function () {
  810. var tag = $(this).children().eq(0).text();
  811. for (var property in translations) {
  812. if (tag.match(property)) {
  813. $(this).children().eq(0).text(translations[property]);
  814. break;
  815. }
  816. }
  817. });
  818. })();
  819. (function () {
  820. var translations = {
  821. "Ask a question": "提一个问题",
  822. };
  823. $(".ask-question-link").each(function () {
  824. var optionValue = $(this).text();
  825. if (translations[optionValue]) {
  826. $(this).text(translations[optionValue]);
  827. }
  828. });
  829. })();
  830. })();
  831.  
  832. // 设置面板
  833.  
  834. $("div[class='lang-chooser']").each(function () {
  835. $(this).before(
  836. "<button class='html2mdButton CFBetter_setting'>CodeforcesBetter设置</button>"
  837. );
  838. });
  839. $(document).ready(function () {
  840. $(".CFBetter_setting").click(function () {
  841. $(".CFBetter_setting").attr("disabled", true);
  842. $(".CFBetter_setting").css("background-color", "#e6e6e6");
  843. $(".CFBetter_setting").css("color", "#727378");
  844. $(".CFBetter_setting").css("cursor", "not-allowed");
  845. $("body").append(`
  846. <div id='CFBetter_setting_menu'>
  847. <div class="tool-box">
  848. <button class="btn-close">×</button>
  849. </div>
  850. <h3>基本设置</h3>
  851. <hr>
  852. <div class='CFBetter_setting_list'>
  853. <input type="checkbox" id="bottomZh_CN" name="bottomZh_CN" checked>
  854. <label for="bottomZh_CN">界面汉化</label>
  855. </div>
  856. <h3>翻译设置</h3>
  857. <hr>
  858. <label>
  859. <input type='radio' name='translation' value='deepl'>
  860. <span class='CFBetter_setting_menu_label_text'>deepl翻译</span>
  861. </label>
  862. <label>
  863. <input type='radio' name='translation' value='youdao'>
  864. <span class='CFBetter_setting_menu_label_text'>有道翻译</span>
  865. </label>
  866. <label>
  867. <input type='radio' name='translation' value='openai'>
  868. <span class='CFBetter_setting_menu_label_text'>使用ChatGPT翻译(API)</span>
  869. </label>
  870. <label>
  871. <input type='radio' name='translation' value='api2d'>
  872. <span class='CFBetter_setting_menu_label_text'>使用api2d翻译(API)</span>
  873. </label><br>
  874. <div class='CFBetter_setting_menu_input' id='baidu' style='display: none;'>
  875. <label for='baidu_uid'>APP ID:</label><input type='text' id='baidu_uid'>
  876. <label for='baidu_key'>KEY:</label><input type='text' id='baidu_key'>
  877. </div>
  878. <div class='CFBetter_setting_menu_input' id='openai' style='display: none;'>
  879. <span class ='tip'>提示:<br>请确保你能够正常访问OpenAIapi<br></span>
  880. <span class ='tip'>使用ChatGPT-3.5进行翻译,脚本的所有请求均在本地完成,</span>
  881. <span class ='tip'>你需要输入自己的OpenAI KEY,<a target="_blank" href="https://platform.openai.com/account/usage">官网</a></span>
  882. <label for='openai_key'>KEY:</label><input type='text' id='openai_key'>
  883. </div>
  884. <div class='CFBetter_setting_menu_input' id='api2d' style='display: none;'>
  885. <span class ='tip'>提示:<br>api2d是国内的一家提供代理直连访问OpenAIapi的服务商,相当于OpenAIapi的套壳<br></span>
  886. <span class ='tip'>使用ChatGPT-3.5进行翻译,脚本的所有请求均在本地完成<br></span>
  887. <span class ='tip'>你需要输入自己的api2d KEY,<a target="_blank" href="https://api2d.com/profile">官网</a></span>
  888. <label for='api2d_key'>KEY:</label><input type='text' id='api2d_key'>
  889. </div>
  890. <br>
  891. <button id='save'>保存</button>
  892. </div>
  893. `);
  894. var translation = getCookie("translation");
  895. $("#bottomZh_CN").prop("checked", getCookie("bottomZh_CN") === "true");
  896. if (translation === 'undefined' || translation === '') {
  897. setCookie("translation", "deepl", 3650);
  898. $("input[name='translation'][value='deepl']").prop("checked", true);
  899. } else {
  900. $("input[name='translation'][value='" + translation + "']").prop("checked", true);
  901. $("input[name='translation']").css("color", "gray");
  902. if (translation == "baidu") {
  903. $("#baidu").show();
  904. $("#baidu_uid").val(getCookie("baidu_uid"));
  905. $("#baidu_key").val(getCookie("baidu_key"));
  906. $("#baidu_uid").css("color", "gray");
  907. $("#baidu_key").css("color", "gray");
  908. } else if (translation == "openai") {
  909. $("#openai").show();
  910. $("#openai_key").val(getCookie("openai_key"));
  911. $("#openai_key").css("color", "gray");
  912. } else if (translation == "api2d") {
  913. $("#api2d").show();
  914. $("#api2d_key").val(getCookie("api2d_key"));
  915. $("#api2d_key").css("color", "gray");
  916. }
  917. }
  918.  
  919. // 当单选框被选中时,显示对应的输入框,同时隐藏其他输入框
  920. $("input[name='translation']").change(function () {
  921. var selected = $(this).val(); // 获取当前选中的值
  922. if (selected === 'baidu') {
  923. $("#baidu").show();
  924. $("#baidu_uid").val(getCookie("baidu_uid"));
  925. $("#baidu_key").val(getCookie("baidu_key"));
  926. $("#openai, #api2d").hide();
  927. } else if (selected === 'openai') {
  928. $("#openai").show();
  929. $("#openai_key").val(getCookie("openai_key"));
  930. $("#baidu, #api2d").hide();
  931. } else if (selected === 'api2d') {
  932. $("#api2d").show();
  933. $("#api2d_key").val(getCookie("api2d_key"));
  934. $("#baidu, #openai").hide();
  935. } else {
  936. $("#baidu, #openai, #api2d").hide();
  937. }
  938. });
  939.  
  940. $("#save").click(function () {
  941. var translation = $("input[name='translation']:checked").val();
  942. var baidu_uid = $("#baidu_uid").val();
  943. var baidu_key = $("#baidu_key").val();
  944. var openai_key = $("#openai_key").val();
  945. var api2d_key = $("#api2d_key").val();
  946. setCookie("translation", translation, 3650);
  947. if (translation == "baidu") {
  948. setCookie("baidu_uid", baidu_uid, 3650);
  949. setCookie("baidu_key", baidu_key, 3650);
  950. } else if (translation == "openai") {
  951. setCookie("openai_key", openai_key, 3650);
  952. } else if (translation == "api2d") {
  953. setCookie("api2d_key", api2d_key, 3650);
  954. }
  955. setCookie("bottomZh_CN", $("#bottomZh_CN").prop("checked"), 3650);
  956. location.reload();
  957. /* 切换汉化
  958. if(JSON.parse(getCookie("bottomZh_CN")) != $("#bottomZh_CN").prop("checked")){
  959. setCookie("bottomZh_CN", $("#bottomZh_CN").prop("checked"), 3650);
  960. location.reload();
  961. }else{
  962. $("#CFBetter_setting_menu .btn-close").click();
  963. }*/
  964. });
  965. // 关闭
  966. $("#CFBetter_setting_menu .btn-close").click(function () {
  967. $("#CFBetter_setting_menu").remove();
  968. $(".CFBetter_setting").attr("disabled", false);
  969. $(".CFBetter_setting").css("background-color", "#60a5fa");
  970. $(".CFBetter_setting").css("color", "white");
  971. $(".CFBetter_setting").css("cursor", "pointer");
  972. });
  973. });
  974. });
  975.  
  976. // 是否为旧的latex渲染
  977. var is_oldLatex = false;
  978. if ($('.tex-span').length) {
  979. is_oldLatex = true;
  980. var newElement = $("<div></div>").addClass("alert alert-warning").html(`
  981. 注意:当前页面存在使用非 MathJax 库渲染为 HTML Latex 公式(这通常是一道古老的题目),这导致 CodeforcesBetter 无法将其还原回 Latex,因此当前页面部分功能不适用。
  982. <br>此外当前页面的翻译功能采用了特别的实现方式,因此可能会出现排版错位的情况。
  983. `).css({
  984. "margin": "1em",
  985. "text-align": "center",
  986. "position": "relative"
  987. });
  988. $(".menu-box:first").next().after(newElement);
  989. }
  990.  
  991. // md2html转换/处理规则
  992. var turndownService = new TurndownService({bulletListMarker: '-'});
  993. var turndown = turndownService.turndown;
  994.  
  995. // 保留原始
  996. turndownService.keep(['del']);
  997.  
  998. // 丢弃
  999. turndownService.addRule('ignore-sample-tests', {
  1000. filter: function (node) {
  1001. return node.classList.contains('sample-tests') || node.classList.contains('header');
  1002. },
  1003. replacement: function (content, node) {
  1004. return "";
  1005. }
  1006. });
  1007. turndownService.addRule('remove-script', {
  1008. filter: function (node, options) {
  1009. return node.tagName.toLowerCase() == "script" && node.type.startsWith("math/tex");
  1010. },
  1011. replacement: function (content, node) {
  1012. return "";
  1013. }
  1014. });
  1015.  
  1016. // inline math
  1017. turndownService.addRule('inline-math', {
  1018. filter: function (node, options) {
  1019. return node.tagName.toLowerCase() == "span" && node.className == "MathJax";
  1020. },
  1021. replacement: function (content, node) {
  1022. return "$ " + $(node).next().text() + " $";
  1023. }
  1024. });
  1025.  
  1026. // block math
  1027. turndownService.addRule('block-math', {
  1028. filter: function (node, options) {
  1029. return node.tagName.toLowerCase() == "div" && node.className == "MathJax_Display";
  1030. },
  1031. replacement: function (content, node) {
  1032. return "\n$$\n" + $(node).next().text() + "\n$$\n";
  1033. }
  1034. });
  1035.  
  1036. // 表格
  1037. turndownService.addRule('bordertable', {
  1038. filter: 'table',
  1039. replacement: function (content, node) {
  1040. if (node.classList.contains('bordertable')) {
  1041. var output = [],
  1042. thead = '',
  1043. trs = node.querySelectorAll('tr');
  1044. if (trs.length > 0) {
  1045. var ths = trs[0].querySelectorAll('th');
  1046. if (ths.length > 0) {
  1047. thead = '| ' + Array.from(ths).map(th => turndownService.turndown(th.innerHTML.trim())).join(' | ') + ' |\n'
  1048. + '| ' + Array.from(ths).map(() => ' --- ').join('|') + ' |\n';
  1049. }
  1050. }
  1051. var rows = node.querySelectorAll('tr');
  1052. Array.from(rows).forEach(function (row, i) {
  1053. if (i > 0) {
  1054. var cells = row.querySelectorAll('td,th');
  1055. var trow = '| ' + Array.from(cells).map(cell => turndownService.turndown(cell.innerHTML.trim())).join(' | ') + ' |';
  1056. output.push(trow);
  1057. }
  1058. });
  1059. return thead + output.join('\n');
  1060. } else {
  1061. return content;
  1062. }
  1063. }
  1064. });
  1065.  
  1066. // 仅GPT适用
  1067. if (getCookie("translation") === "api2d" || getCookie("translation") === "openai") {
  1068. // tex-font-style-bf
  1069. turndownService.addRule('tex-font-style-bf', {
  1070. filter: function (node, options) {
  1071. return node.tagName.toLowerCase() == "span" && node.className == "tex-font-style-bf";
  1072. },
  1073. replacement: function (content, node) {
  1074. return "**" + $(node).text() + "**";
  1075. }
  1076. });
  1077. }
  1078.  
  1079. // 题目markdown转换/翻译面板
  1080. function addButtonPanel(parent, suffix, type, is_simple = false) {
  1081. if (type === "upper_level_2" || type === "problem") {
  1082. $(parent).children(':eq(1)').before(
  1083. "<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>");
  1084. } else if (is_simple) {
  1085. $(parent).before(
  1086. "<div class='html2md-panel'><button class='html2mdButton translateButton" + suffix + "'>翻译</button> </div>");
  1087. } else {
  1088. $(parent).before(
  1089. "<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>");
  1090. }
  1091. }
  1092. function addButtonWithHTML2MD(parent, suffix, type) {
  1093. if(is_oldLatex){
  1094. $(".html2md-view" + suffix).css({
  1095. "cursor": "not-allowed",
  1096. "background-color": "#e6e6e638",
  1097. "color": "#72737896",
  1098. });
  1099. $(".html2md-view" + suffix).prop("disabled", true);
  1100. }
  1101. $(".html2md-view" + suffix).click(function () {
  1102. var target, removedChildren;
  1103. if (type === "problem") {
  1104. target = $(parent).children().next().next().get(0);
  1105. } else if (type === "problem_QA") {
  1106. target = $(this).parent().parent().get(0);
  1107. removedChildren = $(this).parent().parent().children().eq(0).detach();
  1108. } else if (type === "upper_level_2") {
  1109. target = parent;
  1110. removedChildren = $(parent).children().slice(0, 2).detach();
  1111. } else {
  1112. target = parent;
  1113. }
  1114. if (target.viewmd) {
  1115. target.viewmd = false;
  1116. $(this).text("MarkDown视图");
  1117. $(this).removeClass("mdViewed");
  1118. $(target).html(target.original_html);
  1119. } else {
  1120. target.viewmd = true;
  1121. if (!target.original_html) {
  1122. target.original_html = $(target).html();
  1123. }
  1124. if (!target.markdown) {
  1125. target.markdown = turndownService.turndown($(target).html());
  1126. }
  1127. $(this).text("原始内容");
  1128. $(this).addClass("mdViewed");
  1129. $(target).html(`<span class="mdViewContent" oninput="$(this).parent().get(0).markdown=this.value;" style="width:auto; height:auto;">${target.markdown}</span>`);
  1130. }
  1131. // 恢复删除的元素
  1132. if (type === "problem_QA" || type === "upper_level_2") $(target).prepend(removedChildren);
  1133. });
  1134. }
  1135.  
  1136. function addButtonWithCopy(parent, suffix, type) {
  1137. if(is_oldLatex){
  1138. $(".html2md-cb" + suffix).css({
  1139. "cursor": "not-allowed",
  1140. "background-color": "#e6e6e638",
  1141. "color": "#72737896",
  1142. });
  1143. $(".html2md-cb" + suffix).prop("disabled", true);
  1144. }
  1145. $(".html2md-cb" + suffix).click(function () {
  1146. var target, removedChildren;
  1147. if (type === "problem") {
  1148. target = $($(parent).children().next().next().get(0)).clone();
  1149. } else if (type === "problem_QA") {
  1150. target = $(this).parent().parent().eq(0).clone();
  1151. $(target).children(':first').remove();
  1152. } else if (type === "upper_level_2") {
  1153. target = $(parent).clone();
  1154. $(target).children(':first').remove(); // 删除前两个元素(标题和按钮面板)
  1155. $(target).children(':first').remove();
  1156. } else {
  1157. target = $(parent).clone();
  1158. }
  1159. if (!target.markdown) {
  1160. target.markdown = turndownService.turndown($(target).html());
  1161. }
  1162. const textarea = document.createElement('textarea');
  1163. textarea.value = target.markdown;
  1164. document.body.appendChild(textarea);
  1165. textarea.select();
  1166. document.execCommand('copy');
  1167. document.body.removeChild(textarea);
  1168. $(this).addClass("copied");
  1169. $(this).text("Copied");
  1170. // 更新复制按钮文本
  1171. setTimeout(() => {
  1172. $(this).removeClass("copied");
  1173. $(this).text("Copy");
  1174. }, 2000);
  1175. $(target).remove();
  1176. });
  1177. }
  1178.  
  1179. function addButtonWithTranslation(parent, suffix, type) {
  1180. $(".translateButton" + suffix).click(async function () {
  1181. var target, removedChildren;
  1182. if (type === "problem") {
  1183. target = $($(parent).children().next().next().get(0)).clone();
  1184. } else if (type === "problem_QA") {
  1185. target = $(this).parent().parent().eq(0).clone();
  1186. $(target).children(':first').remove();
  1187. } else if (type === "upper_level_2") {
  1188. target = $(parent).clone();
  1189. $(target).children(':first').remove(); // 删除前两个元素(标题和按钮面板)
  1190. $(target).children(':first').remove();
  1191. } else {
  1192. target = $(parent).clone();
  1193. }
  1194. if (is_oldLatex) {
  1195. target.markdown = $(target).html();
  1196. } else if (!target.markdown) {
  1197. target.markdown = turndownService.turndown($(target).html());
  1198. }
  1199. const textarea = document.createElement('textarea');
  1200. textarea.value = target.markdown;
  1201. // 翻译处理
  1202. $(this).removeClass("translated");
  1203. $(this).text("翻译中");
  1204. $(this).css("cursor", "not-allowed");
  1205. var element_node;
  1206. if (type === "problem") {
  1207. element_node = $(parent).children()[2]; // 题面特殊处理
  1208. } else if (type === "problem_QA") {
  1209. element_node = $(parent).children().last().get(0);
  1210. } else {
  1211. element_node = parent;
  1212. }
  1213. var translateDiv = await translateProblemStatement(textarea.value, element_node);
  1214. //
  1215. $(this).addClass("translated");
  1216. $(this).text("已翻译");
  1217. $(this).prop("disabled", true);
  1218. $(target).remove();
  1219. // 重新翻译
  1220. if ($(this).next('.reTranslation').length === 0) {
  1221. const reTranslateBtn = $('<button>').addClass('html2mdButton reTranslation').html('&circlearrowright;').attr('title', '重新翻译');
  1222. reTranslateBtn.on('click', function() {
  1223. $(translateDiv).remove();
  1224. $(this).prev().click();
  1225. });
  1226. $(this).after(reTranslateBtn);
  1227. }else {
  1228. const reTranslateBtn = $(this).next('.reTranslation');
  1229. reTranslateBtn.off('click').on('click', function() {
  1230. $(translateDiv).remove();
  1231. $(this).prev().click();
  1232. });
  1233. }
  1234. });
  1235. }
  1236.  
  1237.  
  1238. window.onload = function () {
  1239. // 添加按钮到题面部分
  1240. $("div[class='problem-statement']").each(function () {
  1241. var problem_id = "_comment_" + getRandomNumber(8);
  1242. addButtonPanel(this, problem_id, "problem");
  1243. addButtonWithHTML2MD(this, problem_id, "problem");
  1244. addButtonWithCopy(this, problem_id, "problem");
  1245. addButtonWithTranslation(this, problem_id, "problem");
  1246. });
  1247.  
  1248. // 添加按钮到input部分
  1249. $("div[class='input-specification']").each(function () {
  1250. var id = "_" + getRandomNumber(8);
  1251. addButtonPanel(this, id, "upper_level_2");
  1252. addButtonWithHTML2MD(this, id, "upper_level_2");
  1253. addButtonWithCopy(this, id, "upper_level_2");
  1254. addButtonWithTranslation(this, id, "upper_level_2");
  1255. });
  1256.  
  1257. // 添加按钮到output部分
  1258. $("div[class='output-specification']").each(function () {
  1259. var id = "_" + getRandomNumber(8);
  1260. addButtonPanel(this, id, "upper_level_2");
  1261. addButtonWithHTML2MD(this, id, "upper_level_2");
  1262. addButtonWithCopy(this, id, "upper_level_2");
  1263. addButtonWithTranslation(this, id, "upper_level_2");
  1264. });
  1265.  
  1266. // 添加按钮到note部分
  1267. $("div[class='note']").each(function () {
  1268. var id = "_" + getRandomNumber(8);
  1269. addButtonPanel(this, id, "upper_level_2");
  1270. addButtonWithHTML2MD(this, id, "upper_level_2");
  1271. addButtonWithCopy(this, id, "upper_level_2");
  1272. addButtonWithTranslation(this, id, "upper_level_2");
  1273. });
  1274.  
  1275. // 添加按钮到ttypography部分
  1276. $(".ttypography").each(function () {
  1277. // 题目页特判
  1278. if (!$(this).parent().hasClass('problemindexholder')) {
  1279. var comment_id = "_comment_" + getRandomNumber(8);
  1280. addButtonPanel(this, comment_id, "this_level");
  1281. addButtonWithHTML2MD(this, comment_id, "this_level");
  1282. addButtonWithCopy(this, comment_id, "this_level");
  1283. addButtonWithTranslation(this, comment_id, "this_level");
  1284. }
  1285. });
  1286.  
  1287. // 添加按钮到titled部分
  1288. (function () {
  1289. var elements = [".Virtual.participation", ".Attention", ".Practice"];//只为部分titled添加
  1290. $.each(elements, function (index, value) {
  1291. $(value).each(function () {
  1292. var titled_id = "_titled_" + getRandomNumber(8);
  1293. var $nextDiv = $(this).next().get(0);
  1294. addButtonPanel($nextDiv, titled_id, "this_level", true);
  1295. addButtonWithTranslation($nextDiv, titled_id, "this_level");
  1296. });
  1297. });
  1298. })();
  1299.  
  1300. // 添加按钮到比赛QA部分
  1301. $(".question-requestText-td").each(function () {
  1302. var $nextDiv = $(this).children().get(0);
  1303. var question_id = "_question_" + getRandomNumber(8);
  1304. addButtonPanel($nextDiv, question_id, "problem_QA", true);
  1305. addButtonWithTranslation(this, question_id, "problem_QA");
  1306. });
  1307. };
  1308.  
  1309. // 翻译框/翻译处理器
  1310. var translatedText = "";
  1311. async function translateProblemStatement(text, element_node) {
  1312. let id = Math.floor(Date.now() / 1000);
  1313. let matches = [];
  1314. let replacements = {};
  1315. // 创建元素并放在element_node的后面
  1316. const translateDiv = document.createElement('div');
  1317. translateDiv.setAttribute('id', id);
  1318. translateDiv.classList.add('translate-problem-statement');
  1319. const spanElement = document.createElement('span');
  1320. translateDiv.appendChild(spanElement);
  1321. element_node.insertAdjacentElement('afterend', translateDiv);
  1322. // 替换latex公式
  1323. if (is_oldLatex) {
  1324. //去除开头结尾的<p>标签
  1325. text = text.replace(/^<p>/i, "");
  1326. text = text.replace(/<\/p>$/i, "");
  1327. //
  1328. let i = 0;
  1329. let regex = /<span\s+class="tex-span">.*?<\/span>/gi;
  1330. matches = text.match(regex);
  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. } else if (getCookie("translation") != "api2d" && getCookie("translation") != "openai") {
  1339. // 使用GPT翻译时不必替换latex公式
  1340. let i = 0;
  1341. // 块公式
  1342. matches = matches.concat(text.match(/\$\$([\s\S]*?)\$\$/g));
  1343. try {
  1344. for (i; i < matches.length; i++) {
  1345. let match = matches[i];
  1346. text = text.replace(match, `【${i + 1}】`);
  1347. replacements[`【${i + 1}】`] = match;
  1348. }
  1349. } catch (e) { }
  1350. // 行内公式
  1351. matches = matches.concat(text.match(/\$(.*?)\$/g));
  1352. try {
  1353. for (i; i < matches.length; i++) {
  1354. let match = matches[i];
  1355. text = text.replace(match, `【${i + 1}】`);
  1356. replacements[`【${i + 1}】`] = match;
  1357. }
  1358. } catch (e) { }
  1359. }
  1360. // 翻译
  1361. var translation = getCookie("translation");
  1362. if (translation === 'undefined' || translation === '') {
  1363. setCookie("translation", "deepl", 3650);
  1364. translation = "deepl";
  1365. }
  1366. if (translation == "deepl") {
  1367. translateDiv.textContent = "正在翻译中……请耐心等待,\n\n如果长时间无变化,请尝试刷新页面重试或者查看控制台的报错信息";
  1368. translatedText = await translate_deepl(text);
  1369. } else if (translation == "youdao") {
  1370. translateDiv.textContent = "正在翻译中……请耐心等待,\n\n如果长时间无变化,请尝试刷新页面重试或者查看控制台的报错信息";
  1371. translatedText = await translate_youdao_mobile(text);
  1372. } else if (translation == "baidu") {
  1373. var baidu_appid = getCookie("baidu_uid");
  1374. var baidu_key = getCookie("baidu_key");
  1375. } else if (translation == "openai") {
  1376. translateDiv.textContent = "正在翻译中……请稍等\n\n使用GPT(ChatGPT/api2d)进行翻译通常需要很长的时间,请耐心等待\n\n如果长时间无变化,请尝试刷新页面重试或者查看控制台的报错信息";
  1377. translatedText = await translate_openai(text);
  1378. } else if (translation == "api2d") {
  1379. translateDiv.textContent = "正在翻译中……请稍等\n\n使用GPT(ChatGPT/api2d)进行翻译通常需要很长的时间,请耐心等待\n\n如果长时间无变化,请尝试刷新页面重试或者查看控制台的报错信息";
  1380. translatedText = await translate_api2d(text);
  1381. }
  1382. // 还原latex公式
  1383. if (is_oldLatex) {
  1384. translatedText = "<p>" + translatedText;
  1385. translatedText += "</p>";
  1386. try {
  1387. for (let i = 0; i < matches.length; i++) {
  1388. let match = matches[i];
  1389. let replacement = replacements[`【${i + 1}】`];
  1390. translatedText = translatedText.replace(`【${i + 1}】`, replacement);
  1391. }
  1392. } catch (e) { }
  1393. }
  1394. else if (getCookie("translation") != "api2d" && getCookie("translation") != "openai") {
  1395. try {
  1396. for (let i = 0; i < matches.length; i++) {
  1397. let match = matches[i];
  1398. let replacement = replacements[`【${i + 1}】`];
  1399. translatedText = translatedText.replace(`【${i + 1}】`, replacement);
  1400. }
  1401. } catch (e) { }
  1402. }
  1403. // 使符合mathjx的转换语法
  1404. translatedText = translatedText.replace(/(\$\$)/g, "");
  1405. translatedText = translatedText.replace(/(?<!\$)\$(?!\$)/g, "$$$$$");
  1406. // 更新
  1407. if (is_oldLatex) {
  1408. // oldlatex
  1409. translatedText = $.parseHTML(translatedText);
  1410. $(translateDiv).empty().append($(translatedText));
  1411. } else {
  1412. translateDiv.innerHTML = translatedText;
  1413. // 渲染MarkDown
  1414. var md = window.markdownit();
  1415. var html = md.render(translateDiv.innerText);
  1416. translateDiv.innerHTML = html;
  1417. // 渲染Latex
  1418. MathJax.Hub.Queue(["Typeset", MathJax.Hub, document.getElementById(id)]);
  1419. }
  1420. return translateDiv;
  1421. }
  1422.  
  1423. // ChatGPT
  1424. async function translate_openai(raw) {
  1425. var openai_key = getCookie("openai_key");
  1426. var openai_retext = "";
  1427. var data;
  1428. if (is_oldLatex) {
  1429. data = {
  1430. prompt: "(You:请帮我将下面的文本翻译为中文,这是一个编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的【】、HTML标签本身以及其中的内容不翻译不变动,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n" + raw + ")",
  1431. max_tokens: 2048,
  1432. model: "text-davinci-003",
  1433. };
  1434. } else {
  1435. data = {
  1436. prompt: "(You:请帮我将下面的文本翻译为中文,这是一个编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的latex公式不翻译,使用markdown语法回复,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n" + raw + ")",
  1437. max_tokens: 2048,
  1438. model: "text-davinci-003",
  1439. };
  1440. };
  1441. return new Promise(function (resolve, reject) {
  1442. GM_xmlhttpRequest({
  1443. method: 'POST',
  1444. url: 'https://api.openai.com/v1/completions',
  1445. data: JSON.stringify(data),
  1446. headers: {
  1447. 'Content-Type': 'application/json',
  1448. 'Authorization': 'Bearer ' + getCookie("openai_key") + ''
  1449. },
  1450. responseType: 'json',
  1451. onload: function (res) {
  1452. if (res.status === 200) {
  1453. openai_retext = res.response.choices[0].text;
  1454. openai_retext = openai_retext.replace(/^\s+/, '');
  1455. resolve(openai_retext);
  1456. }
  1457. else {
  1458. console.error(res.statusText);
  1459. reject(res.statusText);
  1460. }
  1461. }
  1462. });
  1463. });
  1464. }
  1465.  
  1466. // api2d
  1467. async function translate_api2d(raw) {
  1468. var api2d_key = getCookie("api2d_key");
  1469. var api2d_retext = "";
  1470. var postData;
  1471. if (is_oldLatex) {
  1472. postData = JSON.stringify({
  1473. model: 'gpt-3.5-turbo',
  1474. messages: [{ role: 'user', content: '请帮我将下面的文本翻译为中文,这是一个编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的【】、HTML标签本身以及其中的内容不翻译不变动,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n' + raw }],
  1475. });
  1476. } else {
  1477. postData = JSON.stringify({
  1478. model: 'gpt-3.5-turbo',
  1479. messages: [{ role: 'user', content: '请帮我将下面的文本翻译为中文,这是一个编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的latex公式不翻译,使用markdown语法回复,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n' + raw }],
  1480. });
  1481. }
  1482. const options = {
  1483. method: 'POST',
  1484. headers: {
  1485. 'Content-Type': 'application/json',
  1486. Authorization: 'Bearer ' + api2d_key,
  1487. },
  1488. data: postData,
  1489. };
  1490.  
  1491. return new Promise(function (resolve, reject) {
  1492. GM_xmlhttpRequest({
  1493. method: options.method,
  1494. url: `https://openai.api2d.net/v1/chat/completions`,
  1495. headers: options.headers,
  1496. data: options.data,
  1497. responseType: 'json',
  1498. onload: function (response) {
  1499. api2d_retext = response.response.choices[0].message.content;
  1500. resolve(api2d_retext);
  1501. },
  1502. onerror: function (response) {
  1503. console.error(response.statusText);
  1504. reject(response.statusText);
  1505. },
  1506. });
  1507. });
  1508. }
  1509. //
  1510.  
  1511. //--有道翻译m--start
  1512. async function translate_youdao_mobile(raw) {
  1513. const options = {
  1514. method: "POST",
  1515. url: 'http://m.youdao.com/translate',
  1516. data: "inputtext=" + encodeURIComponent(raw) + "&type=AUTO",
  1517. anonymous: true,
  1518. headers: {
  1519. "Content-Type": "application/x-www-form-urlencoded"
  1520. }
  1521. }
  1522. return await BaseTranslate('有道翻译mobile', raw, options, res => /id="translateResult">\s*?<li>([\s\S]*?)<\/li>\s*?<\/ul/.exec(res)[1])
  1523. }
  1524. //--有道翻译m--end
  1525.  
  1526. //--Deepl翻译--start
  1527. function getTimeStamp(iCount) {
  1528. const ts = Date.now();
  1529. if (iCount !== 0) {
  1530. iCount = iCount + 1;
  1531. return ts - (ts % iCount) + iCount;
  1532. } else {
  1533. return ts;
  1534. }
  1535. }
  1536.  
  1537. async function translate_deepl(raw) {
  1538. const id = (Math.floor(Math.random() * 99999) + 100000) * 1000;
  1539. const data = {
  1540. jsonrpc: '2.0',
  1541. method: 'LMT_handle_texts',
  1542. id,
  1543. params: {
  1544. splitting: 'newlines',
  1545. lang: {
  1546. source_lang_user_selected: 'auto',
  1547. target_lang: 'ZH',
  1548. },
  1549. texts: [{
  1550. text: raw,
  1551. requestAlternatives: 3
  1552. }],
  1553. timestamp: getTimeStamp(raw.split('i').length - 1)
  1554. }
  1555. }
  1556. let postData = JSON.stringify(data);
  1557. if ((id + 5) % 29 === 0 || (id + 3) % 13 === 0) {
  1558. postData = postData.replace('"method":"', '"method" : "');
  1559. } else {
  1560. postData = postData.replace('"method":"', '"method": "');
  1561. }
  1562. const options = {
  1563. method: 'POST',
  1564. url: 'https://www2.deepl.com/jsonrpc',
  1565. data: postData,
  1566. headers: {
  1567. 'Content-Type': 'application/json',
  1568. 'Host': 'www.deepl.com',
  1569. 'Origin': 'https://www.deepl.com',
  1570. 'Referer': 'https://www.deepl.com/'
  1571. },
  1572. anonymous: true,
  1573. nocache: true,
  1574. }
  1575. return await BaseTranslate('Deepl翻译', raw, options, res => JSON.parse(res).result.texts[0].text)
  1576. }
  1577.  
  1578. //--Deepl翻译--end
  1579.  
  1580. // Cookie Get/Set
  1581. function setCookie(cname, cvalue, exdays) {
  1582. var d = new Date();
  1583. d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
  1584. var expires = "expires=" + d.toUTCString();
  1585. document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
  1586. }
  1587.  
  1588. function getCookie(cname) {
  1589. var name = cname + "=";
  1590. var decodedCookie = decodeURIComponent(document.cookie);
  1591. var ca = decodedCookie.split(';');
  1592. for (var i = 0; i < ca.length; i++) {
  1593. var c = ca[i];
  1594. while (c.charAt(0) == ' ') {
  1595. c = c.substring(1);
  1596. }
  1597. if (c.indexOf(name) == 0) {
  1598. return c.substring(name.length, c.length);
  1599. }
  1600. }
  1601. return "";
  1602. }
  1603.  
  1604.  
  1605. //--异步请求包装工具--start
  1606. async function PromiseRetryWrap(task, options, ...values) {
  1607. const { RetryTimes, ErrProcesser } = options || {};
  1608. let retryTimes = RetryTimes || 5;
  1609. const usedErrProcesser = ErrProcesser || (err => { throw err });
  1610. if (!task) return;
  1611. while (true) {
  1612. try {
  1613. return await task(...values);
  1614. } catch (err) {
  1615. if (!--retryTimes) {
  1616. console.log(err);
  1617. return usedErrProcesser(err);
  1618. }
  1619. }
  1620. }
  1621. }
  1622.  
  1623. async function BaseTranslate(name, raw, options, processer) {
  1624. const toDo = async () => {
  1625. var tmp;
  1626. try {
  1627. const data = await Request(options);
  1628. tmp = data.responseText;
  1629. const result = await processer(tmp);
  1630. if (result) sessionStorage.setItem(name + '-' + raw, result);
  1631. return result
  1632. } catch (err) {
  1633. throw {
  1634. responseText: tmp,
  1635. err: err
  1636. }
  1637. }
  1638. }
  1639. return await PromiseRetryWrap(toDo, { RetryTimes: 3, ErrProcesser: () => "翻译出错" })
  1640. }
  1641.  
  1642. function Request(options) {
  1643. return new Promise((reslove, reject) => GM_xmlhttpRequest({ ...options, onload: reslove, onerror: reject }))
  1644. }
  1645.  
  1646. //--异步请求包装工具--end
  1647.  
  1648. // 随机数生成
  1649. function getRandomNumber(numDigits) {
  1650. let min = Math.pow(10, numDigits - 1);
  1651. let max = Math.pow(10, numDigits) - 1;
  1652. return Math.floor(Math.random() * (max - min + 1)) + min;
  1653. }

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址