{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'PDF TO Markdown' && linkText !== 'PDF TO Markdown' ) { link.textContent = 'PDF TO Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== 'Voice Cloning' ) { link.textContent = 'Voice Cloning'; link.href = 'https://vibevoice.info/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'PDF TO Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); ';\n\necho $html;"},"label":{"kind":"class label","value":"990","name":"Create an HTML table"},"domain_label":{"kind":"class label","value":"12","name":"php"},"index":{"kind":"string","value":"bxck9"}}},{"rowIdx":12141,"cells":{"code":{"kind":"string","value":"static INPUT: &'static str =\n\"Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!\";\n\nfn main() {\n print!(\"\\n\\n\\n
\");\n for c in INPUT.chars() {\n match c {\n '\\n' => print!(\"
\"),\n ',' => print!(\"\"),\n '<' => print!(\"&lt;\"),\n '>' => print!(\"&gt;\"),\n '&' => print!(\"&amp;\"),\n _ => print!(\"{}\", c)\n }\n }\n println!(\"
\");\n}"},"label":{"kind":"class label","value":"987","name":"CSV to HTML translation"},"domain_label":{"kind":"class label","value":"15","name":"rust"},"index":{"kind":"string","value":"kw2h5"}}},{"rowIdx":12142,"cells":{"code":{"kind":"string","value":"object CsvToHTML extends App {\n val header = \n CsvToHTML\n \n \n val csv =\n \"\"\"Character,Speech\n |The multitude,The messiah! Show us the messiah!\n |Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!\n |The multitude,Who are you?\n |Brians mother,I'm his mother; that's who!\n |The multitude,Behold his mother! Behold his mother!\"\"\".stripMargin\n\n def csv2html(csv: String, withHead: Boolean) = {\n\n def processRow(text: String) = \n {text.split(',').map(s => \n {s}\n )}\n \n\n val (first :: rest) = csv.lines.toList"},"label":{"kind":"class label","value":"987","name":"CSV to HTML translation"},"domain_label":{"kind":"class label","value":"16","name":"scala"},"index":{"kind":"string","value":"1s5pf"}}},{"rowIdx":12143,"cells":{"code":{"kind":"string","value":"import Foundation\n\nfunc countSubstring(str: String, substring: String) -> Int {\n return str.components(separatedBy: substring).count - 1\n}\n\nprint(countSubstring(str: \"the three truths\", substring: \"th\"))\nprint(countSubstring(str: \"ababababab\", substring: \"abab\"))"},"label":{"kind":"class label","value":"992","name":"Count occurrences of a substring"},"domain_label":{"kind":"class label","value":"17","name":"swift"},"index":{"kind":"string","value":"0fgs6"}}},{"rowIdx":12144,"cells":{"code":{"kind":"string","value":"import random\n\ndef rand9999():\n return random.randint(1000, 9999)\n\ndef tag(attr='', **kwargs):\n for tag, txt in kwargs.items():\n return '<{tag}{attr}>{txt}'.format(**locals())\n\nif __name__ == '__main__':\n header = tag(tr=''.join(tag(th=txt) for txt in ',X,Y,Z'.split(','))) + '\\n'\n rows = '\\n'.join(tag(tr=tag(' style=', td=i)\n + ''.join(tag(td=rand9999())\n for j in range(3)))\n for i in range(1, 6))\n table = tag(table='\\n' + header + rows + '\\n')\n print(table)"},"label":{"kind":"class label","value":"990","name":"Create an HTML table"},"domain_label":{"kind":"class label","value":"3","name":"python"},"index":{"kind":"string","value":"3lwzc"}}},{"rowIdx":12145,"cells":{"code":{"kind":"string","value":"int main(){\n char c;\n while ( (c=getchar()) != EOF ){\n putchar(c);\n }\n return 0;\n}"},"label":{"kind":"class label","value":"994","name":"Copy stdin to stdout"},"domain_label":{"kind":"class label","value":"5","name":"c"},"index":{"kind":"string","value":"v702o"}}},{"rowIdx":12146,"cells":{"code":{"kind":"string","value":"import 'dart:io';\n\nvoid main() {\n var line = stdin.readLineSync();\n stdout.write(line);\n}"},"label":{"kind":"class label","value":"994","name":"Copy stdin to stdout"},"domain_label":{"kind":"class label","value":"18","name":"dart"},"index":{"kind":"string","value":"yva65"}}},{"rowIdx":12147,"cells":{"code":{"kind":"string","value":"def r\n rand(10000)\nend\n\nSTDOUT << .tap do |html|\n html << \n [\n ['X', 'Y', 'Z'],\n [r ,r ,r],\n [r ,r ,r],\n [r ,r ,r],\n [r ,r ,r]\n\n ].each_with_index do |row, index|\n html << \n html << \n html << row.map { |e| }.join\n html << \n end\n\n html << \nend"},"label":{"kind":"class label","value":"990","name":"Create an HTML table"},"domain_label":{"kind":"class label","value":"14","name":"ruby"},"index":{"kind":"string","value":"yvq6n"}}},{"rowIdx":12148,"cells":{"code":{"kind":"string","value":"package main\n\nimport (\n \"bufio\"\n \"io\"\n \"os\"\n)\n\nfunc main() {\n r := bufio.NewReader(os.Stdin)\n w := bufio.NewWriter(os.Stdout)\n for {\n b, err := r.ReadByte() \n if err == io.EOF {\n return\n }\n w.WriteByte(b)\n w.Flush()\n } \n}"},"label":{"kind":"class label","value":"994","name":"Copy stdin to stdout"},"domain_label":{"kind":"class label","value":"0","name":"go"},"index":{"kind":"string","value":"sduqa"}}},{"rowIdx":12149,"cells":{"code":{"kind":"string","value":"class StdInToStdOut {\n static void main(args) {\n try (def reader = System.in.newReader()) {\n def line\n while ((line = reader.readLine()) != null) {\n println line\n }\n }\n }\n}"},"label":{"kind":"class label","value":"994","name":"Copy stdin to stdout"},"domain_label":{"kind":"class label","value":"7","name":"groovy"},"index":{"kind":"string","value":"a091p"}}},{"rowIdx":12150,"cells":{"code":{"kind":"string","value":"extern crate rand;\n\nuse rand::Rng;\n\nfn random_cell(rng: &mut R) -> u32 {"},"label":{"kind":"class label","value":"990","name":"Create an HTML table"},"domain_label":{"kind":"class label","value":"15","name":"rust"},"index":{"kind":"string","value":"musya"}}},{"rowIdx":12151,"cells":{"code":{"kind":"string","value":"main = interact id"},"label":{"kind":"class label","value":"994","name":"Copy stdin to stdout"},"domain_label":{"kind":"class label","value":"8","name":"haskell"},"index":{"kind":"string","value":"95wmo"}}},{"rowIdx":12152,"cells":{"code":{"kind":"string","value":"import java.util.Scanner;\n\npublic class CopyStdinToStdout {\n\n public static void main(String[] args) {\n try (Scanner scanner = new Scanner(System.in);) {\n String s;\n while ( (s = scanner.nextLine()).compareTo(\"\") != 0 ) {\n System.out.println(s);\n }\n }\n }\n\n}"},"label":{"kind":"class label","value":"994","name":"Copy stdin to stdout"},"domain_label":{"kind":"class label","value":"9","name":"java"},"index":{"kind":"string","value":"t9kf9"}}},{"rowIdx":12153,"cells":{"code":{"kind":"string","value":"process.stdin.resume();\nprocess.stdin.pipe(process.stdout);"},"label":{"kind":"class label","value":"994","name":"Copy stdin to stdout"},"domain_label":{"kind":"class label","value":"10","name":"javascript"},"index":{"kind":"string","value":"mueyv"}}},{"rowIdx":12154,"cells":{"code":{"kind":"string","value":"object TableGenerator extends App {\n val data = List(List(\"X\", \"Y\", \"Z\"), List(11, 12, 13), List(12, 22, 23), List(13, 32, 33))\n\n def generateTable(data: List[List[Any]]) = {\n \n {data.zipWithIndex.map { case (row, rownum) => (if (rownum == 0) Nil else rownum) +: row}.\n map(row => \n {row.map(cell =>\n )}\n )}\n
\n {cell}\n
\n }\n\n println(generateTable(data))\n}"},"label":{"kind":"class label","value":"990","name":"Create an HTML table"},"domain_label":{"kind":"class label","value":"16","name":"scala"},"index":{"kind":"string","value":"lgocq"}}},{"rowIdx":12155,"cells":{"code":{"kind":"string","value":"fun main() {\n var c: Int\n do {\n c = System.`in`.read()\n System.out.write(c)\n } while (c >= 0)\n}"},"label":{"kind":"class label","value":"994","name":"Copy stdin to stdout"},"domain_label":{"kind":"class label","value":"11","name":"kotlin"},"index":{"kind":"string","value":"ozg8z"}}},{"rowIdx":12156,"cells":{"code":{"kind":"string","value":"lua -e 'for x in io.lines() do print(x) end'"},"label":{"kind":"class label","value":"994","name":"Copy stdin to stdout"},"domain_label":{"kind":"class label","value":"1","name":"lua"},"index":{"kind":"string","value":"i3rot"}}},{"rowIdx":12157,"cells":{"code":{"kind":"string","value":"perl -pe ''"},"label":{"kind":"class label","value":"994","name":"Copy stdin to stdout"},"domain_label":{"kind":"class label","value":"2","name":"perl"},"index":{"kind":"string","value":"gbn4e"}}},{"rowIdx":12158,"cells":{"code":{"kind":"string","value":"python -c 'import sys; sys.stdout.write(sys.stdin.read())'"},"label":{"kind":"class label","value":"994","name":"Copy stdin to stdout"},"domain_label":{"kind":"class label","value":"3","name":"python"},"index":{"kind":"string","value":"rpdgq"}}},{"rowIdx":12159,"cells":{"code":{"kind":"string","value":"Rscript -e 'cat(readLines(file(\"stdin\")))'"},"label":{"kind":"class label","value":"994","name":"Copy stdin to stdout"},"domain_label":{"kind":"class label","value":"13","name":"r"},"index":{"kind":"string","value":"uj8vx"}}},{"rowIdx":12160,"cells":{"code":{"kind":"string","value":"use std::io;\n\nfn main() {\n io::copy(&mut io::stdin().lock(), &mut io::stdout().lock());\n}"},"label":{"kind":"class label","value":"994","name":"Copy stdin to stdout"},"domain_label":{"kind":"class label","value":"15","name":"rust"},"index":{"kind":"string","value":"hezj2"}}},{"rowIdx":12161,"cells":{"code":{"kind":"string","value":"object CopyStdinToStdout extends App {\n io.Source.fromInputStream(System.in).getLines().foreach(println)\n}"},"label":{"kind":"class label","value":"994","name":"Copy stdin to stdout"},"domain_label":{"kind":"class label","value":"16","name":"scala"},"index":{"kind":"string","value":"pqybj"}}},{"rowIdx":12162,"cells":{"code":{"kind":"string","value":"typedef struct{\n\tint num,den;\n\t}fraction;\n\nfraction examples[] = {{1,2}, {3,1}, {23,8}, {13,11}, {22,7}, {-151,77}}; \nfraction sqrt2[] = {{14142,10000}, {141421,100000}, {1414214,1000000}, {14142136,10000000}};\nfraction pi[] = {{31,10}, {314,100}, {3142,1000}, {31428,10000}, {314285,100000}, {3142857,1000000}, {31428571,10000000}, {314285714,100000000}};\n\nint r2cf(int *numerator,int *denominator)\n{\n\tint quotient=0,temp;\n\n\tif(denominator != 0)\n\t{\n\t\tquotient = *numerator / *denominator;\n\n\t\ttemp = *numerator;\n\n\t\t*numerator = *denominator;\n\n\t\t*denominator = temp % *denominator;\n\t}\n\n\treturn quotient;\n}\n\nint main()\n{\n\tint i;\n\n\tprintf();\n\n\tfor(i=0;i= md) {\n\t\t\tx = (md - k[0]) / k[1];\n\t\t\tif (x * 2 >= a || k[1] >= md)\n\t\t\t\ti = 65;\n\t\t\telse\n\t\t\t\tbreak;\n\t\t}\n\n\t\th[2] = x * h[1] + h[0]; h[0] = h[1]; h[1] = h[2];\n\t\tk[2] = x * k[1] + k[0]; k[0] = k[1]; k[1] = k[2];\n\t}\n\t*denom = k[1];\n\t*num = neg ? -h[1] : h[1];\n}\n\nint main()\n{\n\tint i;\n\tint64_t d, n;\n\tdouble f;\n\n\tprintf(, f = 1.0/7);\n\tfor (i = 1; i <= 20000000; i *= 16) {\n\t\tprintf(, i);\n\t\trat_approx(f, i, &n, &d);\n\t\tprintf(, n, d);\n\t}\n\n\tprintf(, f = atan2(1,1) * 4);\n\tfor (i = 1; i <= 20000000; i *= 16) {\n\t\tprintf(, i);\n\t\trat_approx(f, i, &n, &d);\n\t\tprintf(, n, d);\n\t}\n\n\treturn 0;\n}"},"label":{"kind":"class label","value":"996","name":"Convert decimal number to rational"},"domain_label":{"kind":"class label","value":"5","name":"c"},"index":{"kind":"string","value":"mu1ys"}}},{"rowIdx":12164,"cells":{"code":{"kind":"string","value":"(defn r2cf [n d]\n (if-not (= d 0) (cons (quot n d) (lazy-seq (r2cf d (rem n d))))))\n\n\n(def demo '((1 2)\n (3 1)\n (23 8)\n (13 11)\n (22 7)\n (-151 77)\n (14142 10000)\n (141421 100000)\n (1414214 1000000)\n (14142136 10000000)\n (31 10)\n (314 100)\n (3142 1000)\n (31428 10000)\n (314285 100000)\n (3142857 1000000)\n (31428571 10000000)\n (314285714 100000000)\n (3141592653589793 1000000000000000)))\n\n(doseq [inputs demo \n :let [outputs (r2cf (first inputs) (last inputs))]]\n (println inputs \""},"label":{"kind":"class label","value":"995","name":"Continued fraction/Arithmetic/Construct from rational number"},"domain_label":{"kind":"class label","value":"6","name":"clojure"},"index":{"kind":"string","value":"uj0vi"}}},{"rowIdx":12165,"cells":{"code":{"kind":"string","value":"user=> (rationalize 0.1)\n1/10\nuser=> (rationalize 0.9054054)\n4527027/5000000\nuser=> (rationalize 0.518518)\n259259/500000\nuser=> (rationalize Math/PI)\n3141592653589793/1000000000000000"},"label":{"kind":"class label","value":"996","name":"Convert decimal number to rational"},"domain_label":{"kind":"class label","value":"6","name":"clojure"},"index":{"kind":"string","value":"v7q2f"}}},{"rowIdx":12166,"cells":{"code":{"kind":"string","value":"package cf\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)"},"label":{"kind":"class label","value":"995","name":"Continued fraction/Arithmetic/Construct from rational number"},"domain_label":{"kind":"class label","value":"0","name":"go"},"index":{"kind":"string","value":"e89a6"}}},{"rowIdx":12167,"cells":{"code":{"kind":"string","value":"import Data.Ratio ((%))\n\nreal2cf :: (RealFrac a, Integral b) => a -> [b]\nreal2cf x =\n let (i, f) = properFraction x\n in i:\n if f == 0\n then []\n else real2cf (1 / f)\n\nmain :: IO ()\nmain =\n mapM_\n print\n [ real2cf (13 % 11)\n , take 20 $ real2cf (sqrt 2)\n ]"},"label":{"kind":"class label","value":"995","name":"Continued fraction/Arithmetic/Construct from rational number"},"domain_label":{"kind":"class label","value":"8","name":"haskell"},"index":{"kind":"string","value":"3lbzj"}}},{"rowIdx":12168,"cells":{"code":{"kind":"string","value":"import java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\n\npublic class ConstructFromRationalNumber {\n private static class R2cf implements Iterator {\n private int num;\n private int den;\n\n R2cf(int num, int den) {\n this.num = num;\n this.den = den;\n }\n\n @Override\n public boolean hasNext() {\n return den != 0;\n }\n\n @Override\n public Integer next() {\n int div = num / den;\n int rem = num % den;\n num = den;\n den = rem;\n return div;\n }\n }\n\n private static void iterate(R2cf generator) {\n generator.forEachRemaining(n -> System.out.printf(\"%d \", n));\n System.out.println();\n }\n\n public static void main(String[] args) {\n List> fracs = List.of(\n Map.entry(1, 2),\n Map.entry(3, 1),\n Map.entry(23, 8),\n Map.entry(13, 11),\n Map.entry(22, 7),\n Map.entry(-151, 77)\n );\n for (Map.Entry frac : fracs) {\n System.out.printf(\"%4d /%-2d = \", frac.getKey(), frac.getValue());\n iterate(new R2cf(frac.getKey(), frac.getValue()));\n }\n\n System.out.println(\"\\nSqrt(2) ->\");\n List> root2 = List.of(\n Map.entry( 14_142, 10_000),\n Map.entry( 141_421, 100_000),\n Map.entry( 1_414_214, 1_000_000),\n Map.entry(14_142_136, 10_000_000)\n );\n for (Map.Entry frac : root2) {\n System.out.printf(\"%8d /%-8d = \", frac.getKey(), frac.getValue());\n iterate(new R2cf(frac.getKey(), frac.getValue()));\n }\n\n System.out.println(\"\\nPi ->\");\n List> pi = List.of(\n Map.entry( 31, 10),\n Map.entry( 314, 100),\n Map.entry( 3_142, 1_000),\n Map.entry( 31_428, 10_000),\n Map.entry( 314_285, 100_000),\n Map.entry( 3_142_857, 1_000_000),\n Map.entry( 31_428_571, 10_000_000),\n Map.entry(314_285_714, 100_000_000)\n );\n for (Map.Entry frac : pi) {\n System.out.printf(\"%9d /%-9d = \", frac.getKey(), frac.getValue());\n iterate(new R2cf(frac.getKey(), frac.getValue()));\n }\n }\n}"},"label":{"kind":"class label","value":"995","name":"Continued fraction/Arithmetic/Construct from rational number"},"domain_label":{"kind":"class label","value":"9","name":"java"},"index":{"kind":"string","value":"i3gos"}}},{"rowIdx":12169,"cells":{"code":{"kind":"string","value":"package main\n\nimport (\n \"fmt\"\n \"math/big\"\n)\n\nfunc main() {\n for _, d := range []string{\"0.9054054\", \"0.518518\", \"0.75\"} {\n if r, ok := new(big.Rat).SetString(d); ok {\n fmt.Println(d, \"=\", r)\n } else {\n fmt.Println(d, \"invalid decimal number\")\n }\n }\n}"},"label":{"kind":"class label","value":"996","name":"Convert decimal number to rational"},"domain_label":{"kind":"class label","value":"0","name":"go"},"index":{"kind":"string","value":"a0y1f"}}},{"rowIdx":12170,"cells":{"code":{"kind":"null"},"label":{"kind":"class label","value":"995","name":"Continued fraction/Arithmetic/Construct from rational number"},"domain_label":{"kind":"class label","value":"11","name":"kotlin"},"index":{"kind":"string","value":"qn2x1"}}},{"rowIdx":12171,"cells":{"code":{"kind":"string","value":"Number.metaClass.mixin RationalCategory\n\n[\n 0.9054054, 0.518518, 0.75, Math.E, -0.423310825, Math.PI, 0.111111111111111111111111\n].each{\n printf \"%30.27f%s\\n\", it, it as Rational\n}"},"label":{"kind":"class label","value":"996","name":"Convert decimal number to rational"},"domain_label":{"kind":"class label","value":"7","name":"groovy"},"index":{"kind":"string","value":"hefj9"}}},{"rowIdx":12172,"cells":{"code":{"kind":"string","value":"Prelude> map (\\d -> Ratio.approxRational d 0.0001) [0.9054054, 0.518518, 0.75]\n[67 % 74,14 % 27,3 % 4]\nPrelude> [0.9054054, 0.518518, 0.75] :: [Rational]\n[4527027 % 5000000,259259 % 500000,3 % 4]\nPrelude> map (fst . head . Numeric.readFloat) [\"0.9054054\", \"0.518518\", \"0.75\"] :: [Rational]\n[4527027 % 5000000,259259 % 500000,3 % 4]"},"label":{"kind":"class label","value":"996","name":"Convert decimal number to rational"},"domain_label":{"kind":"class label","value":"8","name":"haskell"},"index":{"kind":"string","value":"zcht0"}}},{"rowIdx":12173,"cells":{"code":{"kind":"string","value":"import org.apache.commons.math3.fraction.BigFraction;\n\npublic class Test {\n\n public static void main(String[] args) {\n double[] n = {0.750000000, 0.518518000, 0.905405400, 0.142857143,\n 3.141592654, 2.718281828, -0.423310825, 31.415926536};\n\n for (double d : n)\n System.out.printf(\"%-12s:%s%n\", d, new BigFraction(d, 0.00000002D, 10000));\n }\n}"},"label":{"kind":"class label","value":"996","name":"Convert decimal number to rational"},"domain_label":{"kind":"class label","value":"9","name":"java"},"index":{"kind":"string","value":"oz58d"}}},{"rowIdx":12174,"cells":{"code":{"kind":"string","value":"(() => {\n 'use strict';\n\n const main = () =>\n showJSON(\n map("},"label":{"kind":"class label","value":"996","name":"Convert decimal number to rational"},"domain_label":{"kind":"class label","value":"10","name":"javascript"},"index":{"kind":"string","value":"t9jfm"}}},{"rowIdx":12175,"cells":{"code":{"kind":"string","value":"$|=1;\n\nsub rc2f {\n my($num, $den) = @_;\n return sub { return unless $den;\n my $q = int($num/$den);\n ($num, $den) = ($den, $num - $q*$den);\n $q; };\n}\n\nsub rcshow {\n my $sub = shift;\n print \"[\";\n my $n = $sub->();\n print \"$n\" if defined $n;\n print \"; $n\" while defined($n = $sub->());\n print \"]\\n\";\n}\n\nrcshow(rc2f(@$_)) \n for ([1,2],[3,1],[23,8],[13,11],[22,7],[-151,77]);\nprint \"\\n\";\nrcshow(rc2f(@$_)) \n for ([14142,10000],[141421,100000],[1414214,1000000],[14142136,10000000]);\nprint \"\\n\";\nrcshow(rc2f(314285714,100000000));"},"label":{"kind":"class label","value":"995","name":"Continued fraction/Arithmetic/Construct from rational number"},"domain_label":{"kind":"class label","value":"2","name":"perl"},"index":{"kind":"string","value":"v7s20"}}},{"rowIdx":12176,"cells":{"code":{"kind":"null"},"label":{"kind":"class label","value":"996","name":"Convert decimal number to rational"},"domain_label":{"kind":"class label","value":"11","name":"kotlin"},"index":{"kind":"string","value":"xicws"}}},{"rowIdx":12177,"cells":{"code":{"kind":"string","value":"def r2cf(n1,n2):\n while n2:\n n1, (t1, n2) = n2, divmod(n1, n2)\n yield t1\n\nprint(list(r2cf(1,2))) \nprint(list(r2cf(3,1))) \nprint(list(r2cf(23,8))) \nprint(list(r2cf(13,11))) \nprint(list(r2cf(22,7))) \nprint(list(r2cf(14142,10000))) \nprint(list(r2cf(141421,100000))) \nprint(list(r2cf(1414214,1000000))) \nprint(list(r2cf(14142136,10000000)))"},"label":{"kind":"class label","value":"995","name":"Continued fraction/Arithmetic/Construct from rational number"},"domain_label":{"kind":"class label","value":"3","name":"python"},"index":{"kind":"string","value":"uj0vd"}}},{"rowIdx":12178,"cells":{"code":{"kind":"string","value":"for _,v in ipairs({ 0.9054054, 0.518518, 0.75, math.pi }) do\n local n, d, dmax, eps = 1, 1, 1e7, 1e-15\n while math.abs(n/d-v)>eps and d 0\n n1, (t1, n2) = n2, n1.divmod(n2)\n yield t1\n end\nend"},"label":{"kind":"class label","value":"995","name":"Continued fraction/Arithmetic/Construct from rational number"},"domain_label":{"kind":"class label","value":"14","name":"ruby"},"index":{"kind":"string","value":"4ko5p"}}},{"rowIdx":12180,"cells":{"code":{"kind":"string","value":"struct R2cf {\n n1: i64,\n n2: i64\n}"},"label":{"kind":"class label","value":"995","name":"Continued fraction/Arithmetic/Construct from rational number"},"domain_label":{"kind":"class label","value":"15","name":"rust"},"index":{"kind":"string","value":"gbi4o"}}},{"rowIdx":12181,"cells":{"code":{"kind":"string","value":"sub gcd {\n my ($m, $n) = @_;\n ($m, $n) = ($n, $m % $n) while $n;\n return $m\n}\n\nsub rat_machine {\n my $n = shift;\n my $denom = 1;\n while ($n != int $n) {\n \n \n $n *= 2;\n\n \n $denom <<= 1;\n }\n if ($n) {\n my $g = gcd($n, $denom);\n $n /= $g;\n $denom /= $g;\n }\n return $n, $denom;\n}\n\n\nsub get_denom {\n my ($num, $denom) = (1, pop @_);\n for (reverse @_) {\n ($num, $denom) = ($denom, $_ * $denom + $num);\n }\n wantarray ? ($num, $denom) : $denom\n}\n\nsub best_approx {\n my ($n, $limit) = @_;\n my ($denom, $neg);\n if ($n < 0) {\n $neg = 1;\n $n = -$n;\n }\n\n my $int = int($n);\n my ($num, $denom, @coef) = (1, $n - $int);\n\n \n while (1) {\n \n last if $limit * $denom < 1;\n my $i = int($num / $denom);\n\n \n push @coef, $i;\n\n if (get_denom(@coef) > $limit) {\n pop @coef;\n last;\n }\n\n \n ($num, $denom) = ($denom, $num - $i * $denom);\n }\n\n ($num, $denom) = get_denom @coef;\n $num += $denom * $int;\n\n return $neg ? -$num : $num, $denom;\n}\n\nsub rat_string {\n my $n = shift;\n my $denom = 1;\n my $neg;\n\n \n $n =~ s/\\.0+$//;\n return $n, 1 unless $n =~ /\\./;\n\n if ($n =~ /^-/) {\n $neg = 1;\n $n =~ s/^-//;\n }\n\n \n $denom *= 10 while $n =~ s/\\.(\\d)/$1\\./;\n $n =~ s/\\.$//;\n\n \n $n =~ s/^0*//;\n if ($n) {\n my $g = gcd($n, $denom);\n $n /= $g;\n $denom /= $g;\n }\n return $neg ? -$n : $n, $denom;\n}\n\nmy $limit = 1e8;\nmy $x = 3/8;\nprint \"3/8 = $x:\\n\";\nprintf \"machine:%d/%d\\n\", rat_machine $x;\nprintf \"string: %d/%d\\n\", rat_string $x;\nprintf \"approx below $limit: %d/%d\\n\", best_approx $x, $limit;\n\n$x = 137/4291;\nprint \"\\n137/4291 = $x:\\n\";\nprintf \"machine:%d/%d\\n\", rat_machine $x;\nprintf \"string: %d/%d\\n\", rat_string $x;\nprintf \"approx below $limit: %d/%d\\n\", best_approx $x, $limit;\n\n$x = sqrt(1/2);\nprint \"\\n1/sqrt(2) = $x\\n\";\nprintf \"machine:%d/%d\\n\", rat_machine $x;\nprintf \"string: %d/%d\\n\", rat_string $x;\nprintf \"approx below 10: %d/%d\\n\", best_approx $x, 10;\nprintf \"approx below 100: %d/%d\\n\", best_approx $x, 100;\nprintf \"approx below 1000: %d/%d\\n\", best_approx $x, 1000;\nprintf \"approx below 10000: %d/%d\\n\", best_approx $x, 10000;\nprintf \"approx below 100000: %d/%d\\n\", best_approx $x, 100000;\nprintf \"approx below $limit: %d/%d\\n\", best_approx $x, $limit;\n\n$x = -4 * atan2(1,1);\nprint \"\\n-Pi = $x\\n\";\nprintf \"machine:%d/%d\\n\", rat_machine $x;\nprintf \"string: %d/%d\\n\", rat_string $x;\n\nfor (map { 10 ** $_ } 1 .. 10) {\n printf \"approx below%g:%d /%d\\n\", $_, best_approx($x, $_)\n}"},"label":{"kind":"class label","value":"996","name":"Convert decimal number to rational"},"domain_label":{"kind":"class label","value":"2","name":"perl"},"index":{"kind":"string","value":"2rxlf"}}},{"rowIdx":12182,"cells":{"code":{"kind":"string","value":"int\nmain()\n{\n\tsize_t len;\n\tchar src[] = ;\n\tchar dst1[80], dst2[80];\n\tchar *dst3, *ref;\n\n\t\n\tstrcpy(dst1, src);\n\n\t\n\tlen = strlen(src);\n\tif (len >= sizeof dst2) {\n\t\tfputs(, stderr);\n\t\texit(1);\n\t}\n\tmemcpy(dst2, src, len + 1);\n\n\t\n\tdst3 = strdup(src);\n\tif (dst3 == NULL) {\n\t\t\n\t\tperror();\n\t\texit(1);\n\t}\n\n\t\n\tref = src;\n\n\t\n\tmemset(src, '-', 5);\n\n\tprintf(, src); \n\tprintf(, dst1); \n\tprintf(, dst2); \n\tprintf(, dst3); \n\tprintf(, ref); \n\n\t\n\tfree(dst3);\n\n\treturn 0;\n}"},"label":{"kind":"class label","value":"997","name":"Copy a string"},"domain_label":{"kind":"class label","value":"5","name":"c"},"index":{"kind":"string","value":"4k05t"}}},{"rowIdx":12183,"cells":{"code":{"kind":"string","value":"function asRational($val, $tolerance = 1.e-6)\n{\n if ($val == (int) $val) {\n \n return $val;\n }\n\n $h1=1;\n $h2=0;\n $k1=0;\n $k2=1;\n $b = 1 / $val;\n\n do {\n $b = 1 / $b;\n $a = floor($b);\n $aux = $h1;\n $h1 = $a * $h1 + $h2;\n $h2 = $aux;\n $aux = $k1;\n $k1 = $a * $k1 + $k2;\n $k2 = $aux;\n $b = $b - $a;\n } while (abs($val-$h1/$k1) > $val * $tolerance);\n\n return $h1.'/'.$k1;\n}\n\necho asRational(1/5).; \necho asRational(1/4).; \necho asRational(1/3).; \necho asRational(5).;"},"label":{"kind":"class label","value":"996","name":"Convert decimal number to rational"},"domain_label":{"kind":"class label","value":"12","name":"php"},"index":{"kind":"string","value":"sd2qs"}}},{"rowIdx":12184,"cells":{"code":{"kind":"string","value":"(let [s \"hello\"\n s1 s]\n (println s s1))"},"label":{"kind":"class label","value":"997","name":"Copy a string"},"domain_label":{"kind":"class label","value":"6","name":"clojure"},"index":{"kind":"string","value":"hedjr"}}},{"rowIdx":12185,"cells":{"code":{"kind":"string","value":">>> from fractions import Fraction\n>>> for d in (0.9054054, 0.518518, 0.75): print(d, Fraction.from_float(d).limit_denominator(100))\n\n0.9054054 67/74\n0.518518 14/27\n0.75 3/4\n>>> for d in '0.9054054 0.518518 0.75'.split(): print(d, Fraction(d))\n\n0.9054054 4527027/5000000\n0.518518 259259/500000\n0.75 3/4\n>>>"},"label":{"kind":"class label","value":"996","name":"Convert decimal number to rational"},"domain_label":{"kind":"class label","value":"3","name":"python"},"index":{"kind":"string","value":"v7q29"}}},{"rowIdx":12186,"cells":{"code":{"kind":"string","value":"ratio<-function(decimal){\n denominator=1\n while(nchar(decimal*denominator)!=nchar(round(decimal*denominator))){\n denominator=denominator+1\n }\n str=paste(decimal*denominator,\"/\",sep=\"\")\n str=paste(str,denominator,sep=\"\")\n return(str)\n}"},"label":{"kind":"class label","value":"996","name":"Convert decimal number to rational"},"domain_label":{"kind":"class label","value":"13","name":"r"},"index":{"kind":"string","value":"95amg"}}},{"rowIdx":12187,"cells":{"code":{"kind":"string","value":"> '0.9054054 0.518518 0.75'.split.each { |d| puts % [d, Rational(d)] }\n0.9054054 4527027/5000000\n0.518518 259259/500000\n0.75 3/4\n=> [, , ]"},"label":{"kind":"class label","value":"996","name":"Convert decimal number to rational"},"domain_label":{"kind":"class label","value":"14","name":"ruby"},"index":{"kind":"string","value":"5h0uj"}}},{"rowIdx":12188,"cells":{"code":{"kind":"string","value":"extern crate rand;\nextern crate num;\n\nuse num::Integer;\nuse rand::Rng;\n\nfn decimal_to_rational (mut n: f64) -> [isize;2] {"},"label":{"kind":"class label","value":"996","name":"Convert decimal number to rational"},"domain_label":{"kind":"class label","value":"15","name":"rust"},"index":{"kind":"string","value":"4k85u"}}},{"rowIdx":12189,"cells":{"code":{"kind":"string","value":"import org.apache.commons.math3.fraction.BigFraction\n\nobject Number2Fraction extends App {\n val n = Array(0.750000000, 0.518518000, 0.905405400,\n 0.142857143, 3.141592654, 2.718281828, -0.423310825, 31.415926536)\n for (d <- n)\n println(f\"$d%-12s: ${new BigFraction(d, 0.00000002D, 10000)}%s\")\n}"},"label":{"kind":"class label","value":"996","name":"Convert decimal number to rational"},"domain_label":{"kind":"class label","value":"16","name":"scala"},"index":{"kind":"string","value":"71nr9"}}},{"rowIdx":12190,"cells":{"code":{"kind":"string","value":"char* seconds2string(unsigned long seconds) \n{\n int i;\n\n const unsigned long s = 1;\n const unsigned long m = 60 * s;\n const unsigned long h = 60 * m;\n const unsigned long d = 24 * h;\n const unsigned long w = 7 * d;\n\n const unsigned long coeff[5] = { w, d, h, m, s };\n const char units[5][4] = { , , , , };\n\n static char buffer[256];\n char* ptr = buffer;\n\n for ( i = 0; i < 5; i++ )\n {\n unsigned long value;\n value = seconds / coeff[i];\n seconds = seconds % coeff[i];\n if ( value )\n {\n if ( ptr != buffer ) \n ptr += sprintf(ptr, );\n ptr += sprintf(ptr,,value,units[i]);\n }\n }\n\n return buffer;\n}\n\n\nint main(int argc, char argv[])\n{\n unsigned long seconds;\n\n if ( (argc < 2) && scanf( , &seconds ) \n || (argc >= 2) && sscanf( argv[1], , & seconds ) )\n {\n printf( , seconds2string(seconds) );\n return EXIT_SUCCESS;\n }\n\n return EXIT_FAILURE;\n}"},"label":{"kind":"class label","value":"998","name":"Convert seconds to compound duration"},"domain_label":{"kind":"class label","value":"5","name":"c"},"index":{"kind":"string","value":"5hquk"}}},{"rowIdx":12191,"cells":{"code":{"kind":"string","value":"type eatable interface {\n eat()\n}"},"label":{"kind":"class label","value":"999","name":"Constrained genericity"},"domain_label":{"kind":"class label","value":"0","name":"go"},"index":{"kind":"string","value":"2ral7"}}},{"rowIdx":12192,"cells":{"code":{"kind":"string","value":"class Eatable a where\n eat :: a -> String"},"label":{"kind":"class label","value":"999","name":"Constrained genericity"},"domain_label":{"kind":"class label","value":"8","name":"haskell"},"index":{"kind":"string","value":"a0z1g"}}},{"rowIdx":12193,"cells":{"code":{"kind":"string","value":"package main\n\nimport (\n \"fmt\"\n \"rcu\"\n)\n\nconst LIMIT = 999999\n\nvar primes = rcu.Primes(LIMIT)\n\nfunc longestSeq(dir string) {\n pd := 0\n longSeqs := [][]int{{2}}\n currSeq := []int{2}\n for i := 1; i < len(primes); i++ {\n d := primes[i] - primes[i-1]\n if (dir == \"ascending\" && d <= pd) || (dir == \"descending\" && d >= pd) {\n if len(currSeq) > len(longSeqs[0]) {\n longSeqs = [][]int{currSeq}\n } else if len(currSeq) == len(longSeqs[0]) {\n longSeqs = append(longSeqs, currSeq)\n }\n currSeq = []int{primes[i-1], primes[i]}\n } else {\n currSeq = append(currSeq, primes[i])\n }\n pd = d\n }\n if len(currSeq) > len(longSeqs[0]) {\n longSeqs = [][]int{currSeq}\n } else if len(currSeq) == len(longSeqs[0]) {\n longSeqs = append(longSeqs, currSeq)\n }\n fmt.Println(\"Longest run(s) of primes with\", dir, \"differences is\", len(longSeqs[0]), \":\")\n for _, ls := range longSeqs {\n var diffs []int\n for i := 1; i < len(ls); i++ {\n diffs = append(diffs, ls[i]-ls[i-1])\n }\n for i := 0; i < len(ls)-1; i++ {\n fmt.Print(ls[i], \" (\", diffs[i], \") \")\n }\n fmt.Println(ls[len(ls)-1])\n }\n fmt.Println()\n}\n\nfunc main() {\n fmt.Println(\"For primes < 1 million:\\n\")\n for _, dir := range []string{\"ascending\", \"descending\"} {\n longestSeq(dir)\n }\n}"},"label":{"kind":"class label","value":"1,000","name":"Consecutive primes with ascending or descending differences"},"domain_label":{"kind":"class label","value":"0","name":"go"},"index":{"kind":"string","value":"bxnkh"}}},{"rowIdx":12194,"cells":{"code":{"kind":"string","value":"typedef double (*coeff_func)(unsigned n);\n\n\ndouble calc(coeff_func f_a, coeff_func f_b, unsigned expansions)\n{\n\tdouble a, b, r;\n\ta = b = r = 0.0;\n\n\tunsigned i;\n\tfor (i = expansions; i > 0; i--) {\n\t\ta = f_a(i);\n\t\tb = f_b(i);\n\t\tr = b / (a + r);\n\t}\n\ta = f_a(0);\n\n\treturn a + r;\n}\n\n\ndouble sqrt2_a(unsigned n)\n{\n\treturn n ? 2.0 : 1.0;\n}\n\ndouble sqrt2_b(unsigned n)\n{\n\treturn 1.0;\n}\n\n\ndouble napier_a(unsigned n)\n{\n\treturn n ? n : 2.0;\n}\n\ndouble napier_b(unsigned n)\n{\n\treturn n > 1.0 ? n - 1.0 : 1.0;\n}\n\n\ndouble pi_a(unsigned n)\n{\n\treturn n ? 6.0 : 3.0;\n}\n\ndouble pi_b(unsigned n)\n{\n\tdouble c = 2.0 * n - 1.0;\n\n\treturn c * c;\n}\n\nint main(void)\n{\n\tdouble sqrt2, napier, pi;\n\n\tsqrt2 = calc(sqrt2_a, sqrt2_b, 1000);\n\tnapier = calc(napier_a, napier_b, 1000);\n\tpi = calc(pi_a, pi_b, 1000);\n\n\tprintf(, sqrt2, napier, pi);\n\n\treturn 0;\n}"},"label":{"kind":"class label","value":"1,001","name":"Continued fraction"},"domain_label":{"kind":"class label","value":"5","name":"c"},"index":{"kind":"string","value":"rpqg7"}}},{"rowIdx":12195,"cells":{"code":{"kind":"string","value":"(require '[clojure.string:as string])\n\n(def seconds-in-minute 60)\n(def seconds-in-hour (* 60 seconds-in-minute))\n(def seconds-in-day (* 24 seconds-in-hour))\n(def seconds-in-week (* 7 seconds-in-day))\n\n(defn seconds->duration [seconds]\n (let [weeks ((juxt quot rem) seconds seconds-in-week)\n wk (first weeks)\n days ((juxt quot rem) (last weeks) seconds-in-day)\n d (first days)\n hours ((juxt quot rem) (last days) seconds-in-hour)\n hr (first hours)\n min (quot (last hours) seconds-in-minute)\n sec (rem (last hours) seconds-in-minute)]\n (string/join \", \"\n (filter #(not (string/blank? %))\n (conj []\n (when (> wk 0) (str wk \" wk\"))\n (when (> d 0) (str d \" d\"))\n (when (> hr 0) (str hr \" hr\"))\n (when (> min 0) (str min \" min\"))\n (when (> sec 0) (str sec \" sec\")))))))\n\n(seconds->duration 7259)\n(seconds->duration 86400)\n(seconds->duration 6000000)"},"label":{"kind":"class label","value":"998","name":"Convert seconds to compound duration"},"domain_label":{"kind":"class label","value":"6","name":"clojure"},"index":{"kind":"string","value":"jai7m"}}},{"rowIdx":12196,"cells":{"code":{"kind":"string","value":"interface Eatable\n{\n void eat();\n}"},"label":{"kind":"class label","value":"999","name":"Constrained genericity"},"domain_label":{"kind":"class label","value":"9","name":"java"},"index":{"kind":"string","value":"jao7c"}}},{"rowIdx":12197,"cells":{"code":{"kind":"null"},"label":{"kind":"class label","value":"999","name":"Constrained genericity"},"domain_label":{"kind":"class label","value":"11","name":"kotlin"},"index":{"kind":"string","value":"5hxua"}}},{"rowIdx":12198,"cells":{"code":{"kind":"string","value":"import Data.Numbers.Primes (primes)\n\n\nconsecutives equiv = filter ((> 1) . length) . go []\n where\n go r [] = [r]\n go [] (h: t) = go [h] t\n go (y: ys) (h: t)\n | y `equiv` h = go (h: y: ys) t\n | otherwise = (y: ys): go [h] t\n\n\nmaximumBy g (h: t) = foldr f h t\n where\n f r x = if g r < g x then x else r\n\n\ntask ord n = reverse $ p + s: p: (fst <$> rest)\n where\n (p, s): rest =\n maximumBy length $\n consecutives (\\(_, a) (_, b) -> a `ord` b) $\n differences $\n takeWhile (< n) primes\n differences l = zip l $ zipWith (-) (tail l) l"},"label":{"kind":"class label","value":"1,000","name":"Consecutive primes with ascending or descending differences"},"domain_label":{"kind":"class label","value":"8","name":"haskell"},"index":{"kind":"string","value":"dyun4"}}},{"rowIdx":12199,"cells":{"code":{"kind":"string","value":"function findcps(primelist, fcmp)\n local currlist = {primelist[1]}\n local longlist, prevdiff = currlist, 0\n for i = 2, #primelist do\n local diff = primelist[i] - primelist[i-1]\n if fcmp(diff, prevdiff) then\n currlist[#currlist+1] = primelist[i]\n if #currlist > #longlist then\n longlist = currlist\n end\n else\n currlist = {primelist[i-1], primelist[i]}\n end\n prevdiff = diff\n end\n return longlist\nend\n\nprimegen:generate(nil, 1000000)\ncplist = findcps(primegen.primelist, function(a,b) return a>b end)\nprint(\"ASC (\"..#cplist..\"): [\"..table.concat(cplist, \" \")..\"]\")\ncplist = findcps(primegen.primelist, function(a,b) return a
code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
use std::env; fn main() { let mut args = env::args().skip(1).flat_map(|num| num.parse()); let rows = args.next().expect("Expected number of rows as first argument"); let cols = args.next().expect("Expected number of columns as second argument"); assert_ne!(rows, 0, "rows were zero"); assert_ne!(cols, 0, "cols were zero");
986Create a two-dimensional array at runtime
15rust
he2j2
object Array2D{ def main(args: Array[String]): Unit = { val x = Console.readInt val y = Console.readInt val a=Array.fill(x, y)(0) a(0)(0)=42 println("The number at (0, 0) is "+a(0)(0)) } }
986Create a two-dimensional array at runtime
16scala
pq5bj
def countChange(amount: Int, coins:List[Int]) = { val ways = Array.fill(amount + 1)(0) ways(0) = 1 coins.foreach (coin => for (j<-coin to amount) ways(j) = ways(j) + ways(j - coin) ) ways(amount) } countChange (15, List(1, 5, 10, 25))
989Count the coins
16scala
bxlk6
sub countSubstring { my $str = shift; my $sub = quotemeta(shift); my $count = () = $str =~ /$sub/g; return $count; } print countSubstring("the three truths","th"), "\n"; print countSubstring("ababababab","abab"), "\n";
992Count occurrences of a substring
2perl
qn5x6
use ntheory qw/factor/; print "$_ = ", join(" x ", factor($_)), "\n" for 1000000000000000000 .. 1000000000000000010;
991Count in factors
2perl
pqcb0
use HTML::Entities; sub row { my $elem = shift; my @cells = map {"<$elem>$_</$elem>"} split ',', shift; print '<tr>', @cells, "</tr>\n"; } my ($first, @rest) = map {my $x = $_; chomp $x; encode_entities $x} <STDIN>; print "<table>\n"; row @ARGV ? 'th' : 'td', $first; row 'td', $_ foreach @rest; print "</table>\n";
987CSV to HTML translation
2perl
rpmgd
<?php echo substr_count(, ), PHP_EOL; echo substr_count(, ), PHP_EOL;
992Count occurrences of a substring
12php
v7o2v
import sys for n in xrange(sys.maxint): print oct(n)
993Count in octal
3python
zcptt
import os for directory in ['/', './']: open(directory + 'output.txt', 'w').close() os.mkdir(directory + 'docs')
988Create a file
3python
kwlhf
f <- file("output.txt", "w") close(f) f <- file("/output.txt", "w") close(f) success <- dir.create("docs") success <- dir.create("/docs")
988Create a file
13r
rpygj
<?php $csv = <<<EOT Character,Speech The multitude,The messiah! Show us the messiah! Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry> The multitude,Who are you? Brians mother,I'm his mother; that's who! The multitude,Behold his mother! Behold his mother! EOT; function convert($csv) { $out = []; array_map(function($ln) use(&$out) { $ln = htmlentities($ln); $out[] = count($out) == 0 ? '<thead><tr><th>'.implode('</th><th>',explode(',',$ln)). : '<tr><td>'.implode('</td><td>',explode(',',$ln)).; }, explode(,$csv)); return '<table>'.implode('',$out).'</table>'; } echo convert($csv);
987CSV to HTML translation
12php
dyen8
class StdDevAccumulator def initialize @n, @sum, @sumofsquares = 0, 0.0, 0.0 end def <<(num) @n += 1 @sum += num @sumofsquares += num**2 self end def stddev Math.sqrt( (@sumofsquares / @n) - (@sum / @n)**2 ) end def to_s stddev.to_s end end sd = StdDevAccumulator.new i = 0 [2,4,4,4,5,5,7,9].each {|n| puts }
982Cumulative standard deviation
14ruby
mutyj
import BigInt func countCoins(amountCents cents: Int, coins: [Int]) -> BigInt { let cycle = coins.filter({ $0 <= cents }).map({ $0 + 1 }).max()! * coins.count var table = [BigInt](repeating: 0, count: cycle) for x in 0..<coins.count { table[x] = 1 } var pos = coins.count for s in 1..<cents+1 { for i in 0..<coins.count { if i == 0 && pos >= cycle { pos = 0 } if coins[i] <= s { let q = pos - coins[i] * coins.count table[pos] = q >= 0? table[q]: table[q + cycle] } if i!= 0 { table[pos] += table[pos - 1] } pos += 1 } } return table[pos - 1] } let usCoins = [100, 50, 25, 10, 5, 1] let euCoins = [200, 100, 50, 20, 10, 5, 2, 1] for set in [usCoins, euCoins] { print(countCoins(amountCents: 100, coins: Array(set.dropFirst(2)))) print(countCoins(amountCents: 100000, coins: set)) print(countCoins(amountCents: 1000000, coins: set)) print(countCoins(amountCents: 10000000, coins: set)) print() }
989Count the coins
17swift
rp6gg
from functools import lru_cache primes = [2, 3, 5, 7, 11, 13, 17] @lru_cache(maxsize=2000) def pfactor(n): if n == 1: return [1] n2 = n for p in primes: if p <= n2: d, m = divmod(n, p) if m == 0: if d > 1: return [p] + pfactor(d) else: return [p] else: if n > primes[-1]: primes.append(n) return [n] if __name__ == '__main__': mx = 5000 for n in range(1, mx + 1): factors = pfactor(n) if n <= 10 or n >= mx - 20: print( '%4i%5s%s'% (n, '' if factors != [n] or n == 1 else 'prime', 'x'.join(str(i) for i in factors)) ) if n == 11: print('...') print('\nNumber of primes gathered up to', n, 'is', len(primes)) print(pfactor.cache_info())
991Count in factors
3python
1slpc
import Foundation print("Enter the dimensions of the array seperated by a space (width height): ") let fileHandle = NSFileHandle.fileHandleWithStandardInput() let dims = NSString(data: fileHandle.availableData, encoding: NSUTF8StringEncoding)?.componentsSeparatedByString(" ") if let dims = dims where dims.count == 2{ let w = dims[0].integerValue let h = dims[1].integerValue if let w = w, h = h where w > 0 && h > 0 { var array = Array<[Int!]>(count: h, repeatedValue: Array<Int!>(count: w, repeatedValue: nil)) array[0][0] = 2 println(array[0][0]) println(array) } }
986Create a two-dimensional array at runtime
17swift
71crq
n = 0 loop do puts % n n += 1 end for n in 0..Float::INFINITY puts n.to_s(8) end 0.upto(1/0.0) do |n| printf , n end 0.step do |n| puts format(, n) end
993Count in octal
14ruby
62a3t
findfactors <- function(num) { x <- c() p1<- 2 p2 <- 3 everyprime <- num while( everyprime!= 1 ) { while( everyprime%%p1 == 0 ) { x <- c(x, p1) everyprime <- floor(everyprime/ p1) } p1 <- p2 p2 <- p2 + 2 } x } count_in_factors=function(x){ primes=findfactors(x) x=c(1) for (i in 1:length(primes)) { x=paste(primes[i],"x",x) } return(x) } count_in_factors(72)
991Count in factors
13r
heyjj
pub struct CumulativeStandardDeviation { n: f64, sum: f64, sum_sq: f64 } impl CumulativeStandardDeviation { pub fn new() -> Self { CumulativeStandardDeviation { n: 0., sum: 0., sum_sq: 0. } } fn push(&mut self, x: f64) -> f64 { self.n += 1.; self.sum += x; self.sum_sq += x * x; (self.sum_sq / self.n - self.sum * self.sum / self.n / self.n).sqrt() } } fn main() { let nums = [2, 4, 4, 4, 5, 5, 7, 9]; let mut cum_stdev = CumulativeStandardDeviation::new(); for num in nums.iter() { println!("{}", cum_stdev.push(*num as f64)); } }
982Cumulative standard deviation
15rust
95zmm
>>> .count() 3 >>> .count() 2
992Count occurrences of a substring
3python
sd4q9
fn main() { for i in 0..std::usize::MAX { println!("{:o}", i); } }
993Count in octal
15rust
yve68
['/', './'].each{|dir| Dir.mkdir(dir + 'docs') File.open(dir + 'output.txt', 'w') {} }
988Create a file
14ruby
pqvbh
csvtxt = '''\ Character,Speech The multitude,The messiah! Show us the messiah! Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry> The multitude,Who are you? Brians mother,I'm his mother; that's who! The multitude,Behold his mother! Behold his mother!\ ''' from cgi import escape def _row2tr(row, attr=None): cols = escape(row).split(',') return ('<TR>' + ''.join('<TD>%s</TD>'% data for data in cols) + '</TR>') def csv2html(txt): htmltxt = '<TABLE summary=>\n' for rownum, row in enumerate(txt.split('\n')): htmlrow = _row2tr(row) htmlrow = ' <TBODY>%s</TBODY>\n'% htmlrow htmltxt += htmlrow htmltxt += '</TABLE>\n' return htmltxt htmltxt = csv2html(csvtxt) print(htmltxt)
987CSV to HTML translation
3python
719rm
count = function(haystack, needle) {v = attr(gregexpr(needle, haystack, fixed = T)[[1]], "match.length") if (identical(v, -1L)) 0 else length(v)} print(count("hello", "l"))
992Count occurrences of a substring
13r
e82ad
Stream from 0 foreach (i => println(i.toOctalString))
993Count in octal
16scala
c4q93
use std::io::{self, Write}; use std::fs::{DirBuilder, File}; use std::path::Path; use std::{process,fmt}; const FILE_NAME: &'static str = "output.txt"; const DIR_NAME: &'static str = "docs"; fn main() { create(".").and(create("/")) .unwrap_or_else(|e| error_handler(e,1)); } fn create<P>(root: P) -> io::Result<File> where P: AsRef<Path> { let f_path = root.as_ref().join(FILE_NAME); let d_path = root.as_ref().join(DIR_NAME); DirBuilder::new().create(d_path).and(File::create(f_path)) } fn error_handler<E: fmt::Display>(error: E, code: i32) ->! { let _ = writeln!(&mut io::stderr(), "Error: {}", error); process::exit(code) }
988Create a file
15rust
1supu
File <- "~/test.csv" Opened <- readLines(con = File) Size <- length(Opened) HTML <- "~/test.html" Table <- list() for(i in 1:Size) { Split <- unlist(strsplit(Opened[i],split = ",")) Table[i] <- paste0("<td>",Split,"</td>",collapse = "") Table[i] <- paste0("<tr>",Table[i],"</tr>") } Table[1] <- paste0("<table>",Table[1]) Table[length(Table)] <- paste0(Table[length(Table)],"</table>") writeLines(as.character(Table), HTML)
987CSV to HTML translation
13r
5h3uy
import scala.math.sqrt object StddevCalc extends App { def calcAvgAndStddev[T](ts: Iterable[T])(implicit num: Fractional[T]): (T, Double) = { def avg(ts: Iterable[T])(implicit num: Fractional[T]): T = num.div(ts.sum, num.fromInt(ts.size))
982Cumulative standard deviation
16scala
2rylb
require 'optparse' require 'prime' maximum = 10 OptionParser.new do |o| o.banner = o.on(, Integer, ) { |m| maximum = m } o.parse! rescue ($stderr.puts $!, o; exit 1) ($stderr.puts o; exit 1) unless ARGV.size == 0 end puts unless maximum < 1 2.upto(maximum) do |i| f = i.prime_division.map! do |factor, exponent| ([factor] * exponent).join end.join puts end
991Count in factors
14ruby
e8vax
import java.io.File object CreateFile extends App { try { new File("output.txt").createNewFile() } catch { case e: Exception => println(s"Exception caught: $e with creating output.txt") } try { new File(s"${File.separator}output.txt").createNewFile() } catch { case e: Exception => println(s"Exception caught: $e with creating ${File.separator}output.txt") } try { new File("docs").mkdir() } catch { case e: Exception => println(s"Exception caught: $e with creating directory docs") } try { new File(s"${File.separator}docs").mkdir() } catch { case e: Exception => println(s"Exception caught: $e with creating directory ${File.separator}docs") } }
988Create a file
16scala
woges
use std::env; fn main() { let args: Vec<_> = env::args().collect(); let n = if args.len() > 1 { args[1].parse().expect("Not a valid number to count to") } else { 20 }; count_in_factors_to(n); } fn count_in_factors_to(n: u64) { println!("1"); let mut primes = vec![]; for i in 2..=n { let fs = factors(&primes, i); if fs.len() <= 1 { primes.push(i); println!("{}", i); } else { println!("{} = {}", i, fs.iter().map(|f| f.to_string()).collect::<Vec<String>>().join(" x ")); } } } fn factors(primes: &[u64], mut n: u64) -> Vec<u64> { let mut result = Vec::new(); for p in primes { while n% p == 0 { result.push(*p); n /= p; } if n == 1 { return result; } } vec![n] }
991Count in factors
15rust
woue4
def countSubstrings str, subStr str.scan(subStr).length end p countSubstrings , p countSubstrings ,
992Count occurrences of a substring
14ruby
8tr01
import Foundation func octalSuccessor(value: String) -> String { if value.isEmpty { return "1" } else { let i = value.startIndex, j = value.endIndex.predecessor() switch (value[j]) { case "0": return value[i..<j] + "1" case "1": return value[i..<j] + "2" case "2": return value[i..<j] + "3" case "3": return value[i..<j] + "4" case "4": return value[i..<j] + "5" case "5": return value[i..<j] + "6" case "6": return value[i..<j] + "7" case "7": return octalSuccessor(value[i..<j]) + "0" default: NSException(name:"InvalidDigit", reason: "InvalidOctalDigit", userInfo: nil).raise(); return "" } } } var n = "0" while strtoul(n, nil, 8) < UInt.max { println(n) n = octalSuccessor(n) }
993Count in octal
17swift
3l1z2
object CountInFactors extends App { def primeFactors(n: Int): List[Int] = { def primeStream(s: LazyList[Int]): LazyList[Int] = { s.head #:: primeStream(s.tail filter { _ % s.head != 0 }) } val primes = primeStream(LazyList.from(2)) def factors(n: Int): List[Int] = primes.takeWhile(_ <= n).find(n % _ == 0) match { case None => Nil case Some(p) => p :: factors(n / p) } if (n == 1) List(1) else factors(n) }
991Count in factors
16scala
sdgqo
fn main() { println!("{}","the three truths".matches("th").count()); println!("{}","ababababab".matches("abab").count()); }
992Count occurrences of a substring
15rust
oz783
import scala.annotation.tailrec def countSubstring(str1:String, str2:String):Int={ @tailrec def count(pos:Int, c:Int):Int={ val idx=str1 indexOf(str2, pos) if(idx == -1) c else count(idx+str2.size, c+1) } count(0,0) }
992Count occurrences of a substring
16scala
dykng
my @heading = qw(X Y Z); my $rows = 5; print '<table><thead><td>', (map { "<th>$_</th>" } @heading), "</thead><tbody>"; for (1 .. $rows) { print "<tr><th>$_</th>", (map { "<td>".int(rand(10000))."</td>" } @heading), "</tr>"; } print "</tbody></table>";
990Create an HTML table
2perl
zcetb
-- the minimal table CREATE TABLE IF NOT EXISTS teststd (n DOUBLE PRECISION NOT NULL); -- code modularity with view, we could have used a common table expression instead CREATE VIEW vteststd AS SELECT COUNT(n) AS cnt, SUM(n) AS tsum, SUM(POWER(n,2)) AS tsqr FROM teststd; -- you can of course put this code into every query CREATE OR REPLACE FUNCTION std_dev() RETURNS DOUBLE PRECISION AS $$ SELECT SQRT(tsqr/cnt - (tsum/cnt)^2) FROM vteststd; $$ LANGUAGE SQL; -- test data is: 2,4,4,4,5,5,7,9 INSERT INTO teststd VALUES (2); SELECT std_dev() AS std_deviation; INSERT INTO teststd VALUES (4); SELECT std_dev() AS std_deviation; INSERT INTO teststd VALUES (4); SELECT std_dev() AS std_deviation; INSERT INTO teststd VALUES (4); SELECT std_dev() AS std_deviation; INSERT INTO teststd VALUES (5); SELECT std_dev() AS std_deviation; INSERT INTO teststd VALUES (5); SELECT std_dev() AS std_deviation; INSERT INTO teststd VALUES (7); SELECT std_dev() AS std_deviation; INSERT INTO teststd VALUES (9); SELECT std_dev() AS std_deviation; -- cleanup test data DELETE FROM teststd;
982Cumulative standard deviation
19sql
5hcu3
extension BinaryInteger { @inlinable public func primeDecomposition() -> [Self] { guard self > 1 else { return [] } func step(_ x: Self) -> Self { return 1 + (x << 2) - ((x >> 1) << 1) } let maxQ = Self(Double(self).squareRoot()) var d: Self = 1 var q: Self = self & 1 == 0? 2: 3 while q <= maxQ && self% q!= 0 { q = step(d) d += 1 } return q <= maxQ? [q] + (self / q).primeDecomposition(): [self] } } for i in 1...20 { if i == 1 { print("1 = 1") } else { print("\(i) = \(i.primeDecomposition().map(String.init).joined(separator: " x "))") } }
991Count in factors
17swift
a021i
ruby csv2html.rb header
987CSV to HTML translation
14ruby
heljx
import Darwin class stdDev{ var n:Double = 0.0 var sum:Double = 0.0 var sum2:Double = 0.0 init(){ let testData:[Double] = [2,4,4,4,5,5,7,9]; for x in testData{ var a:Double = calcSd(x) println("value \(Int(x)) SD = \(a)"); } } func calcSd(x:Double)->Double{ n += 1 sum += x sum2 += x*x return sqrt( sum2 / n - sum*sum / n / n) } } var aa = stdDev()
982Cumulative standard deviation
17swift
yvf6e
<?php $cols = array('', 'X', 'Y', 'Z'); $rows = 3; $html = '<html><body><table><colgroup>'; foreach($cols as $col) { $html .= '<col style= />'; } unset($col); $html .= '</colgroup><thead><tr>'; foreach($cols as $col) { $html .= ; } unset($col); $html .= '</tr></thead><tbody>'; for($r = 1; $r <= $rows; $r++) { $html .= '<tr>'; foreach($cols as $key => $col) { $html .= '<td>' . (($key > 0)? rand(1, 9999) : $r) . '</td>'; } unset($col); $html .= '</tr>'; } $html .= '</tbody></table></body></html>'; echo $html;
990Create an HTML table
12php
bxck9
static INPUT: &'static str = "Character,Speech The multitude,The messiah! Show us the messiah! Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry> The multitude,Who are you? Brians mother,I'm his mother; that's who! The multitude,Behold his mother! Behold his mother!"; fn main() { print!("<table>\n<tr><td>"); for c in INPUT.chars() { match c { '\n' => print!("</td></tr>\n<tr><td>"), ',' => print!("</td><td>"), '<' => print!("&lt;"), '>' => print!("&gt;"), '&' => print!("&amp;"), _ => print!("{}", c) } } println!("</td></tr>\n</table>"); }
987CSV to HTML translation
15rust
kw2h5
object CsvToHTML extends App { val header = <head> <title>CsvToHTML</title> <style type="text/css"> td {{background-color:#ddddff; }} thead td {{background-color:#ddffdd; text-align:center; }} </style> </head> val csv = """Character,Speech |The multitude,The messiah! Show us the messiah! |Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry> |The multitude,Who are you? |Brians mother,I'm his mother; that's who! |The multitude,Behold his mother! Behold his mother!""".stripMargin def csv2html(csv: String, withHead: Boolean) = { def processRow(text: String) = <tr> {text.split(',').map(s => <td> {s} </td>)} </tr> val (first :: rest) = csv.lines.toList
987CSV to HTML translation
16scala
1s5pf
import Foundation func countSubstring(str: String, substring: String) -> Int { return str.components(separatedBy: substring).count - 1 } print(countSubstring(str: "the three truths", substring: "th")) print(countSubstring(str: "ababababab", substring: "abab"))
992Count occurrences of a substring
17swift
0fgs6
import random def rand9999(): return random.randint(1000, 9999) def tag(attr='', **kwargs): for tag, txt in kwargs.items(): return '<{tag}{attr}>{txt}</{tag}>'.format(**locals()) if __name__ == '__main__': header = tag(tr=''.join(tag(th=txt) for txt in ',X,Y,Z'.split(','))) + '\n' rows = '\n'.join(tag(tr=tag(' style=', td=i) + ''.join(tag(td=rand9999()) for j in range(3))) for i in range(1, 6)) table = tag(table='\n' + header + rows + '\n') print(table)
990Create an HTML table
3python
3lwzc
int main(){ char c; while ( (c=getchar()) != EOF ){ putchar(c); } return 0; }
994Copy stdin to stdout
5c
v702o
import 'dart:io'; void main() { var line = stdin.readLineSync(); stdout.write(line); }
994Copy stdin to stdout
18dart
yva65
def r rand(10000) end STDOUT << .tap do |html| html << [ ['X', 'Y', 'Z'], [r ,r ,r], [r ,r ,r], [r ,r ,r], [r ,r ,r] ].each_with_index do |row, index| html << html << html << row.map { |e| }.join html << end html << end
990Create an HTML table
14ruby
yvq6n
package main import ( "bufio" "io" "os" ) func main() { r := bufio.NewReader(os.Stdin) w := bufio.NewWriter(os.Stdout) for { b, err := r.ReadByte() if err == io.EOF { return } w.WriteByte(b) w.Flush() } }
994Copy stdin to stdout
0go
sduqa
class StdInToStdOut { static void main(args) { try (def reader = System.in.newReader()) { def line while ((line = reader.readLine()) != null) { println line } } } }
994Copy stdin to stdout
7groovy
a091p
extern crate rand; use rand::Rng; fn random_cell<R: Rng>(rng: &mut R) -> u32 {
990Create an HTML table
15rust
musya
main = interact id
994Copy stdin to stdout
8haskell
95wmo
import java.util.Scanner; public class CopyStdinToStdout { public static void main(String[] args) { try (Scanner scanner = new Scanner(System.in);) { String s; while ( (s = scanner.nextLine()).compareTo("") != 0 ) { System.out.println(s); } } } }
994Copy stdin to stdout
9java
t9kf9
process.stdin.resume(); process.stdin.pipe(process.stdout);
994Copy stdin to stdout
10javascript
mueyv
object TableGenerator extends App { val data = List(List("X", "Y", "Z"), List(11, 12, 13), List(12, 22, 23), List(13, 32, 33)) def generateTable(data: List[List[Any]]) = { <table> {data.zipWithIndex.map { case (row, rownum) => (if (rownum == 0) Nil else rownum) +: row}. map(row => <tr> {row.map(cell => <td> {cell} </td>)} </tr>)} </table> } println(generateTable(data)) }
990Create an HTML table
16scala
lgocq
fun main() { var c: Int do { c = System.`in`.read() System.out.write(c) } while (c >= 0) }
994Copy stdin to stdout
11kotlin
ozg8z
lua -e 'for x in io.lines() do print(x) end'
994Copy stdin to stdout
1lua
i3rot
perl -pe ''
994Copy stdin to stdout
2perl
gbn4e
python -c 'import sys; sys.stdout.write(sys.stdin.read())'
994Copy stdin to stdout
3python
rpdgq
Rscript -e 'cat(readLines(file("stdin")))'
994Copy stdin to stdout
13r
uj8vx
use std::io; fn main() { io::copy(&mut io::stdin().lock(), &mut io::stdout().lock()); }
994Copy stdin to stdout
15rust
hezj2
object CopyStdinToStdout extends App { io.Source.fromInputStream(System.in).getLines().foreach(println) }
994Copy stdin to stdout
16scala
pqybj
typedef struct{ int num,den; }fraction; fraction examples[] = {{1,2}, {3,1}, {23,8}, {13,11}, {22,7}, {-151,77}}; fraction sqrt2[] = {{14142,10000}, {141421,100000}, {1414214,1000000}, {14142136,10000000}}; fraction pi[] = {{31,10}, {314,100}, {3142,1000}, {31428,10000}, {314285,100000}, {3142857,1000000}, {31428571,10000000}, {314285714,100000000}}; int r2cf(int *numerator,int *denominator) { int quotient=0,temp; if(denominator != 0) { quotient = *numerator / *denominator; temp = *numerator; *numerator = *denominator; *denominator = temp % *denominator; } return quotient; } int main() { int i; printf(); for(i=0;i<sizeof(examples)/sizeof(fraction);i++) { printf(,examples[i].num,examples[i].den); while(examples[i].den != 0){ printf(,r2cf(&examples[i].num,&examples[i].den)); } } printf(,251); for(i=0;i<sizeof(sqrt2)/sizeof(fraction);i++) { printf(,sqrt2[i].num,sqrt2[i].den); while(sqrt2[i].den != 0){ printf(,r2cf(&sqrt2[i].num,&sqrt2[i].den)); } } printf(,227); for(i=0;i<sizeof(pi)/sizeof(fraction);i++) { printf(,pi[i].num,pi[i].den); while(pi[i].den != 0){ printf(,r2cf(&pi[i].num,&pi[i].den)); } } return 0; }
995Continued fraction/Arithmetic/Construct from rational number
5c
95em1
void rat_approx(double f, int64_t md, int64_t *num, int64_t *denom) { int64_t a, h[3] = { 0, 1, 0 }, k[3] = { 1, 0, 0 }; int64_t x, d, n = 1; int i, neg = 0; if (md <= 1) { *denom = 1; *num = (int64_t) f; return; } if (f < 0) { neg = 1; f = -f; } while (f != floor(f)) { n <<= 1; f *= 2; } d = f; for (i = 0; i < 64; i++) { a = n ? d / n : 0; if (i && !a) break; x = d; d = n; n = x % n; x = a; if (k[1] * a + k[0] >= md) { x = (md - k[0]) / k[1]; if (x * 2 >= a || k[1] >= md) i = 65; else break; } h[2] = x * h[1] + h[0]; h[0] = h[1]; h[1] = h[2]; k[2] = x * k[1] + k[0]; k[0] = k[1]; k[1] = k[2]; } *denom = k[1]; *num = neg ? -h[1] : h[1]; } int main() { int i; int64_t d, n; double f; printf(, f = 1.0/7); for (i = 1; i <= 20000000; i *= 16) { printf(, i); rat_approx(f, i, &n, &d); printf(, n, d); } printf(, f = atan2(1,1) * 4); for (i = 1; i <= 20000000; i *= 16) { printf(, i); rat_approx(f, i, &n, &d); printf(, n, d); } return 0; }
996Convert decimal number to rational
5c
mu1ys
(defn r2cf [n d] (if-not (= d 0) (cons (quot n d) (lazy-seq (r2cf d (rem n d)))))) (def demo '((1 2) (3 1) (23 8) (13 11) (22 7) (-151 77) (14142 10000) (141421 100000) (1414214 1000000) (14142136 10000000) (31 10) (314 100) (3142 1000) (31428 10000) (314285 100000) (3142857 1000000) (31428571 10000000) (314285714 100000000) (3141592653589793 1000000000000000))) (doseq [inputs demo :let [outputs (r2cf (first inputs) (last inputs))]] (println inputs "
995Continued fraction/Arithmetic/Construct from rational number
6clojure
uj0vi
user=> (rationalize 0.1) 1/10 user=> (rationalize 0.9054054) 4527027/5000000 user=> (rationalize 0.518518) 259259/500000 user=> (rationalize Math/PI) 3141592653589793/1000000000000000
996Convert decimal number to rational
6clojure
v7q2f
package cf import ( "fmt" "strings" )
995Continued fraction/Arithmetic/Construct from rational number
0go
e89a6
import Data.Ratio ((%)) real2cf :: (RealFrac a, Integral b) => a -> [b] real2cf x = let (i, f) = properFraction x in i: if f == 0 then [] else real2cf (1 / f) main :: IO () main = mapM_ print [ real2cf (13 % 11) , take 20 $ real2cf (sqrt 2) ]
995Continued fraction/Arithmetic/Construct from rational number
8haskell
3lbzj
import java.util.Iterator; import java.util.List; import java.util.Map; public class ConstructFromRationalNumber { private static class R2cf implements Iterator<Integer> { private int num; private int den; R2cf(int num, int den) { this.num = num; this.den = den; } @Override public boolean hasNext() { return den != 0; } @Override public Integer next() { int div = num / den; int rem = num % den; num = den; den = rem; return div; } } private static void iterate(R2cf generator) { generator.forEachRemaining(n -> System.out.printf("%d ", n)); System.out.println(); } public static void main(String[] args) { List<Map.Entry<Integer, Integer>> fracs = List.of( Map.entry(1, 2), Map.entry(3, 1), Map.entry(23, 8), Map.entry(13, 11), Map.entry(22, 7), Map.entry(-151, 77) ); for (Map.Entry<Integer, Integer> frac : fracs) { System.out.printf("%4d /%-2d = ", frac.getKey(), frac.getValue()); iterate(new R2cf(frac.getKey(), frac.getValue())); } System.out.println("\nSqrt(2) ->"); List<Map.Entry<Integer, Integer>> root2 = List.of( Map.entry( 14_142, 10_000), Map.entry( 141_421, 100_000), Map.entry( 1_414_214, 1_000_000), Map.entry(14_142_136, 10_000_000) ); for (Map.Entry<Integer, Integer> frac : root2) { System.out.printf("%8d /%-8d = ", frac.getKey(), frac.getValue()); iterate(new R2cf(frac.getKey(), frac.getValue())); } System.out.println("\nPi ->"); List<Map.Entry<Integer, Integer>> pi = List.of( Map.entry( 31, 10), Map.entry( 314, 100), Map.entry( 3_142, 1_000), Map.entry( 31_428, 10_000), Map.entry( 314_285, 100_000), Map.entry( 3_142_857, 1_000_000), Map.entry( 31_428_571, 10_000_000), Map.entry(314_285_714, 100_000_000) ); for (Map.Entry<Integer, Integer> frac : pi) { System.out.printf("%9d /%-9d = ", frac.getKey(), frac.getValue()); iterate(new R2cf(frac.getKey(), frac.getValue())); } } }
995Continued fraction/Arithmetic/Construct from rational number
9java
i3gos
package main import ( "fmt" "math/big" ) func main() { for _, d := range []string{"0.9054054", "0.518518", "0.75"} { if r, ok := new(big.Rat).SetString(d); ok { fmt.Println(d, "=", r) } else { fmt.Println(d, "invalid decimal number") } } }
996Convert decimal number to rational
0go
a0y1f
null
995Continued fraction/Arithmetic/Construct from rational number
11kotlin
qn2x1
Number.metaClass.mixin RationalCategory [ 0.9054054, 0.518518, 0.75, Math.E, -0.423310825, Math.PI, 0.111111111111111111111111 ].each{ printf "%30.27f%s\n", it, it as Rational }
996Convert decimal number to rational
7groovy
hefj9
Prelude> map (\d -> Ratio.approxRational d 0.0001) [0.9054054, 0.518518, 0.75] [67 % 74,14 % 27,3 % 4] Prelude> [0.9054054, 0.518518, 0.75] :: [Rational] [4527027 % 5000000,259259 % 500000,3 % 4] Prelude> map (fst . head . Numeric.readFloat) ["0.9054054", "0.518518", "0.75"] :: [Rational] [4527027 % 5000000,259259 % 500000,3 % 4]
996Convert decimal number to rational
8haskell
zcht0
import org.apache.commons.math3.fraction.BigFraction; public class Test { public static void main(String[] args) { double[] n = {0.750000000, 0.518518000, 0.905405400, 0.142857143, 3.141592654, 2.718281828, -0.423310825, 31.415926536}; for (double d : n) System.out.printf("%-12s:%s%n", d, new BigFraction(d, 0.00000002D, 10000)); } }
996Convert decimal number to rational
9java
oz58d
(() => { 'use strict'; const main = () => showJSON( map(
996Convert decimal number to rational
10javascript
t9jfm
$|=1; sub rc2f { my($num, $den) = @_; return sub { return unless $den; my $q = int($num/$den); ($num, $den) = ($den, $num - $q*$den); $q; }; } sub rcshow { my $sub = shift; print "["; my $n = $sub->(); print "$n" if defined $n; print "; $n" while defined($n = $sub->()); print "]\n"; } rcshow(rc2f(@$_)) for ([1,2],[3,1],[23,8],[13,11],[22,7],[-151,77]); print "\n"; rcshow(rc2f(@$_)) for ([14142,10000],[141421,100000],[1414214,1000000],[14142136,10000000]); print "\n"; rcshow(rc2f(314285714,100000000));
995Continued fraction/Arithmetic/Construct from rational number
2perl
v7s20
null
996Convert decimal number to rational
11kotlin
xicws
def r2cf(n1,n2): while n2: n1, (t1, n2) = n2, divmod(n1, n2) yield t1 print(list(r2cf(1,2))) print(list(r2cf(3,1))) print(list(r2cf(23,8))) print(list(r2cf(13,11))) print(list(r2cf(22,7))) print(list(r2cf(14142,10000))) print(list(r2cf(141421,100000))) print(list(r2cf(1414214,1000000))) print(list(r2cf(14142136,10000000)))
995Continued fraction/Arithmetic/Construct from rational number
3python
uj0vd
for _,v in ipairs({ 0.9054054, 0.518518, 0.75, math.pi }) do local n, d, dmax, eps = 1, 1, 1e7, 1e-15 while math.abs(n/d-v)>eps and d<dmax do d=d+1 n=math.floor(v*d) end print(string.format("%15.13f
996Convert decimal number to rational
1lua
qnlx0
def r2cf(n1,n2) while n2 > 0 n1, (t1, n2) = n2, n1.divmod(n2) yield t1 end end
995Continued fraction/Arithmetic/Construct from rational number
14ruby
4ko5p
struct R2cf { n1: i64, n2: i64 }
995Continued fraction/Arithmetic/Construct from rational number
15rust
gbi4o
sub gcd { my ($m, $n) = @_; ($m, $n) = ($n, $m % $n) while $n; return $m } sub rat_machine { my $n = shift; my $denom = 1; while ($n != int $n) { $n *= 2; $denom <<= 1; } if ($n) { my $g = gcd($n, $denom); $n /= $g; $denom /= $g; } return $n, $denom; } sub get_denom { my ($num, $denom) = (1, pop @_); for (reverse @_) { ($num, $denom) = ($denom, $_ * $denom + $num); } wantarray ? ($num, $denom) : $denom } sub best_approx { my ($n, $limit) = @_; my ($denom, $neg); if ($n < 0) { $neg = 1; $n = -$n; } my $int = int($n); my ($num, $denom, @coef) = (1, $n - $int); while (1) { last if $limit * $denom < 1; my $i = int($num / $denom); push @coef, $i; if (get_denom(@coef) > $limit) { pop @coef; last; } ($num, $denom) = ($denom, $num - $i * $denom); } ($num, $denom) = get_denom @coef; $num += $denom * $int; return $neg ? -$num : $num, $denom; } sub rat_string { my $n = shift; my $denom = 1; my $neg; $n =~ s/\.0+$//; return $n, 1 unless $n =~ /\./; if ($n =~ /^-/) { $neg = 1; $n =~ s/^-//; } $denom *= 10 while $n =~ s/\.(\d)/$1\./; $n =~ s/\.$//; $n =~ s/^0*//; if ($n) { my $g = gcd($n, $denom); $n /= $g; $denom /= $g; } return $neg ? -$n : $n, $denom; } my $limit = 1e8; my $x = 3/8; print "3/8 = $x:\n"; printf "machine:%d/%d\n", rat_machine $x; printf "string: %d/%d\n", rat_string $x; printf "approx below $limit: %d/%d\n", best_approx $x, $limit; $x = 137/4291; print "\n137/4291 = $x:\n"; printf "machine:%d/%d\n", rat_machine $x; printf "string: %d/%d\n", rat_string $x; printf "approx below $limit: %d/%d\n", best_approx $x, $limit; $x = sqrt(1/2); print "\n1/sqrt(2) = $x\n"; printf "machine:%d/%d\n", rat_machine $x; printf "string: %d/%d\n", rat_string $x; printf "approx below 10: %d/%d\n", best_approx $x, 10; printf "approx below 100: %d/%d\n", best_approx $x, 100; printf "approx below 1000: %d/%d\n", best_approx $x, 1000; printf "approx below 10000: %d/%d\n", best_approx $x, 10000; printf "approx below 100000: %d/%d\n", best_approx $x, 100000; printf "approx below $limit: %d/%d\n", best_approx $x, $limit; $x = -4 * atan2(1,1); print "\n-Pi = $x\n"; printf "machine:%d/%d\n", rat_machine $x; printf "string: %d/%d\n", rat_string $x; for (map { 10 ** $_ } 1 .. 10) { printf "approx below%g:%d /%d\n", $_, best_approx($x, $_) }
996Convert decimal number to rational
2perl
2rxlf
int main() { size_t len; char src[] = ; char dst1[80], dst2[80]; char *dst3, *ref; strcpy(dst1, src); len = strlen(src); if (len >= sizeof dst2) { fputs(, stderr); exit(1); } memcpy(dst2, src, len + 1); dst3 = strdup(src); if (dst3 == NULL) { perror(); exit(1); } ref = src; memset(src, '-', 5); printf(, src); printf(, dst1); printf(, dst2); printf(, dst3); printf(, ref); free(dst3); return 0; }
997Copy a string
5c
4k05t
function asRational($val, $tolerance = 1.e-6) { if ($val == (int) $val) { return $val; } $h1=1; $h2=0; $k1=0; $k2=1; $b = 1 / $val; do { $b = 1 / $b; $a = floor($b); $aux = $h1; $h1 = $a * $h1 + $h2; $h2 = $aux; $aux = $k1; $k1 = $a * $k1 + $k2; $k2 = $aux; $b = $b - $a; } while (abs($val-$h1/$k1) > $val * $tolerance); return $h1.'/'.$k1; } echo asRational(1/5).; echo asRational(1/4).; echo asRational(1/3).; echo asRational(5).;
996Convert decimal number to rational
12php
sd2qs
(let [s "hello" s1 s] (println s s1))
997Copy a string
6clojure
hedjr
>>> from fractions import Fraction >>> for d in (0.9054054, 0.518518, 0.75): print(d, Fraction.from_float(d).limit_denominator(100)) 0.9054054 67/74 0.518518 14/27 0.75 3/4 >>> for d in '0.9054054 0.518518 0.75'.split(): print(d, Fraction(d)) 0.9054054 4527027/5000000 0.518518 259259/500000 0.75 3/4 >>>
996Convert decimal number to rational
3python
v7q29
ratio<-function(decimal){ denominator=1 while(nchar(decimal*denominator)!=nchar(round(decimal*denominator))){ denominator=denominator+1 } str=paste(decimal*denominator,"/",sep="") str=paste(str,denominator,sep="") return(str) }
996Convert decimal number to rational
13r
95amg
> '0.9054054 0.518518 0.75'.split.each { |d| puts % [d, Rational(d)] } 0.9054054 4527027/5000000 0.518518 259259/500000 0.75 3/4 => [, , ]
996Convert decimal number to rational
14ruby
5h0uj
extern crate rand; extern crate num; use num::Integer; use rand::Rng; fn decimal_to_rational (mut n: f64) -> [isize;2] {
996Convert decimal number to rational
15rust
4k85u
import org.apache.commons.math3.fraction.BigFraction object Number2Fraction extends App { val n = Array(0.750000000, 0.518518000, 0.905405400, 0.142857143, 3.141592654, 2.718281828, -0.423310825, 31.415926536) for (d <- n) println(f"$d%-12s: ${new BigFraction(d, 0.00000002D, 10000)}%s") }
996Convert decimal number to rational
16scala
71nr9
char* seconds2string(unsigned long seconds) { int i; const unsigned long s = 1; const unsigned long m = 60 * s; const unsigned long h = 60 * m; const unsigned long d = 24 * h; const unsigned long w = 7 * d; const unsigned long coeff[5] = { w, d, h, m, s }; const char units[5][4] = { , , , , }; static char buffer[256]; char* ptr = buffer; for ( i = 0; i < 5; i++ ) { unsigned long value; value = seconds / coeff[i]; seconds = seconds % coeff[i]; if ( value ) { if ( ptr != buffer ) ptr += sprintf(ptr, ); ptr += sprintf(ptr,,value,units[i]); } } return buffer; } int main(int argc, char argv[]) { unsigned long seconds; if ( (argc < 2) && scanf( , &seconds ) || (argc >= 2) && sscanf( argv[1], , & seconds ) ) { printf( , seconds2string(seconds) ); return EXIT_SUCCESS; } return EXIT_FAILURE; }
998Convert seconds to compound duration
5c
5hquk
type eatable interface { eat() }
999Constrained genericity
0go
2ral7
class Eatable a where eat :: a -> String
999Constrained genericity
8haskell
a0z1g
package main import ( "fmt" "rcu" ) const LIMIT = 999999 var primes = rcu.Primes(LIMIT) func longestSeq(dir string) { pd := 0 longSeqs := [][]int{{2}} currSeq := []int{2} for i := 1; i < len(primes); i++ { d := primes[i] - primes[i-1] if (dir == "ascending" && d <= pd) || (dir == "descending" && d >= pd) { if len(currSeq) > len(longSeqs[0]) { longSeqs = [][]int{currSeq} } else if len(currSeq) == len(longSeqs[0]) { longSeqs = append(longSeqs, currSeq) } currSeq = []int{primes[i-1], primes[i]} } else { currSeq = append(currSeq, primes[i]) } pd = d } if len(currSeq) > len(longSeqs[0]) { longSeqs = [][]int{currSeq} } else if len(currSeq) == len(longSeqs[0]) { longSeqs = append(longSeqs, currSeq) } fmt.Println("Longest run(s) of primes with", dir, "differences is", len(longSeqs[0]), ":") for _, ls := range longSeqs { var diffs []int for i := 1; i < len(ls); i++ { diffs = append(diffs, ls[i]-ls[i-1]) } for i := 0; i < len(ls)-1; i++ { fmt.Print(ls[i], " (", diffs[i], ") ") } fmt.Println(ls[len(ls)-1]) } fmt.Println() } func main() { fmt.Println("For primes < 1 million:\n") for _, dir := range []string{"ascending", "descending"} { longestSeq(dir) } }
1,000Consecutive primes with ascending or descending differences
0go
bxnkh
typedef double (*coeff_func)(unsigned n); double calc(coeff_func f_a, coeff_func f_b, unsigned expansions) { double a, b, r; a = b = r = 0.0; unsigned i; for (i = expansions; i > 0; i--) { a = f_a(i); b = f_b(i); r = b / (a + r); } a = f_a(0); return a + r; } double sqrt2_a(unsigned n) { return n ? 2.0 : 1.0; } double sqrt2_b(unsigned n) { return 1.0; } double napier_a(unsigned n) { return n ? n : 2.0; } double napier_b(unsigned n) { return n > 1.0 ? n - 1.0 : 1.0; } double pi_a(unsigned n) { return n ? 6.0 : 3.0; } double pi_b(unsigned n) { double c = 2.0 * n - 1.0; return c * c; } int main(void) { double sqrt2, napier, pi; sqrt2 = calc(sqrt2_a, sqrt2_b, 1000); napier = calc(napier_a, napier_b, 1000); pi = calc(pi_a, pi_b, 1000); printf(, sqrt2, napier, pi); return 0; }
1,001Continued fraction
5c
rpqg7
(require '[clojure.string:as string]) (def seconds-in-minute 60) (def seconds-in-hour (* 60 seconds-in-minute)) (def seconds-in-day (* 24 seconds-in-hour)) (def seconds-in-week (* 7 seconds-in-day)) (defn seconds->duration [seconds] (let [weeks ((juxt quot rem) seconds seconds-in-week) wk (first weeks) days ((juxt quot rem) (last weeks) seconds-in-day) d (first days) hours ((juxt quot rem) (last days) seconds-in-hour) hr (first hours) min (quot (last hours) seconds-in-minute) sec (rem (last hours) seconds-in-minute)] (string/join ", " (filter #(not (string/blank? %)) (conj [] (when (> wk 0) (str wk " wk")) (when (> d 0) (str d " d")) (when (> hr 0) (str hr " hr")) (when (> min 0) (str min " min")) (when (> sec 0) (str sec " sec"))))))) (seconds->duration 7259) (seconds->duration 86400) (seconds->duration 6000000)
998Convert seconds to compound duration
6clojure
jai7m
interface Eatable { void eat(); }
999Constrained genericity
9java
jao7c
null
999Constrained genericity
11kotlin
5hxua
import Data.Numbers.Primes (primes) consecutives equiv = filter ((> 1) . length) . go [] where go r [] = [r] go [] (h: t) = go [h] t go (y: ys) (h: t) | y `equiv` h = go (h: y: ys) t | otherwise = (y: ys): go [h] t maximumBy g (h: t) = foldr f h t where f r x = if g r < g x then x else r task ord n = reverse $ p + s: p: (fst <$> rest) where (p, s): rest = maximumBy length $ consecutives (\(_, a) (_, b) -> a `ord` b) $ differences $ takeWhile (< n) primes differences l = zip l $ zipWith (-) (tail l) l
1,000Consecutive primes with ascending or descending differences
8haskell
dyun4
function findcps(primelist, fcmp) local currlist = {primelist[1]} local longlist, prevdiff = currlist, 0 for i = 2, #primelist do local diff = primelist[i] - primelist[i-1] if fcmp(diff, prevdiff) then currlist[#currlist+1] = primelist[i] if #currlist > #longlist then longlist = currlist end else currlist = {primelist[i-1], primelist[i]} end prevdiff = diff end return longlist end primegen:generate(nil, 1000000) cplist = findcps(primegen.primelist, function(a,b) return a>b end) print("ASC ("..#cplist.."): ["..table.concat(cplist, " ").."]") cplist = findcps(primegen.primelist, function(a,b) return a<b end) print("DESC ("..#cplist.."): ["..table.concat(cplist, " ").."]")
1,000Consecutive primes with ascending or descending differences
1lua
e8zac