Codeforces Better!

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

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

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