{ // 获取包含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 !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转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 !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; 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, 'OCR模型免费转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 }); }); } })(); \") == [\"165.91.15.131\"]\n","\n assert candidate(\"Current IP CheckCurrent IP Address: 165.91.15.131 and this is not a IP Address: 165.91.15\") == [\"165.91.15.131\"]\n","\n assert candidate(\"Current IP CheckCurrent IP Address: 192.168.1.1 & this is another IP address: 192.168.1.2\") == [\"192.168.1.1\", \"192.168.1.2\"]\n"],"string":"[\n \"\\n assert candidate(\\\"Current IP CheckCurrent IP Address: 165.91.15.131\\\") == [\\\"165.91.15.131\\\"]\\n\",\n \"\\n assert candidate(\\\"Current IP CheckCurrent IP Address: 165.91.15.131 and this is not a IP Address: 165.91.15\\\") == [\\\"165.91.15.131\\\"]\\n\",\n \"\\n assert candidate(\\\"Current IP CheckCurrent IP Address: 192.168.1.1 & this is another IP address: 192.168.1.2\\\") == [\\\"192.168.1.1\\\", \\\"192.168.1.2\\\"]\\n\"\n]"},"entry_point":{"kind":"string","value":"f_2890896"},"intent":{"kind":"string","value":"extract ip address `ip` from an html string `s`"},"library":{"kind":"list like","value":["re"],"string":"[\n \"re\"\n]"},"docs":{"kind":"list like","value":[{"function":"re.findall","text":"re.findall(pattern, string, flags=0) \nReturn all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result. Changed in version 3.7: Non-empty matches can now start just after a previous empty match.","title":"python.library.re#re.findall"}],"string":"[\n {\n \"function\": \"re.findall\",\n \"text\": \"re.findall(pattern, string, flags=0) \\nReturn all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result. Changed in version 3.7: Non-empty matches can now start just after a previous empty match.\",\n \"title\": \"python.library.re#re.findall\"\n }\n]"}}},{"rowIdx":264,"cells":{"task_id":{"kind":"number","value":29836836,"string":"29,836,836"},"prompt":{"kind":"string","value":"def f_29836836(df):\n\treturn "},"suffix":{"kind":"string","value":""},"canonical_solution":{"kind":"string","value":"df.groupby('A').filter(lambda x: len(x) > 1)"},"test_start":{"kind":"string","value":"\nimport pandas as pd\n\ndef check(candidate):"},"test":{"kind":"list like","value":["\n assert candidate(pd.DataFrame([[1, 2], [1, 4], [5, 6]], columns=['A', 'B'])).equals(pd.DataFrame([[1, 2], [1, 4]], columns=['A', 'B'])) is True\n","\n assert candidate(pd.DataFrame([[1, 2], [1, 4], [1, 6]], columns=['A', 'B'])).equals(pd.DataFrame([[1, 2], [1, 4], [1, 6]], columns=['A', 'B'])) is True\n"],"string":"[\n \"\\n assert candidate(pd.DataFrame([[1, 2], [1, 4], [5, 6]], columns=['A', 'B'])).equals(pd.DataFrame([[1, 2], [1, 4]], columns=['A', 'B'])) is True\\n\",\n \"\\n assert candidate(pd.DataFrame([[1, 2], [1, 4], [1, 6]], columns=['A', 'B'])).equals(pd.DataFrame([[1, 2], [1, 4], [1, 6]], columns=['A', 'B'])) is True\\n\"\n]"},"entry_point":{"kind":"string","value":"f_29836836"},"intent":{"kind":"string","value":"filter dataframe `df` by values in column `A` that appear more than once"},"library":{"kind":"list like","value":["pandas"],"string":"[\n \"pandas\"\n]"},"docs":{"kind":"list like","value":[{"function":"pandas.dataframe.groupby","text":"pandas.DataFrame.groupby DataFrame.groupby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=NoDefault.no_default, observed=False, dropna=True)[source]\n \nGroup DataFrame using a mapper or by a Series of columns. A groupby operation involves some combination of splitting the object, applying a function, and combining the results. This can be used to group large amounts of data and compute operations on these groups. Parameters ","title":"pandas.reference.api.pandas.dataframe.groupby"},{"function":"dataframegroupby.filter","text":"pandas.core.groupby.DataFrameGroupBy.filter DataFrameGroupBy.filter(func, dropna=True, *args, **kwargs)[source]\n \nReturn a copy of a DataFrame excluding filtered elements. Elements from groups are filtered if they do not satisfy the boolean criterion specified by func. Parameters ","title":"pandas.reference.api.pandas.core.groupby.dataframegroupby.filter"}],"string":"[\n {\n \"function\": \"pandas.dataframe.groupby\",\n \"text\": \"pandas.DataFrame.groupby DataFrame.groupby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=NoDefault.no_default, observed=False, dropna=True)[source]\\n \\nGroup DataFrame using a mapper or by a Series of columns. A groupby operation involves some combination of splitting the object, applying a function, and combining the results. This can be used to group large amounts of data and compute operations on these groups. Parameters \",\n \"title\": \"pandas.reference.api.pandas.dataframe.groupby\"\n },\n {\n \"function\": \"dataframegroupby.filter\",\n \"text\": \"pandas.core.groupby.DataFrameGroupBy.filter DataFrameGroupBy.filter(func, dropna=True, *args, **kwargs)[source]\\n \\nReturn a copy of a DataFrame excluding filtered elements. Elements from groups are filtered if they do not satisfy the boolean criterion specified by func. Parameters \",\n \"title\": \"pandas.reference.api.pandas.core.groupby.dataframegroupby.filter\"\n }\n]"}}},{"rowIdx":265,"cells":{"task_id":{"kind":"number","value":2545397,"string":"2,545,397"},"prompt":{"kind":"string","value":"def f_2545397(myfile):\n\treturn "},"suffix":{"kind":"string","value":""},"canonical_solution":{"kind":"string","value":"[x for x in myfile if x != '']"},"test_start":{"kind":"string","value":"\ndef check(candidate):"},"test":{"kind":"list like","value":["\n with open('./tmp.txt', 'w') as fw: \n for s in [\"hello\", \"world\", \"!!!\"]:\n fw.write(f\"{s}\\n\")\n\n with open('./tmp.txt', 'r') as myfile:\n lines = candidate(myfile)\n assert isinstance(lines, list)\n assert len(lines) == 3\n assert lines[0].strip() == \"hello\"\n"],"string":"[\n \"\\n with open('./tmp.txt', 'w') as fw: \\n for s in [\\\"hello\\\", \\\"world\\\", \\\"!!!\\\"]:\\n fw.write(f\\\"{s}\\\\n\\\")\\n\\n with open('./tmp.txt', 'r') as myfile:\\n lines = candidate(myfile)\\n assert isinstance(lines, list)\\n assert len(lines) == 3\\n assert lines[0].strip() == \\\"hello\\\"\\n\"\n]"},"entry_point":{"kind":"string","value":"f_2545397"},"intent":{"kind":"string","value":"append each line in file `myfile` into a list"},"library":{"kind":"list like","value":[],"string":"[]"},"docs":{"kind":"list like","value":[],"string":"[]"}}},{"rowIdx":266,"cells":{"task_id":{"kind":"number","value":2545397,"string":"2,545,397"},"prompt":{"kind":"string","value":"def f_2545397():\n\t"},"suffix":{"kind":"string","value":"\n\treturn lst"},"canonical_solution":{"kind":"string","value":"lst = list(map(int, open('filename.txt').readlines()))"},"test_start":{"kind":"string","value":"\nimport pandas as pd\n\ndef check(candidate):"},"test":{"kind":"list like","value":["\n with open('./filename.txt', 'w') as fw: \n for s in [\"1\", \"2\", \"100\"]:\n fw.write(f\"{s}\\n\")\n\n assert candidate() == [1, 2, 100]\n"],"string":"[\n \"\\n with open('./filename.txt', 'w') as fw: \\n for s in [\\\"1\\\", \\\"2\\\", \\\"100\\\"]:\\n fw.write(f\\\"{s}\\\\n\\\")\\n\\n assert candidate() == [1, 2, 100]\\n\"\n]"},"entry_point":{"kind":"string","value":"f_2545397"},"intent":{"kind":"string","value":"Get a list of integers `lst` from a file `filename.txt`"},"library":{"kind":"list like","value":["pandas"],"string":"[\n \"pandas\"\n]"},"docs":{"kind":"list like","value":[],"string":"[]"}}},{"rowIdx":267,"cells":{"task_id":{"kind":"number","value":35420052,"string":"35,420,052"},"prompt":{"kind":"string","value":"def f_35420052(plt, mappable, ax3):\n\t"},"suffix":{"kind":"string","value":"\n\treturn plt"},"canonical_solution":{"kind":"string","value":"plt.colorbar(mappable=mappable, cax=ax3)"},"test_start":{"kind":"string","value":"\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom obspy.core.trace import Trace\nfrom obspy.imaging.spectrogram import spectrogram\n\ndef check(candidate):"},"test":{"kind":"list like","value":["\n spl1 = Trace(data=np.arange(0, 10))\n fig = plt.figure()\n ax1 = fig.add_axes([0.1, 0.75, 0.7, 0.2]) #[left bottom width height]\n ax2 = fig.add_axes([0.1, 0.1, 0.7, 0.60], sharex=ax1)\n ax3 = fig.add_axes([0.83, 0.1, 0.03, 0.6])\n\n #make time vector\n t = np.arange(spl1.stats.npts) / spl1.stats.sampling_rate\n\n #plot waveform (top subfigure) \n ax1.plot(t, spl1.data, 'k')\n\n #plot spectrogram (bottom subfigure)\n spl2 = spl1\n fig = spl2.spectrogram(show=False, axes=ax2, wlen=10)\n mappable = ax2.images[0]\n candidate(plt, mappable, ax3)\n \n im=ax2.images\n assert im[-1].colorbar is not None\n"],"string":"[\n \"\\n spl1 = Trace(data=np.arange(0, 10))\\n fig = plt.figure()\\n ax1 = fig.add_axes([0.1, 0.75, 0.7, 0.2]) #[left bottom width height]\\n ax2 = fig.add_axes([0.1, 0.1, 0.7, 0.60], sharex=ax1)\\n ax3 = fig.add_axes([0.83, 0.1, 0.03, 0.6])\\n\\n #make time vector\\n t = np.arange(spl1.stats.npts) / spl1.stats.sampling_rate\\n\\n #plot waveform (top subfigure) \\n ax1.plot(t, spl1.data, 'k')\\n\\n #plot spectrogram (bottom subfigure)\\n spl2 = spl1\\n fig = spl2.spectrogram(show=False, axes=ax2, wlen=10)\\n mappable = ax2.images[0]\\n candidate(plt, mappable, ax3)\\n \\n im=ax2.images\\n assert im[-1].colorbar is not None\\n\"\n]"},"entry_point":{"kind":"string","value":"f_35420052"},"intent":{"kind":"string","value":"add color bar with image `mappable` to plot `plt`"},"library":{"kind":"list like","value":["matplotlib","numpy","obspy"],"string":"[\n \"matplotlib\",\n \"numpy\",\n \"obspy\"\n]"},"docs":{"kind":"list like","value":[{"function":"plt.colorbar","text":"matplotlib.pyplot.colorbar matplotlib.pyplot.colorbar(mappable=None, cax=None, ax=None, **kw)[source]\n \nAdd a colorbar to a plot. Parameters ","title":"matplotlib._as_gen.matplotlib.pyplot.colorbar"}],"string":"[\n {\n \"function\": \"plt.colorbar\",\n \"text\": \"matplotlib.pyplot.colorbar matplotlib.pyplot.colorbar(mappable=None, cax=None, ax=None, **kw)[source]\\n \\nAdd a colorbar to a plot. Parameters \",\n \"title\": \"matplotlib._as_gen.matplotlib.pyplot.colorbar\"\n }\n]"}}},{"rowIdx":268,"cells":{"task_id":{"kind":"number","value":29903025,"string":"29,903,025"},"prompt":{"kind":"string","value":"def f_29903025(df):\n\treturn "},"suffix":{"kind":"string","value":""},"canonical_solution":{"kind":"string","value":"Counter(' '.join(df['text']).split()).most_common(100)"},"test_start":{"kind":"string","value":"\nimport pandas as pd\nfrom collections import Counter\n \ndef check(candidate):"},"test":{"kind":"list like","value":["\n df = pd.DataFrame({\"text\": [\n 'Python is a high-level, general-purpose programming language.', \n 'Its design philosophy emphasizes code readability with the use of significant indentation. Python is dynamically-typed and garbage-collected.'\n ]})\n assert candidate(df) == [('Python', 2),('is', 2),('a', 1),('high-level,', 1),('general-purpose', 1),\n ('programming', 1),('language.', 1),('Its', 1),('design', 1),('philosophy', 1),('emphasizes', 1),\n ('code', 1),('readability', 1),('with', 1), ('the', 1),('use', 1),('of', 1),('significant', 1),\n ('indentation.', 1),('dynamically-typed', 1),('and', 1),('garbage-collected.', 1)]\n"],"string":"[\n \"\\n df = pd.DataFrame({\\\"text\\\": [\\n 'Python is a high-level, general-purpose programming language.', \\n 'Its design philosophy emphasizes code readability with the use of significant indentation. Python is dynamically-typed and garbage-collected.'\\n ]})\\n assert candidate(df) == [('Python', 2),('is', 2),('a', 1),('high-level,', 1),('general-purpose', 1),\\n ('programming', 1),('language.', 1),('Its', 1),('design', 1),('philosophy', 1),('emphasizes', 1),\\n ('code', 1),('readability', 1),('with', 1), ('the', 1),('use', 1),('of', 1),('significant', 1),\\n ('indentation.', 1),('dynamically-typed', 1),('and', 1),('garbage-collected.', 1)]\\n\"\n]"},"entry_point":{"kind":"string","value":"f_29903025"},"intent":{"kind":"string","value":"count most frequent 100 words in column 'text' of dataframe `df`"},"library":{"kind":"list like","value":["collections","pandas"],"string":"[\n \"collections\",\n \"pandas\"\n]"},"docs":{"kind":"list like","value":[{"function":"Counter.most_common","text":"most_common([n]) \nReturn a list of the n most common elements and their counts from the most common to the least. If n is omitted or None, most_common() returns all elements in the counter. Elements with equal counts are ordered in the order first encountered: >>> Counter('abracadabra').most_common(3)\n[('a', 5), ('b', 2), ('r', 2)]","title":"python.library.collections#collections.Counter.most_common"}],"string":"[\n {\n \"function\": \"Counter.most_common\",\n \"text\": \"most_common([n]) \\nReturn a list of the n most common elements and their counts from the most common to the least. If n is omitted or None, most_common() returns all elements in the counter. Elements with equal counts are ordered in the order first encountered: >>> Counter('abracadabra').most_common(3)\\n[('a', 5), ('b', 2), ('r', 2)]\",\n \"title\": \"python.library.collections#collections.Counter.most_common\"\n }\n]"}}},{"rowIdx":269,"cells":{"task_id":{"kind":"number","value":7378180,"string":"7,378,180"},"prompt":{"kind":"string","value":"def f_7378180():\n\treturn "},"suffix":{"kind":"string","value":""},"canonical_solution":{"kind":"string","value":"list(itertools.combinations((1, 2, 3), 2))"},"test_start":{"kind":"string","value":"\nimport itertools\n\ndef check(candidate):"},"test":{"kind":"list like","value":["\n assert candidate() == [(1, 2), (1, 3), (2, 3)]\n"],"string":"[\n \"\\n assert candidate() == [(1, 2), (1, 3), (2, 3)]\\n\"\n]"},"entry_point":{"kind":"string","value":"f_7378180"},"intent":{"kind":"string","value":"generate all 2-element subsets of tuple `(1, 2, 3)`"},"library":{"kind":"list like","value":["itertools"],"string":"[\n \"itertools\"\n]"},"docs":{"kind":"list like","value":[{"function":"itertools.combinations","text":"itertools.combinations(iterable, r) \nReturn r length subsequences of elements from the input iterable. The combination tuples are emitted in lexicographic ordering according to the order of the input iterable. So, if the input iterable is sorted, the combination tuples will be produced in sorted order. Elements are treated as unique based on their position, not on their value. So if the input elements are unique, there will be no repeat values in each combination. Roughly equivalent to: def combinations(iterable, r):\n # combinations('ABCD', 2) --> AB AC AD BC BD CD","title":"python.library.itertools#itertools.combinations"}],"string":"[\n {\n \"function\": \"itertools.combinations\",\n \"text\": \"itertools.combinations(iterable, r) \\nReturn r length subsequences of elements from the input iterable. The combination tuples are emitted in lexicographic ordering according to the order of the input iterable. So, if the input iterable is sorted, the combination tuples will be produced in sorted order. Elements are treated as unique based on their position, not on their value. So if the input elements are unique, there will be no repeat values in each combination. Roughly equivalent to: def combinations(iterable, r):\\n # combinations('ABCD', 2) --> AB AC AD BC BD CD\",\n \"title\": \"python.library.itertools#itertools.combinations\"\n }\n]"}}},{"rowIdx":270,"cells":{"task_id":{"kind":"number","value":4530069,"string":"4,530,069"},"prompt":{"kind":"string","value":"def f_4530069():\n\treturn "},"suffix":{"kind":"string","value":""},"canonical_solution":{"kind":"string","value":"datetime.now(pytz.utc)"},"test_start":{"kind":"string","value":"\nimport pytz\nimport time\nfrom datetime import datetime, timezone\n\ndef check(candidate):"},"test":{"kind":"list like","value":["\n assert (candidate() - datetime(1970, 1, 1).replace(tzinfo=timezone.utc)).total_seconds() - time.time() <= 1\n"],"string":"[\n \"\\n assert (candidate() - datetime(1970, 1, 1).replace(tzinfo=timezone.utc)).total_seconds() - time.time() <= 1\\n\"\n]"},"entry_point":{"kind":"string","value":"f_4530069"},"intent":{"kind":"string","value":"get a value of datetime.today() in the UTC time zone"},"library":{"kind":"list like","value":["datetime","pytz","time"],"string":"[\n \"datetime\",\n \"pytz\",\n \"time\"\n]"},"docs":{"kind":"list like","value":[{"function":"datetime.now","text":"classmethod datetime.now(tz=None) \nReturn the current local date and time. If optional argument tz is None or not specified, this is like today(), but, if possible, supplies more precision than can be gotten from going through a time.time() timestamp (for example, this may be possible on platforms supplying the C gettimeofday() function). If tz is not None, it must be an instance of a tzinfo subclass, and the current date and time are converted to tz’s time zone. This function is preferred over today() and utcnow().","title":"python.library.datetime#datetime.datetime.now"}],"string":"[\n {\n \"function\": \"datetime.now\",\n \"text\": \"classmethod datetime.now(tz=None) \\nReturn the current local date and time. If optional argument tz is None or not specified, this is like today(), but, if possible, supplies more precision than can be gotten from going through a time.time() timestamp (for example, this may be possible on platforms supplying the C gettimeofday() function). If tz is not None, it must be an instance of a tzinfo subclass, and the current date and time are converted to tz’s time zone. This function is preferred over today() and utcnow().\",\n \"title\": \"python.library.datetime#datetime.datetime.now\"\n }\n]"}}},{"rowIdx":271,"cells":{"task_id":{"kind":"number","value":4842956,"string":"4,842,956"},"prompt":{"kind":"string","value":"def f_4842956(list1):\n\t"},"suffix":{"kind":"string","value":"\n\treturn list2"},"canonical_solution":{"kind":"string","value":"list2 = [x for x in list1 if x != []]"},"test_start":{"kind":"string","value":"\ndef check(candidate):"},"test":{"kind":"list like","value":["\n assert candidate([[\"a\"], [], [\"b\"]]) == [[\"a\"], [\"b\"]]\n","\n assert candidate([[], [1,2,3], [], [\"b\"]]) == [[1,2,3], [\"b\"]]\n"],"string":"[\n \"\\n assert candidate([[\\\"a\\\"], [], [\\\"b\\\"]]) == [[\\\"a\\\"], [\\\"b\\\"]]\\n\",\n \"\\n assert candidate([[], [1,2,3], [], [\\\"b\\\"]]) == [[1,2,3], [\\\"b\\\"]]\\n\"\n]"},"entry_point":{"kind":"string","value":"f_4842956"},"intent":{"kind":"string","value":"Get a new list `list2`by removing empty list from a list of lists `list1`"},"library":{"kind":"list like","value":[],"string":"[]"},"docs":{"kind":"list like","value":[],"string":"[]"}}},{"rowIdx":272,"cells":{"task_id":{"kind":"number","value":4842956,"string":"4,842,956"},"prompt":{"kind":"string","value":"def f_4842956(list1):\n\t"},"suffix":{"kind":"string","value":"\n\treturn list2"},"canonical_solution":{"kind":"string","value":"list2 = [x for x in list1 if x]"},"test_start":{"kind":"string","value":"\ndef check(candidate):"},"test":{"kind":"list like","value":["\n assert candidate([[\"a\"], [], [\"b\"]]) == [[\"a\"], [\"b\"]]\n","\n assert candidate([[], [1,2,3], [], [\"b\"]]) == [[1,2,3], [\"b\"]]\n"],"string":"[\n \"\\n assert candidate([[\\\"a\\\"], [], [\\\"b\\\"]]) == [[\\\"a\\\"], [\\\"b\\\"]]\\n\",\n \"\\n assert candidate([[], [1,2,3], [], [\\\"b\\\"]]) == [[1,2,3], [\\\"b\\\"]]\\n\"\n]"},"entry_point":{"kind":"string","value":"f_4842956"},"intent":{"kind":"string","value":"Create `list2` to contain the lists from list `list1` excluding the empty lists from `list1`"},"library":{"kind":"list like","value":[],"string":"[]"},"docs":{"kind":"list like","value":[],"string":"[]"}}},{"rowIdx":273,"cells":{"task_id":{"kind":"number","value":9262278,"string":"9,262,278"},"prompt":{"kind":"string","value":"def f_9262278(data):\n\treturn "},"suffix":{"kind":"string","value":""},"canonical_solution":{"kind":"string","value":"HttpResponse(data, content_type='application/json')"},"test_start":{"kind":"string","value":"\nimport os\nimport json\nfrom django.http import HttpResponse\nfrom django.conf import settings\nif not settings.configured:\n settings.configure(DEBUG=True)\n\ndef check(candidate):"},"test":{"kind":"list like","value":["\n if settings.DEBUG:\n assert candidate(json.dumps({\"Sample-Key\": \"Sample-Value\"})).content == b'{\"Sample-Key\": \"Sample-Value\"}'\n","\n if settings.DEBUG:\n assert candidate(json.dumps({\"Sample-Key\": \"Sample-Value\"}))['content-type'] == 'application/json'\n"],"string":"[\n \"\\n if settings.DEBUG:\\n assert candidate(json.dumps({\\\"Sample-Key\\\": \\\"Sample-Value\\\"})).content == b'{\\\"Sample-Key\\\": \\\"Sample-Value\\\"}'\\n\",\n \"\\n if settings.DEBUG:\\n assert candidate(json.dumps({\\\"Sample-Key\\\": \\\"Sample-Value\\\"}))['content-type'] == 'application/json'\\n\"\n]"},"entry_point":{"kind":"string","value":"f_9262278"},"intent":{"kind":"string","value":"Django response with JSON `data`"},"library":{"kind":"list like","value":["django","json","os"],"string":"[\n \"django\",\n \"json\",\n \"os\"\n]"},"docs":{"kind":"list like","value":[{"function":"HttpResponse","text":"class HttpResponse","title":"django.ref.request-response#django.http.HttpResponse"}],"string":"[\n {\n \"function\": \"HttpResponse\",\n \"text\": \"class HttpResponse\",\n \"title\": \"django.ref.request-response#django.http.HttpResponse\"\n }\n]"}}},{"rowIdx":274,"cells":{"task_id":{"kind":"number","value":17284947,"string":"17,284,947"},"prompt":{"kind":"string","value":"def f_17284947(example_str):\n\treturn "},"suffix":{"kind":"string","value":""},"canonical_solution":{"kind":"string","value":"re.findall('(.*?)\\\\[.*?\\\\]', example_str)"},"test_start":{"kind":"string","value":"\nimport re \n\ndef check(candidate): "},"test":{"kind":"list like","value":["\n list_elems = candidate(\"Josie Smith [3996 COLLEGE AVENUE, SOMETOWN, MD 21003]Mugsy Dog Smith [2560 OAK ST, GLENMEADE, WI 14098]\")\n assert \"\".join(list_elems).strip() == 'Josie Smith Mugsy Dog Smith'\n"],"string":"[\n \"\\n list_elems = candidate(\\\"Josie Smith [3996 COLLEGE AVENUE, SOMETOWN, MD 21003]Mugsy Dog Smith [2560 OAK ST, GLENMEADE, WI 14098]\\\")\\n assert \\\"\\\".join(list_elems).strip() == 'Josie Smith Mugsy Dog Smith'\\n\"\n]"},"entry_point":{"kind":"string","value":"f_17284947"},"intent":{"kind":"string","value":"get all text that is not enclosed within square brackets in string `example_str`"},"library":{"kind":"list like","value":["re"],"string":"[\n \"re\"\n]"},"docs":{"kind":"list like","value":[{"function":"re.findall","text":"re.findall(pattern, string, flags=0) \nReturn all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result. Changed in version 3.7: Non-empty matches can now start just after a previous empty match.","title":"python.library.re#re.findall"}],"string":"[\n {\n \"function\": \"re.findall\",\n \"text\": \"re.findall(pattern, string, flags=0) \\nReturn all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result. Changed in version 3.7: Non-empty matches can now start just after a previous empty match.\",\n \"title\": \"python.library.re#re.findall\"\n }\n]"}}},{"rowIdx":275,"cells":{"task_id":{"kind":"number","value":17284947,"string":"17,284,947"},"prompt":{"kind":"string","value":"def f_17284947(example_str):\n\treturn "},"suffix":{"kind":"string","value":""},"canonical_solution":{"kind":"string","value":"re.findall('(.*?)(?:\\\\[.*?\\\\]|$)', example_str)"},"test_start":{"kind":"string","value":"\nimport re \n\ndef check(candidate): "},"test":{"kind":"list like","value":["\n list_elems = candidate(\"Josie Smith [3996 COLLEGE AVENUE, SOMETOWN, MD 21003]Mugsy Dog Smith [2560 OAK ST, GLENMEADE, WI 14098]\")\n assert \"\".join(list_elems).strip() == 'Josie Smith Mugsy Dog Smith'\n"],"string":"[\n \"\\n list_elems = candidate(\\\"Josie Smith [3996 COLLEGE AVENUE, SOMETOWN, MD 21003]Mugsy Dog Smith [2560 OAK ST, GLENMEADE, WI 14098]\\\")\\n assert \\\"\\\".join(list_elems).strip() == 'Josie Smith Mugsy Dog Smith'\\n\"\n]"},"entry_point":{"kind":"string","value":"f_17284947"},"intent":{"kind":"string","value":"Use a regex to get all text in a string `example_str` that is not surrounded by square brackets"},"library":{"kind":"list like","value":["re"],"string":"[\n \"re\"\n]"},"docs":{"kind":"list like","value":[{"function":"re.findall","text":"re.findall(pattern, string, flags=0) \nReturn all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result. Changed in version 3.7: Non-empty matches can now start just after a previous empty match.","title":"python.library.re#re.findall"}],"string":"[\n {\n \"function\": \"re.findall\",\n \"text\": \"re.findall(pattern, string, flags=0) \\nReturn all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result. Changed in version 3.7: Non-empty matches can now start just after a previous empty match.\",\n \"title\": \"python.library.re#re.findall\"\n }\n]"}}},{"rowIdx":276,"cells":{"task_id":{"kind":"number","value":14182339,"string":"14,182,339"},"prompt":{"kind":"string","value":"def f_14182339():\n\treturn "},"suffix":{"kind":"string","value":""},"canonical_solution":{"kind":"string","value":"re.findall('\\\\(.+?\\\\)|\\\\w', '(zyx)bc')"},"test_start":{"kind":"string","value":"\nimport re \n\ndef check(candidate): "},"test":{"kind":"list like","value":["\n assert candidate() == ['(zyx)', 'b', 'c']\n"],"string":"[\n \"\\n assert candidate() == ['(zyx)', 'b', 'c']\\n\"\n]"},"entry_point":{"kind":"string","value":"f_14182339"},"intent":{"kind":"string","value":"get whatever is between parentheses as a single match, and any char outside as an individual match in string '(zyx)bc'"},"library":{"kind":"list like","value":["re"],"string":"[\n \"re\"\n]"},"docs":{"kind":"list like","value":[{"function":"re.findall","text":"re.findall(pattern, string, flags=0) \nReturn all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result. Changed in version 3.7: Non-empty matches can now start just after a previous empty match.","title":"python.library.re#re.findall"}],"string":"[\n {\n \"function\": \"re.findall\",\n \"text\": \"re.findall(pattern, string, flags=0) \\nReturn all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result. Changed in version 3.7: Non-empty matches can now start just after a previous empty match.\",\n \"title\": \"python.library.re#re.findall\"\n }\n]"}}},{"rowIdx":277,"cells":{"task_id":{"kind":"number","value":14182339,"string":"14,182,339"},"prompt":{"kind":"string","value":"def f_14182339():\n\treturn "},"suffix":{"kind":"string","value":""},"canonical_solution":{"kind":"string","value":"re.findall('\\\\((.*?)\\\\)|(\\\\w)', '(zyx)bc')"},"test_start":{"kind":"string","value":"\nimport re \n\ndef check(candidate): "},"test":{"kind":"list like","value":["\n assert candidate() == [('zyx', ''), ('', 'b'), ('', 'c')]\n"],"string":"[\n \"\\n assert candidate() == [('zyx', ''), ('', 'b'), ('', 'c')]\\n\"\n]"},"entry_point":{"kind":"string","value":"f_14182339"},"intent":{"kind":"string","value":"match regex '\\\\((.*?)\\\\)|(\\\\w)' with string '(zyx)bc'"},"library":{"kind":"list like","value":["re"],"string":"[\n \"re\"\n]"},"docs":{"kind":"list like","value":[{"function":"re.findall","text":"re.findall(pattern, string, flags=0) \nReturn all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result. Changed in version 3.7: Non-empty matches can now start just after a previous empty match.","title":"python.library.re#re.findall"}],"string":"[\n {\n \"function\": \"re.findall\",\n \"text\": \"re.findall(pattern, string, flags=0) \\nReturn all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result. Changed in version 3.7: Non-empty matches can now start just after a previous empty match.\",\n \"title\": \"python.library.re#re.findall\"\n }\n]"}}},{"rowIdx":278,"cells":{"task_id":{"kind":"number","value":14182339,"string":"14,182,339"},"prompt":{"kind":"string","value":"def f_14182339():\n\treturn "},"suffix":{"kind":"string","value":""},"canonical_solution":{"kind":"string","value":"re.findall('\\\\(.*?\\\\)|\\\\w', '(zyx)bc')"},"test_start":{"kind":"string","value":"\nimport re \n\ndef check(candidate): "},"test":{"kind":"list like","value":["\n assert candidate() == ['(zyx)', 'b', 'c']\n"],"string":"[\n \"\\n assert candidate() == ['(zyx)', 'b', 'c']\\n\"\n]"},"entry_point":{"kind":"string","value":"f_14182339"},"intent":{"kind":"string","value":"match multiple regex patterns with the alternation operator `|` in a string `(zyx)bc`"},"library":{"kind":"list like","value":["re"],"string":"[\n \"re\"\n]"},"docs":{"kind":"list like","value":[{"function":"re.findall","text":"re.findall(pattern, string, flags=0) \nReturn all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result. Changed in version 3.7: Non-empty matches can now start just after a previous empty match.","title":"python.library.re#re.findall"}],"string":"[\n {\n \"function\": \"re.findall\",\n \"text\": \"re.findall(pattern, string, flags=0) \\nReturn all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result. Changed in version 3.7: Non-empty matches can now start just after a previous empty match.\",\n \"title\": \"python.library.re#re.findall\"\n }\n]"}}},{"rowIdx":279,"cells":{"task_id":{"kind":"number","value":7126916,"string":"7,126,916"},"prompt":{"kind":"string","value":"def f_7126916(elements):\n\t"},"suffix":{"kind":"string","value":"\n\treturn elements"},"canonical_solution":{"kind":"string","value":"elements = ['%{0}%'.format(element) for element in elements]"},"test_start":{"kind":"string","value":"\ndef check(candidate): "},"test":{"kind":"list like","value":["\n elements = ['abc', 'def', 'ijk', 'mno']\n assert candidate(elements) == ['%abc%', '%def%', '%ijk%', '%mno%']\n","\n elements = [1, 2, 3, 4, 500]\n assert candidate(elements) == ['%1%', '%2%', '%3%', '%4%', '%500%']\n"],"string":"[\n \"\\n elements = ['abc', 'def', 'ijk', 'mno']\\n assert candidate(elements) == ['%abc%', '%def%', '%ijk%', '%mno%']\\n\",\n \"\\n elements = [1, 2, 3, 4, 500]\\n assert candidate(elements) == ['%1%', '%2%', '%3%', '%4%', '%500%']\\n\"\n]"},"entry_point":{"kind":"string","value":"f_7126916"},"intent":{"kind":"string","value":"formate each string cin list `elements` into pattern '%{0}%'"},"library":{"kind":"list like","value":[],"string":"[]"},"docs":{"kind":"list like","value":[],"string":"[]"}}},{"rowIdx":280,"cells":{"task_id":{"kind":"number","value":3595685,"string":"3,595,685"},"prompt":{"kind":"string","value":"def f_3595685():\n\treturn "},"suffix":{"kind":"string","value":""},"canonical_solution":{"kind":"string","value":"subprocess.Popen(['background-process', 'arguments'])"},"test_start":{"kind":"string","value":"\nimport subprocess\nfrom unittest.mock import Mock\n\ndef check(candidate):"},"test":{"kind":"list like","value":["\n subprocess.Popen = Mock(return_value = 0)\n assert candidate() == 0\n"],"string":"[\n \"\\n subprocess.Popen = Mock(return_value = 0)\\n assert candidate() == 0\\n\"\n]"},"entry_point":{"kind":"string","value":"f_3595685"},"intent":{"kind":"string","value":"Open a background process 'background-process' with arguments 'arguments'"},"library":{"kind":"list like","value":["subprocess"],"string":"[\n \"subprocess\"\n]"},"docs":{"kind":"list like","value":[{"function":"subprocess.Popen","text":"class subprocess.Popen(args, bufsize=-1, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, universal_newlines=None, startupinfo=None, creationflags=0, restore_signals=True, start_new_session=False, pass_fds=(), *, group=None, extra_groups=None, user=None, umask=-1, encoding=None, errors=None, text=None) \nExecute a child program in a new process. On POSIX, the class uses os.execvp()-like behavior to execute the child program. On Windows, the class uses the Windows CreateProcess() function. The arguments to Popen are as follows. args should be a sequence of program arguments or else a single string or path-like object. By default, the program to execute is the first item in args if args is a sequence. If args is a string, the interpretation is platform-dependent and described below. See the shell and executable arguments for additional differences from the default behavior. Unless otherwise stated, it is recommended to pass args as a sequence. An example of passing some arguments to an external program as a sequence is: Popen([\"/usr/bin/git\", \"commit\", \"-m\", \"Fixes a bug.\"])\n On POSIX, if args is a string, the string is interpreted as the name or path of the program to execute. However, this can only be done if not passing arguments to the program. Note It may not be obvious how to break a shell command into a sequence of arguments, especially in complex cases. shlex.split() can illustrate how to determine the correct tokenization for args: >>> import shlex, subprocess","title":"python.library.subprocess#subprocess.Popen"}],"string":"[\n {\n \"function\": \"subprocess.Popen\",\n \"text\": \"class subprocess.Popen(args, bufsize=-1, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, universal_newlines=None, startupinfo=None, creationflags=0, restore_signals=True, start_new_session=False, pass_fds=(), *, group=None, extra_groups=None, user=None, umask=-1, encoding=None, errors=None, text=None) \\nExecute a child program in a new process. On POSIX, the class uses os.execvp()-like behavior to execute the child program. On Windows, the class uses the Windows CreateProcess() function. The arguments to Popen are as follows. args should be a sequence of program arguments or else a single string or path-like object. By default, the program to execute is the first item in args if args is a sequence. If args is a string, the interpretation is platform-dependent and described below. See the shell and executable arguments for additional differences from the default behavior. Unless otherwise stated, it is recommended to pass args as a sequence. An example of passing some arguments to an external program as a sequence is: Popen([\\\"/usr/bin/git\\\", \\\"commit\\\", \\\"-m\\\", \\\"Fixes a bug.\\\"])\\n On POSIX, if args is a string, the string is interpreted as the name or path of the program to execute. However, this can only be done if not passing arguments to the program. Note It may not be obvious how to break a shell command into a sequence of arguments, especially in complex cases. shlex.split() can illustrate how to determine the correct tokenization for args: >>> import shlex, subprocess\",\n \"title\": \"python.library.subprocess#subprocess.Popen\"\n }\n]"}}},{"rowIdx":281,"cells":{"task_id":{"kind":"number","value":18453566,"string":"18,453,566"},"prompt":{"kind":"string","value":"def f_18453566(mydict, mykeys):\n\treturn "},"suffix":{"kind":"string","value":""},"canonical_solution":{"kind":"string","value":"[mydict[x] for x in mykeys]"},"test_start":{"kind":"string","value":"\ndef check(candidate):"},"test":{"kind":"list like","value":["\n mydict = {'one': 1, 'two': 2, 'three': 3}\n mykeys = ['three', 'one']\n assert candidate(mydict, mykeys) == [3, 1]\n","\n mydict = {'one': 1.0, 'two': 2.0, 'three': 3.0}\n mykeys = ['one']\n assert candidate(mydict, mykeys) == [1.0]\n"],"string":"[\n \"\\n mydict = {'one': 1, 'two': 2, 'three': 3}\\n mykeys = ['three', 'one']\\n assert candidate(mydict, mykeys) == [3, 1]\\n\",\n \"\\n mydict = {'one': 1.0, 'two': 2.0, 'three': 3.0}\\n mykeys = ['one']\\n assert candidate(mydict, mykeys) == [1.0]\\n\"\n]"},"entry_point":{"kind":"string","value":"f_18453566"},"intent":{"kind":"string","value":"get list of values from dictionary 'mydict' w.r.t. list of keys 'mykeys'"},"library":{"kind":"list like","value":[],"string":"[]"},"docs":{"kind":"list like","value":[],"string":"[]"}}},{"rowIdx":282,"cells":{"task_id":{"kind":"number","value":12692135,"string":"12,692,135"},"prompt":{"kind":"string","value":"def f_12692135():\n\treturn "},"suffix":{"kind":"string","value":""},"canonical_solution":{"kind":"string","value":"dict([('Name', 'Joe'), ('Age', 22)])"},"test_start":{"kind":"string","value":"\ndef check(candidate):"},"test":{"kind":"list like","value":["\n assert candidate() == {'Name': 'Joe', 'Age': 22}\n"],"string":"[\n \"\\n assert candidate() == {'Name': 'Joe', 'Age': 22}\\n\"\n]"},"entry_point":{"kind":"string","value":"f_12692135"},"intent":{"kind":"string","value":"convert list `[('Name', 'Joe'), ('Age', 22)]` into a dictionary"},"library":{"kind":"list like","value":[],"string":"[]"},"docs":{"kind":"list like","value":[],"string":"[]"}}},{"rowIdx":283,"cells":{"task_id":{"kind":"number","value":14401047,"string":"14,401,047"},"prompt":{"kind":"string","value":"def f_14401047(data):\n\treturn "},"suffix":{"kind":"string","value":""},"canonical_solution":{"kind":"string","value":"data.mean(axis=1).reshape(data.shape[0], -1)"},"test_start":{"kind":"string","value":"\nimport numpy as np\n\ndef check(candidate):"},"test":{"kind":"list like","value":["\n data = np.array([[1, 2, 3, 4, 4, 3, 7, 1], [6, 2, 3, 4, 3, 4, 4, 1]])\n expected_res = np.array([[3.125], [3.375]])\n assert np.array_equal(candidate(data), expected_res)\n"],"string":"[\n \"\\n data = np.array([[1, 2, 3, 4, 4, 3, 7, 1], [6, 2, 3, 4, 3, 4, 4, 1]])\\n expected_res = np.array([[3.125], [3.375]])\\n assert np.array_equal(candidate(data), expected_res)\\n\"\n]"},"entry_point":{"kind":"string","value":"f_14401047"},"intent":{"kind":"string","value":"average each two columns of array `data`"},"library":{"kind":"list like","value":["numpy"],"string":"[\n \"numpy\"\n]"},"docs":{"kind":"list like","value":[{"function":"numpy.ndarray.mean","text":"numpy.ndarray.mean method ndarray.mean(axis=None, dtype=None, out=None, keepdims=False, *, where=True)\n \nReturns the average of the array elements along given axis. Refer to numpy.mean for full documentation. See also numpy.mean\n\nequivalent function","title":"numpy.reference.generated.numpy.ndarray.mean"},{"function":"numpy.ndarray.reshape","text":"numpy.ndarray.reshape method ndarray.reshape(shape, order='C')\n \nReturns an array containing the same data with a new shape. Refer to numpy.reshape for full documentation. See also numpy.reshape\n\nequivalent function Notes Unlike the free function numpy.reshape, this method on ndarray allows the elements of the shape parameter to be passed in as separate arguments. For example, a.reshape(10, 11) is equivalent to a.reshape((10, 11)).","title":"numpy.reference.generated.numpy.ndarray.reshape"}],"string":"[\n {\n \"function\": \"numpy.ndarray.mean\",\n \"text\": \"numpy.ndarray.mean method ndarray.mean(axis=None, dtype=None, out=None, keepdims=False, *, where=True)\\n \\nReturns the average of the array elements along given axis. Refer to numpy.mean for full documentation. See also numpy.mean\\n\\nequivalent function\",\n \"title\": \"numpy.reference.generated.numpy.ndarray.mean\"\n },\n {\n \"function\": \"numpy.ndarray.reshape\",\n \"text\": \"numpy.ndarray.reshape method ndarray.reshape(shape, order='C')\\n \\nReturns an array containing the same data with a new shape. Refer to numpy.reshape for full documentation. See also numpy.reshape\\n\\nequivalent function Notes Unlike the free function numpy.reshape, this method on ndarray allows the elements of the shape parameter to be passed in as separate arguments. For example, a.reshape(10, 11) is equivalent to a.reshape((10, 11)).\",\n \"title\": \"numpy.reference.generated.numpy.ndarray.reshape\"\n }\n]"}}},{"rowIdx":284,"cells":{"task_id":{"kind":"number","value":18886596,"string":"18,886,596"},"prompt":{"kind":"string","value":"def f_18886596(s):\n\treturn "},"suffix":{"kind":"string","value":""},"canonical_solution":{"kind":"string","value":"s.replace('\"', '\\\"')"},"test_start":{"kind":"string","value":"\ndef check(candidate):"},"test":{"kind":"list like","value":["\n s = 'This sentence has some \"quotes\" in it'\n assert candidate(s) == 'This sentence has some \\\"quotes\\\" in it'\n"],"string":"[\n \"\\n s = 'This sentence has some \\\"quotes\\\" in it'\\n assert candidate(s) == 'This sentence has some \\\\\\\"quotes\\\\\\\" in it'\\n\"\n]"},"entry_point":{"kind":"string","value":"f_18886596"},"intent":{"kind":"string","value":"double backslash escape all double quotes in string `s`"},"library":{"kind":"list like","value":[],"string":"[]"},"docs":{"kind":"list like","value":[],"string":"[]"}}},{"rowIdx":285,"cells":{"task_id":{"kind":"number","value":5932059,"string":"5,932,059"},"prompt":{"kind":"string","value":"def f_5932059(s):\n\treturn "},"suffix":{"kind":"string","value":""},"canonical_solution":{"kind":"string","value":"re.split('(\\\\W+)', s)"},"test_start":{"kind":"string","value":"\nimport re \n\ndef check(candidate):"},"test":{"kind":"list like","value":["\n s = \"this is a\\nsentence\"\n assert candidate(s) == ['this', ' ', 'is', ' ', 'a', '\\n', 'sentence']\n"],"string":"[\n \"\\n s = \\\"this is a\\\\nsentence\\\"\\n assert candidate(s) == ['this', ' ', 'is', ' ', 'a', '\\\\n', 'sentence']\\n\"\n]"},"entry_point":{"kind":"string","value":"f_5932059"},"intent":{"kind":"string","value":"split a string `s` into a list of words and whitespace"},"library":{"kind":"list like","value":["re"],"string":"[\n \"re\"\n]"},"docs":{"kind":"list like","value":[{"function":"re.split","text":"re.split(pattern, string, maxsplit=0, flags=0) \nSplit string by the occurrences of pattern. If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list. If maxsplit is nonzero, at most maxsplit splits occur, and the remainder of the string is returned as the final element of the list. >>> re.split(r'\\W+', 'Words, words, words.')\n['Words', 'words', 'words', '']","title":"python.library.re#re.split"}],"string":"[\n {\n \"function\": \"re.split\",\n \"text\": \"re.split(pattern, string, maxsplit=0, flags=0) \\nSplit string by the occurrences of pattern. If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list. If maxsplit is nonzero, at most maxsplit splits occur, and the remainder of the string is returned as the final element of the list. >>> re.split(r'\\\\W+', 'Words, words, words.')\\n['Words', 'words', 'words', '']\",\n \"title\": \"python.library.re#re.split\"\n }\n]"}}},{"rowIdx":286,"cells":{"task_id":{"kind":"number","value":9938130,"string":"9,938,130"},"prompt":{"kind":"string","value":"def f_9938130(df):\n\treturn "},"suffix":{"kind":"string","value":""},"canonical_solution":{"kind":"string","value":"df.plot(kind='barh', stacked=True)"},"test_start":{"kind":"string","value":"\nimport pandas as pd\n\ndef check(candidate):"},"test":{"kind":"list like","value":["\n data = [[1, 3], [2, 5], [4, 8]]\n df = pd.DataFrame(data, columns = ['a', 'b'])\n assert str(candidate(df)).split('(')[0] == 'AxesSubplot'\n"],"string":"[\n \"\\n data = [[1, 3], [2, 5], [4, 8]]\\n df = pd.DataFrame(data, columns = ['a', 'b'])\\n assert str(candidate(df)).split('(')[0] == 'AxesSubplot'\\n\"\n]"},"entry_point":{"kind":"string","value":"f_9938130"},"intent":{"kind":"string","value":"plotting stacked barplots on a panda data frame `df`"},"library":{"kind":"list like","value":["pandas"],"string":"[\n \"pandas\"\n]"},"docs":{"kind":"list like","value":[{"function":"df.plot","text":"pandas.DataFrame.plot DataFrame.plot(*args, **kwargs)[source]\n \nMake plots of Series or DataFrame. Uses the backend specified by the option plotting.backend. By default, matplotlib is used. Parameters ","title":"pandas.reference.api.pandas.dataframe.plot"}],"string":"[\n {\n \"function\": \"df.plot\",\n \"text\": \"pandas.DataFrame.plot DataFrame.plot(*args, **kwargs)[source]\\n \\nMake plots of Series or DataFrame. Uses the backend specified by the option plotting.backend. By default, matplotlib is used. Parameters \",\n \"title\": \"pandas.reference.api.pandas.dataframe.plot\"\n }\n]"}}},{"rowIdx":287,"cells":{"task_id":{"kind":"number","value":35945473,"string":"35,945,473"},"prompt":{"kind":"string","value":"def f_35945473(myDictionary):\n\treturn "},"suffix":{"kind":"string","value":""},"canonical_solution":{"kind":"string","value":"{i[1]: i[0] for i in list(myDictionary.items())}"},"test_start":{"kind":"string","value":"\ndef check(candidate):"},"test":{"kind":"list like","value":["\n assert candidate({'a' : 'b', 'c' : 'd'}) == {'b': 'a', 'd': 'c'}\n"],"string":"[\n \"\\n assert candidate({'a' : 'b', 'c' : 'd'}) == {'b': 'a', 'd': 'c'}\\n\"\n]"},"entry_point":{"kind":"string","value":"f_35945473"},"intent":{"kind":"string","value":"reverse the keys and values in a dictionary `myDictionary`"},"library":{"kind":"list like","value":[],"string":"[]"},"docs":{"kind":"list like","value":[],"string":"[]"}}},{"rowIdx":288,"cells":{"task_id":{"kind":"number","value":30729735,"string":"30,729,735"},"prompt":{"kind":"string","value":"def f_30729735(myList):\n\treturn "},"suffix":{"kind":"string","value":""},"canonical_solution":{"kind":"string","value":"[i for i, j in enumerate(myList) if 'how' in j.lower() or 'what' in j.lower()]"},"test_start":{"kind":"string","value":"\ndef check(candidate):"},"test":{"kind":"list like","value":["\n assert candidate(['abc', 'how', 'what', 'def']) == [1, 2]\n"],"string":"[\n \"\\n assert candidate(['abc', 'how', 'what', 'def']) == [1, 2]\\n\"\n]"},"entry_point":{"kind":"string","value":"f_30729735"},"intent":{"kind":"string","value":"finding the index of elements containing substring 'how' and 'what' in a list of strings 'myList'."},"library":{"kind":"list like","value":[],"string":"[]"},"docs":{"kind":"list like","value":[],"string":"[]"}}},{"rowIdx":289,"cells":{"task_id":{"kind":"number","value":1303243,"string":"1,303,243"},"prompt":{"kind":"string","value":"def f_1303243(obj):\n\treturn "},"suffix":{"kind":"string","value":""},"canonical_solution":{"kind":"string","value":"isinstance(obj, str)"},"test_start":{"kind":"string","value":"\ndef check(candidate):"},"test":{"kind":"list like","value":["\n assert candidate('python3') == True\n","\n assert candidate(1.23) == False\n"],"string":"[\n \"\\n assert candidate('python3') == True\\n\",\n \"\\n assert candidate(1.23) == False\\n\"\n]"},"entry_point":{"kind":"string","value":"f_1303243"},"intent":{"kind":"string","value":"check if object `obj` is a string"},"library":{"kind":"list like","value":[],"string":"[]"},"docs":{"kind":"list like","value":[],"string":"[]"}}},{"rowIdx":290,"cells":{"task_id":{"kind":"number","value":1303243,"string":"1,303,243"},"prompt":{"kind":"string","value":"def f_1303243(o):\n\treturn "},"suffix":{"kind":"string","value":""},"canonical_solution":{"kind":"string","value":"isinstance(o, str)"},"test_start":{"kind":"string","value":"\ndef check(candidate):"},"test":{"kind":"list like","value":["\n assert candidate(\"hello\") == True\n","\n assert candidate(123) == False\n","\n assert candidate([]) == False\n","\n assert candidate({\"aa\", \"v\"}) == False\n","\n assert candidate(\"123\") == True\n"],"string":"[\n \"\\n assert candidate(\\\"hello\\\") == True\\n\",\n \"\\n assert candidate(123) == False\\n\",\n \"\\n assert candidate([]) == False\\n\",\n \"\\n assert candidate({\\\"aa\\\", \\\"v\\\"}) == False\\n\",\n \"\\n assert candidate(\\\"123\\\") == True\\n\"\n]"},"entry_point":{"kind":"string","value":"f_1303243"},"intent":{"kind":"string","value":"check if object `o` is a string"},"library":{"kind":"list like","value":[],"string":"[]"},"docs":{"kind":"list like","value":[],"string":"[]"}}},{"rowIdx":291,"cells":{"task_id":{"kind":"number","value":1303243,"string":"1,303,243"},"prompt":{"kind":"string","value":"def f_1303243(o):\n\treturn "},"suffix":{"kind":"string","value":""},"canonical_solution":{"kind":"string","value":"(type(o) is str)"},"test_start":{"kind":"string","value":"\ndef check(candidate):"},"test":{"kind":"list like","value":["\n assert candidate(\"hello\") == True\n","\n assert candidate(123) == False\n","\n assert candidate([]) == False\n","\n assert candidate({\"aa\", \"v\"}) == False\n","\n assert candidate(\"123\") == True\n"],"string":"[\n \"\\n assert candidate(\\\"hello\\\") == True\\n\",\n \"\\n assert candidate(123) == False\\n\",\n \"\\n assert candidate([]) == False\\n\",\n \"\\n assert candidate({\\\"aa\\\", \\\"v\\\"}) == False\\n\",\n \"\\n assert candidate(\\\"123\\\") == True\\n\"\n]"},"entry_point":{"kind":"string","value":"f_1303243"},"intent":{"kind":"string","value":"check if object `o` is a string"},"library":{"kind":"list like","value":[],"string":"[]"},"docs":{"kind":"list like","value":[],"string":"[]"}}},{"rowIdx":292,"cells":{"task_id":{"kind":"number","value":1303243,"string":"1,303,243"},"prompt":{"kind":"string","value":"def f_1303243(obj_to_test):\n\treturn "},"suffix":{"kind":"string","value":""},"canonical_solution":{"kind":"string","value":"isinstance(obj_to_test, str)"},"test_start":{"kind":"string","value":"\ndef check(candidate):"},"test":{"kind":"list like","value":["\n assert candidate(\"hello\") == True\n","\n assert candidate(123) == False\n","\n assert candidate([]) == False\n","\n assert candidate({\"aa\", \"v\"}) == False\n","\n assert candidate(\"123\") == True\n"],"string":"[\n \"\\n assert candidate(\\\"hello\\\") == True\\n\",\n \"\\n assert candidate(123) == False\\n\",\n \"\\n assert candidate([]) == False\\n\",\n \"\\n assert candidate({\\\"aa\\\", \\\"v\\\"}) == False\\n\",\n \"\\n assert candidate(\\\"123\\\") == True\\n\"\n]"},"entry_point":{"kind":"string","value":"f_1303243"},"intent":{"kind":"string","value":"check if `obj_to_test` is a string"},"library":{"kind":"list like","value":[],"string":"[]"},"docs":{"kind":"list like","value":[],"string":"[]"}}},{"rowIdx":293,"cells":{"task_id":{"kind":"number","value":8177079,"string":"8,177,079"},"prompt":{"kind":"string","value":"def f_8177079(list1, list2):\n\t"},"suffix":{"kind":"string","value":"\n\treturn "},"canonical_solution":{"kind":"string","value":"list2.extend(list1)"},"test_start":{"kind":"string","value":"\ndef check(candidate):"},"test":{"kind":"list like","value":["\n a, b = [1, 2, 3], [4, 5, 6]\n candidate(a, b)\n assert b == [4, 5, 6, 1, 2, 3]\n","\n a, c = [1, 2, 3], [7, 8, 9]\n candidate(a, c)\n assert c == [7, 8, 9, 1, 2, 3] \n","\n b = [4, 5, 6, 1, 2, 3]\n c = [7, 8, 9, 1, 2, 3] \n candidate(b, c)\n assert c == [7, 8, 9, 1, 2, 3, 4, 5, 6, 1, 2, 3]\n"],"string":"[\n \"\\n a, b = [1, 2, 3], [4, 5, 6]\\n candidate(a, b)\\n assert b == [4, 5, 6, 1, 2, 3]\\n\",\n \"\\n a, c = [1, 2, 3], [7, 8, 9]\\n candidate(a, c)\\n assert c == [7, 8, 9, 1, 2, 3] \\n\",\n \"\\n b = [4, 5, 6, 1, 2, 3]\\n c = [7, 8, 9, 1, 2, 3] \\n candidate(b, c)\\n assert c == [7, 8, 9, 1, 2, 3, 4, 5, 6, 1, 2, 3]\\n\"\n]"},"entry_point":{"kind":"string","value":"f_8177079"},"intent":{"kind":"string","value":"append list `list1` to `list2`"},"library":{"kind":"list like","value":[],"string":"[]"},"docs":{"kind":"list like","value":[],"string":"[]"}}},{"rowIdx":294,"cells":{"task_id":{"kind":"number","value":8177079,"string":"8,177,079"},"prompt":{"kind":"string","value":"def f_8177079(mylog, list1):\n\t"},"suffix":{"kind":"string","value":"\n\treturn "},"canonical_solution":{"kind":"string","value":"list1.extend(mylog)"},"test_start":{"kind":"string","value":"\ndef check(candidate):"},"test":{"kind":"list like","value":["\n a, b = [1, 2, 3], [4, 5, 6]\n candidate(a, b)\n assert b == [4, 5, 6, 1, 2, 3]\n","\n a, c = [1, 2, 3], [7, 8, 9]\n candidate(a, c)\n assert c == [7, 8, 9, 1, 2, 3] \n","\n b = [4, 5, 6, 1, 2, 3]\n c = [7, 8, 9, 1, 2, 3] \n candidate(b, c)\n assert c == [7, 8, 9, 1, 2, 3, 4, 5, 6, 1, 2, 3]\n"],"string":"[\n \"\\n a, b = [1, 2, 3], [4, 5, 6]\\n candidate(a, b)\\n assert b == [4, 5, 6, 1, 2, 3]\\n\",\n \"\\n a, c = [1, 2, 3], [7, 8, 9]\\n candidate(a, c)\\n assert c == [7, 8, 9, 1, 2, 3] \\n\",\n \"\\n b = [4, 5, 6, 1, 2, 3]\\n c = [7, 8, 9, 1, 2, 3] \\n candidate(b, c)\\n assert c == [7, 8, 9, 1, 2, 3, 4, 5, 6, 1, 2, 3]\\n\"\n]"},"entry_point":{"kind":"string","value":"f_8177079"},"intent":{"kind":"string","value":"append list `mylog` to `list1`"},"library":{"kind":"list like","value":[],"string":"[]"},"docs":{"kind":"list like","value":[],"string":"[]"}}},{"rowIdx":295,"cells":{"task_id":{"kind":"number","value":8177079,"string":"8,177,079"},"prompt":{"kind":"string","value":"def f_8177079(a, c):\n\t"},"suffix":{"kind":"string","value":"\n\treturn "},"canonical_solution":{"kind":"string","value":"c.extend(a)"},"test_start":{"kind":"string","value":"\ndef check(candidate):"},"test":{"kind":"list like","value":["\n a, b = [1, 2, 3], [4, 5, 6]\n candidate(a, b)\n assert b == [4, 5, 6, 1, 2, 3]\n","\n a, c = [1, 2, 3], [7, 8, 9]\n candidate(a, c)\n assert c == [7, 8, 9, 1, 2, 3] \n","\n b = [4, 5, 6, 1, 2, 3]\n c = [7, 8, 9, 1, 2, 3] \n candidate(b, c)\n assert c == [7, 8, 9, 1, 2, 3, 4, 5, 6, 1, 2, 3]\n"],"string":"[\n \"\\n a, b = [1, 2, 3], [4, 5, 6]\\n candidate(a, b)\\n assert b == [4, 5, 6, 1, 2, 3]\\n\",\n \"\\n a, c = [1, 2, 3], [7, 8, 9]\\n candidate(a, c)\\n assert c == [7, 8, 9, 1, 2, 3] \\n\",\n \"\\n b = [4, 5, 6, 1, 2, 3]\\n c = [7, 8, 9, 1, 2, 3] \\n candidate(b, c)\\n assert c == [7, 8, 9, 1, 2, 3, 4, 5, 6, 1, 2, 3]\\n\"\n]"},"entry_point":{"kind":"string","value":"f_8177079"},"intent":{"kind":"string","value":"append list `a` to `c`"},"library":{"kind":"list like","value":[],"string":"[]"},"docs":{"kind":"list like","value":[],"string":"[]"}}},{"rowIdx":296,"cells":{"task_id":{"kind":"number","value":8177079,"string":"8,177,079"},"prompt":{"kind":"string","value":"def f_8177079(mylog, list1):\n\t"},"suffix":{"kind":"string","value":"\n\treturn "},"canonical_solution":{"kind":"string","value":"for line in mylog:\n\t list1.append(line)"},"test_start":{"kind":"string","value":"\ndef check(candidate):"},"test":{"kind":"list like","value":["\n a, b = [1, 2, 3], [4, 5, 6]\n candidate(a, b)\n assert b == [4, 5, 6, 1, 2, 3]\n","\n a, c = [1, 2, 3], [7, 8, 9]\n candidate(a, c)\n assert c == [7, 8, 9, 1, 2, 3] \n","\n b = [4, 5, 6, 1, 2, 3]\n c = [7, 8, 9, 1, 2, 3] \n candidate(b, c)\n assert c == [7, 8, 9, 1, 2, 3, 4, 5, 6, 1, 2, 3]\n"],"string":"[\n \"\\n a, b = [1, 2, 3], [4, 5, 6]\\n candidate(a, b)\\n assert b == [4, 5, 6, 1, 2, 3]\\n\",\n \"\\n a, c = [1, 2, 3], [7, 8, 9]\\n candidate(a, c)\\n assert c == [7, 8, 9, 1, 2, 3] \\n\",\n \"\\n b = [4, 5, 6, 1, 2, 3]\\n c = [7, 8, 9, 1, 2, 3] \\n candidate(b, c)\\n assert c == [7, 8, 9, 1, 2, 3, 4, 5, 6, 1, 2, 3]\\n\"\n]"},"entry_point":{"kind":"string","value":"f_8177079"},"intent":{"kind":"string","value":"append items in list `mylog` to `list1`"},"library":{"kind":"list like","value":[],"string":"[]"},"docs":{"kind":"list like","value":[],"string":"[]"}}},{"rowIdx":297,"cells":{"task_id":{"kind":"number","value":4126227,"string":"4,126,227"},"prompt":{"kind":"string","value":"def f_4126227(a, b):\n\t"},"suffix":{"kind":"string","value":"\n\treturn "},"canonical_solution":{"kind":"string","value":"b.append((a[0][0], a[0][2]))"},"test_start":{"kind":"string","value":"\ndef check(candidate):"},"test":{"kind":"list like","value":["\n a = [(1,2,3),(4,5,6)]\n b = [(0,0)]\n candidate(a, b)\n assert(b == [(0, 0), (1, 3)])\n"],"string":"[\n \"\\n a = [(1,2,3),(4,5,6)]\\n b = [(0,0)]\\n candidate(a, b)\\n assert(b == [(0, 0), (1, 3)])\\n\"\n]"},"entry_point":{"kind":"string","value":"f_4126227"},"intent":{"kind":"string","value":"append a tuple of elements from list `a` with indexes '[0][0] [0][2]' to list `b`"},"library":{"kind":"list like","value":[],"string":"[]"},"docs":{"kind":"list like","value":[],"string":"[]"}}},{"rowIdx":298,"cells":{"task_id":{"kind":"number","value":34902378,"string":"34,902,378"},"prompt":{"kind":"string","value":"def f_34902378(app):\n\t"},"suffix":{"kind":"string","value":"\n\treturn "},"canonical_solution":{"kind":"string","value":"app.config['SECRET_KEY'] = 'Your_secret_string'"},"test_start":{"kind":"string","value":"\nfrom flask import Flask\n\ndef check(candidate):"},"test":{"kind":"list like","value":["\n app = Flask(\"test\")\n candidate(app)\n assert app.config['SECRET_KEY'] == 'Your_secret_string'\n"],"string":"[\n \"\\n app = Flask(\\\"test\\\")\\n candidate(app)\\n assert app.config['SECRET_KEY'] == 'Your_secret_string'\\n\"\n]"},"entry_point":{"kind":"string","value":"f_34902378"},"intent":{"kind":"string","value":"Initialize `SECRET_KEY` in flask config with `Your_secret_string `"},"library":{"kind":"list like","value":["flask"],"string":"[\n \"flask\"\n]"},"docs":{"kind":"list like","value":[{"function":"flask.Flask.config","text":"config \nThe configuration dictionary as Config. This behaves exactly like a regular dictionary but supports additional methods to load a config from files.","title":"flask.api.index#flask.Flask.config"}],"string":"[\n {\n \"function\": \"flask.Flask.config\",\n \"text\": \"config \\nThe configuration dictionary as Config. This behaves exactly like a regular dictionary but supports additional methods to load a config from files.\",\n \"title\": \"flask.api.index#flask.Flask.config\"\n }\n]"}}},{"rowIdx":299,"cells":{"task_id":{"kind":"number","value":22799300,"string":"22,799,300"},"prompt":{"kind":"string","value":"def f_22799300(out):\n\treturn "},"suffix":{"kind":"string","value":""},"canonical_solution":{"kind":"string","value":"pd.DataFrame(out.tolist(), columns=['out-1', 'out-2'], index=out.index)"},"test_start":{"kind":"string","value":"\nimport numpy as np\nimport pandas as pd\nfrom scipy import stats\n\ndef check(candidate):"},"test":{"kind":"list like","value":["\n df = pd.DataFrame(dict(x=np.random.randn(100), y=np.repeat(list(\"abcd\"), 25)))\n out = df.groupby(\"y\").x.apply(stats.ttest_1samp, 0)\n test = pd.DataFrame(out.tolist())\n test.columns = ['out-1', 'out-2']\n test.index = out.index\n res = candidate(out)\n assert(test.equals(res))\n"],"string":"[\n \"\\n df = pd.DataFrame(dict(x=np.random.randn(100), y=np.repeat(list(\\\"abcd\\\"), 25)))\\n out = df.groupby(\\\"y\\\").x.apply(stats.ttest_1samp, 0)\\n test = pd.DataFrame(out.tolist())\\n test.columns = ['out-1', 'out-2']\\n test.index = out.index\\n res = candidate(out)\\n assert(test.equals(res))\\n\"\n]"},"entry_point":{"kind":"string","value":"f_22799300"},"intent":{"kind":"string","value":"unpack a series of tuples in pandas `out` into a DataFrame with column names 'out-1' and 'out-2'"},"library":{"kind":"list like","value":["numpy","pandas","scipy"],"string":"[\n \"numpy\",\n \"pandas\",\n \"scipy\"\n]"},"docs":{"kind":"list like","value":[{"function":"pandas.dataframe","text":"pandas.DataFrame classpandas.DataFrame(data=None, index=None, columns=None, dtype=None, copy=None)[source]\n \nTwo-dimensional, size-mutable, potentially heterogeneous tabular data. Data structure also contains labeled axes (rows and columns). Arithmetic operations align on both row and column labels. Can be thought of as a dict-like container for Series objects. The primary pandas data structure. Parameters ","title":"pandas.reference.api.pandas.dataframe"}],"string":"[\n {\n \"function\": \"pandas.dataframe\",\n \"text\": \"pandas.DataFrame classpandas.DataFrame(data=None, index=None, columns=None, dtype=None, copy=None)[source]\\n \\nTwo-dimensional, size-mutable, potentially heterogeneous tabular data. Data structure also contains labeled axes (rows and columns). Arithmetic operations align on both row and column labels. Can be thought of as a dict-like container for Series objects. The primary pandas data structure. Parameters \",\n \"title\": \"pandas.reference.api.pandas.dataframe\"\n }\n]"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":2,"numItemsPerPage":100,"numTotalItems":439,"offset":200,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1NjIwNDAxMiwic3ViIjoiL2RhdGFzZXRzL2NvZGUtcmFnLWJlbmNoL29kZXgiLCJleHAiOjE3NTYyMDc2MTIsImlzcyI6Imh0dHBzOi8vaHVnZ2luZ2ZhY2UuY28ifQ.edMGTcrrnqsYr8plEQFYM6dnpQ1LB8zSlWA3ydDL_a0xWOXCRL0vRoHOYPYgPn2AvnrRY_qU-9uU32CZsZWUAQ","displayUrls":true},"discussionsStats":{"closed":0,"open":0,"total":0},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}">
task_id
int64
19.3k
41.9M
prompt
stringlengths
17
68
suffix
stringclasses
37 values
canonical_solution
stringlengths
6
153
test_start
stringlengths
22
198
test
listlengths
1
7
entry_point
stringlengths
7
10
intent
stringlengths
19
200
library
listlengths
0
3
docs
listlengths
0
3
638,048
def f_638048(list_of_pairs): return
sum([pair[0] for pair in list_of_pairs])
def check(candidate):
[ "\n assert candidate([(5, 9), (-1, -2), (4, 2)]) == 8\n" ]
f_638048
sum the first value in each tuple in a list of tuples `list_of_pairs` in python
[]
[]
14,950,260
def f_14950260(): return
ast.literal_eval("{'code1':1,'code2':1}")
import ast def check(candidate):
[ "\n d = candidate()\n exp_result = {'code1' : 1, 'code2': 1}\n for key in d:\n if key not in exp_result:\n assert False\n else:\n assert d[key] == exp_result[key]\n" ]
f_14950260
convert unicode string u"{'code1':1,'code2':1}" into dictionary
[ "ast" ]
[ { "function": "ast.literal_eval", "text": "ast.literal_eval(node_or_string) \nSafely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None. This can be used for safely evaluating strings containing Python values from untrusted sources without the need to parse the values oneself. It is not capable of evaluating arbitrarily complex expressions, for example involving operators or indexing. Warning It is possible to crash the Python interpreter with a sufficiently large/complex string due to stack depth limitations in Python’s AST compiler. Changed in version 3.2: Now allows bytes and set literals. Changed in version 3.9: Now supports creating empty sets with 'set()'.", "title": "python.library.ast#ast.literal_eval" } ]
11,416,772
def f_11416772(mystring): return
[word for word in mystring.split() if word.startswith('$')]
def check(candidate):
[ "\n str = \"$abc def $efg $hij klm $\"\n exp_result = ['$abc', '$efg', '$hij', '$']\n assert sorted(candidate(str)) == sorted(exp_result)\n" ]
f_11416772
find all words in a string `mystring` that start with the `$` sign
[]
[]
11,331,982
def f_11331982(text):
return text
text = re.sub('^https?:\\/\\/.*[\\r\\n]*', '', text, flags=re.MULTILINE)
import re def check(candidate):
[ "\n assert candidate(\"https://www.wikipedia.org/ click at\") == \"\"\n" ]
f_11331982
remove any url within string `text`
[ "re" ]
[ { "function": "re.sub", "text": "re.sub(pattern, repl, string, count=0, flags=0) \nReturn the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. If the pattern isn’t found, string is returned unchanged. repl can be a string or a function; if it is a string, any backslash escapes in it are processed. That is, \\n is converted to a single newline character, \\r is converted to a carriage return, and so forth. Unknown escapes of ASCII letters are reserved for future use and treated as errors. Other unknown escapes such as \\& are left alone. Backreferences, such as \\6, are replaced with the substring matched by group 6 in the pattern. For example: >>> re.sub(r'def\\s+([a-zA-Z_][a-zA-Z_0-9]*)\\s*\\(\\s*\\):',\n... r'static PyObject*\\npy_\\1(void)\\n{',\n... 'def myfunc():')\n'static PyObject*\\npy_myfunc(void)\\n{'\n If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string. For example: >>> def dashrepl(matchobj):\n... if matchobj.group(0) == '-': return ' '\n... else: return '-'", "title": "python.library.re#re.sub" } ]
34,945,274
def f_34945274(A): return
np.where(np.in1d(A, [1, 3, 4]).reshape(A.shape), A, 0)
import numpy as np def check(candidate):
[ "\n A = np.array([[6, 8, 1, 3, 4], [-1, 0, 3, 5, 1]])\n B = np.array([[0, 0, 1, 3, 4], [0, 0, 3, 0, 1]])\n assert np.array_equal(candidate(A), B)\n" ]
f_34945274
replace all elements in array `A` that are not present in array `[1, 3, 4]` with zeros
[ "numpy" ]
[ { "function": "numpy.where", "text": "numpy.where numpy.where(condition, [x, y, ]/)\n \nReturn elements chosen from x or y depending on condition. Note When only condition is provided, this function is a shorthand for np.asarray(condition).nonzero(). Using nonzero directly should be preferred, as it behaves correctly for subclasses. The rest of this documentation covers only the case where all three arguments are provided. Parameters ", "title": "numpy.reference.generated.numpy.where" }, { "function": "numpy.in1d", "text": "numpy.in1d numpy.in1d(ar1, ar2, assume_unique=False, invert=False)[source]\n \nTest whether each element of a 1-D array is also present in a second array. Returns a boolean array the same length as ar1 that is True where an element of ar1 is in ar2 and False otherwise. We recommend using isin instead of in1d for new code. Parameters ", "title": "numpy.reference.generated.numpy.in1d" } ]
15,819,980
def f_15819980(a): return
np.mean(a, axis=1)
import numpy as np def check(candidate):
[ "\n A = np.array([[6, 8, 1, 3, 4], [-1, 0, 3, 5, 1]])\n B = np.array([4.4, 1.6])\n assert np.array_equal(candidate(A), B)\n" ]
f_15819980
calculate mean across dimension in a 2d array `a`
[ "numpy" ]
[ { "function": "numpy.mean", "text": "numpy.mean numpy.mean(a, axis=None, dtype=None, out=None, keepdims=<no value>, *, where=<no value>)[source]\n \nCompute the arithmetic mean along the specified axis. Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over the specified axis. float64 intermediate and return values are used for integer inputs. Parameters ", "title": "numpy.reference.generated.numpy.mean" } ]
19,894,365
def f_19894365(): return
subprocess.call(['/usr/bin/Rscript', '--vanilla', '/pathto/MyrScript.r'])
from unittest.mock import Mock import subprocess def check(candidate):
[ "\n subprocess.call = Mock(return_value = 0)\n assert candidate() == 0\n" ]
f_19894365
running r script '/pathto/MyrScript.r' from python
[ "subprocess" ]
[ { "function": "subprocess.call", "text": "subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False, cwd=None, timeout=None, **other_popen_kwargs) \nRun the command described by args. Wait for command to complete, then return the returncode attribute. Code needing to capture stdout or stderr should use run() instead: run(...).returncode\n To suppress stdout or stderr, supply a value of DEVNULL. The arguments shown above are merely some common ones. The full function signature is the same as that of the Popen constructor - this function passes all supplied arguments other than timeout directly through to that interface. Note Do not use stdout=PIPE or stderr=PIPE with this function. The child process will block if it generates enough output to a pipe to fill up the OS pipe buffer as the pipes are not being read from. Changed in version 3.3: timeout was added.", "title": "python.library.subprocess#subprocess.call" } ]
19,894,365
def f_19894365(): return
subprocess.call('/usr/bin/Rscript --vanilla /pathto/MyrScript.r', shell=True)
from unittest.mock import Mock import subprocess def check(candidate):
[ "\n subprocess.call = Mock(return_value = 0)\n assert candidate() == 0\n" ]
f_19894365
run r script '/usr/bin/Rscript --vanilla /pathto/MyrScript.r'
[ "subprocess" ]
[ { "function": "subprocess.call", "text": "subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False, cwd=None, timeout=None, **other_popen_kwargs) \nRun the command described by args. Wait for command to complete, then return the returncode attribute. Code needing to capture stdout or stderr should use run() instead: run(...).returncode\n To suppress stdout or stderr, supply a value of DEVNULL. The arguments shown above are merely some common ones. The full function signature is the same as that of the Popen constructor - this function passes all supplied arguments other than timeout directly through to that interface. Note Do not use stdout=PIPE or stderr=PIPE with this function. The child process will block if it generates enough output to a pipe to fill up the OS pipe buffer as the pipes are not being read from. Changed in version 3.3: timeout was added.", "title": "python.library.subprocess#subprocess.call" } ]
33,058,590
def f_33058590(df): return
df.fillna(df.mean(axis=0))
import pandas as pd import numpy as np def check(candidate):
[ "\n df = pd.DataFrame([[1,2,3],[4,5,6],[7.0,np.nan,9.0]], columns=[\"c1\",\"c2\",\"c3\"]) \n res = pd.DataFrame([[1,2,3],[4,5,6],[7.0,3.5,9.0]], columns=[\"c1\",\"c2\",\"c3\"])\n assert candidate(df).equals(res)\n" ]
f_33058590
replacing nan in the dataframe `df` with row average
[ "numpy", "pandas" ]
[ { "function": "df.fillna", "text": "pandas.DataFrame.fillna DataFrame.fillna(value=None, method=None, axis=None, inplace=False, limit=None, downcast=None)[source]\n \nFill NA/NaN values using the specified method. Parameters ", "title": "pandas.reference.api.pandas.dataframe.fillna" }, { "function": "pandas.dataframe.mean", "text": "pandas.DataFrame.mean DataFrame.mean(axis=NoDefault.no_default, skipna=True, level=None, numeric_only=None, **kwargs)[source]\n \nReturn the mean of the values over the requested axis. Parameters ", "title": "pandas.reference.api.pandas.dataframe.mean" } ]
12,400,256
def f_12400256(): return
time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1347517370))
import time def check(candidate):
[ "\n assert candidate() == \"2012-09-13 06:22:50\"\n" ]
f_12400256
Convert unix timestamp '1347517370' to formatted string '%Y-%m-%d %H:%M:%S'
[ "time" ]
[ { "function": "time.strftime", "text": "time.strftime(format[, t]) \nConvert a tuple or struct_time representing a time as returned by gmtime() or localtime() to a string as specified by the format argument. If t is not provided, the current time as returned by localtime() is used. format must be a string. ValueError is raised if any field in t is outside of the allowed range. 0 is a legal argument for any position in the time tuple; if it is normally illegal the value is forced to a correct one. The following directives can be embedded in the format string. They are shown without the optional field width and precision specification, and are replaced by the indicated characters in the strftime() result: \nDirective Meaning Notes ", "title": "python.library.time#time.strftime" } ]
23,359,886
def f_23359886(a): return
a[np.where((a[:, (0)] == 0) * (a[:, (1)] == 1))]
import numpy as np def check(candidate):
[ "\n a = np.array([[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8], [ 9, 10, 11], [12, 13, 14]])\n res = np.array([[0, 1, 2]])\n assert np.array_equal(candidate(a), res)\n" ]
f_23359886
selecting rows in Numpy ndarray 'a', where the value in the first column is 0 and value in the second column is 1
[ "numpy" ]
[ { "function": "numpy.where", "text": "numpy.where numpy.where(condition, [x, y, ]/)\n \nReturn elements chosen from x or y depending on condition. Note When only condition is provided, this function is a shorthand for np.asarray(condition).nonzero(). Using nonzero directly should be preferred, as it behaves correctly for subclasses. The rest of this documentation covers only the case where all three arguments are provided. Parameters ", "title": "numpy.reference.generated.numpy.where" } ]
4,383,082
def f_4383082(words): return
re.split(' +', words)
import regex as re def check(candidate):
[ "\n s = \"hello world sample text\"\n res = [\"hello\", \"world\", \"sample\", \"text\"]\n assert candidate(s) == res\n" ]
f_4383082
separate words delimited by one or more spaces into a list
[ "regex" ]
[ { "function": "re.split", "text": "re.split(pattern, string, maxsplit=0, flags=0) \nSplit string by the occurrences of pattern. If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list. If maxsplit is nonzero, at most maxsplit splits occur, and the remainder of the string is returned as the final element of the list. >>> re.split(r'\\W+', 'Words, words, words.')\n['Words', 'words', 'words', '']", "title": "python.library.re#re.split" } ]
14,637,696
def f_14637696(words): return
len(max(words, key=len))
def check(candidate):
[ "\n assert candidate([\"hello\", \"world\", \"sample\", \"text\", \"superballer\"]) == 11\n" ]
f_14637696
length of longest element in list `words`
[]
[]
3,933,478
def f_3933478(result): return
result[0]['from_user']
def check(candidate):
[ "\n Contents = [{\"hi\": 7, \"bye\": 4, \"from_user\": 0}, {1: 2, 3: 4, 5: 6}]\n assert candidate(Contents) == 0\n" ]
f_3933478
get the value associated with unicode key 'from_user' of first dictionary in list `result`
[]
[]
39,112,645
def f_39112645(): return
[line.split() for line in open('File.txt')]
def check(candidate):
[ "\n with open('File.txt','w') as fw:\n fw.write(\"hi hello cat dog\")\n assert candidate() == [['hi', 'hello', 'cat', 'dog']]\n" ]
f_39112645
Retrieve each line from a file 'File.txt' as a list
[]
[]
1,031,851
def f_1031851(a): return
dict((v, k) for k, v in a.items())
def check(candidate):
[ "\n a = {\"one\": 1, \"two\": 2}\n assert candidate(a) == {1: \"one\", 2: \"two\"}\n" ]
f_1031851
swap keys with values in a dictionary `a`
[]
[]
8,577,137
def f_8577137(): return
open('path/to/FILE_NAME.ext', 'w')
import os def check(candidate):
[ "\n path1 = os.path.join(\"\", \"path\")\n os.mkdir(path1)\n path2 = os.path.join(\"path\", \"to\")\n os.mkdir(path2)\n candidate()\n assert os.path.exists('path/to/FILE_NAME.ext')\n" ]
f_8577137
Open a file `path/to/FILE_NAME.ext` in write mode
[ "os" ]
[ { "function": "open", "text": "os.open(path, flags, mode=0o777, *, dir_fd=None) \nOpen the file path and set various flags according to flags and possibly its mode according to mode. When computing mode, the current umask value is first masked out. Return the file descriptor for the newly opened file. The new file descriptor is non-inheritable. For a description of the flag and mode values, see the C run-time documentation; flag constants (like O_RDONLY and O_WRONLY) are defined in the os module. In particular, on Windows adding O_BINARY is needed to open files in binary mode. This function can support paths relative to directory descriptors with the dir_fd parameter. Raises an auditing event open with arguments path, mode, flags. Changed in version 3.4: The new file descriptor is now non-inheritable. Note This function is intended for low-level I/O. For normal usage, use the built-in function open(), which returns a file object with read() and write() methods (and many more). To wrap a file descriptor in a file object, use fdopen(). New in version 3.3: The dir_fd argument. Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an exception, the function now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale). Changed in version 3.6: Accepts a path-like object.", "title": "python.library.os#os.open" } ]
17,926,273
def f_17926273(df): return
df.groupby(['col1', 'col2'])['col3'].nunique().reset_index()
import pandas as pd def check(candidate):
[ "\n data = [[1, 1, 1], [1, 1, 1], [1, 1, 2], [1, 2, 3], [1, 2, 3], [1, 2, 3], \n [2, 1, 1], [2, 1, 2], [2, 1, 3], [2, 2, 3], [2, 2, 3], [2, 2, 3]]\n expected = [[1, 1, 2], [1, 2, 1], [2, 1, 3], [2, 2, 1]]\n df = pd.DataFrame(data, columns = ['col1', 'col2', 'col3'])\n expected_df = pd.DataFrame(expected, columns = ['col1', 'col2', 'col3'])\n df1 = candidate(df)\n assert pd.DataFrame.equals(expected_df, df1)\n" ]
f_17926273
count distinct values in a column 'col3' of a pandas dataframe `df` group by objects in 'col1' and 'col2'
[ "pandas" ]
[ { "function": "pandas.dataframe.groupby", "text": "pandas.DataFrame.groupby DataFrame.groupby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=NoDefault.no_default, observed=False, dropna=True)[source]\n \nGroup DataFrame using a mapper or by a Series of columns. A groupby operation involves some combination of splitting the object, applying a function, and combining the results. This can be used to group large amounts of data and compute operations on these groups. Parameters ", "title": "pandas.reference.api.pandas.dataframe.groupby" }, { "function": "nunique", "text": "pandas.core.groupby.DataFrameGroupBy.nunique DataFrameGroupBy.nunique(dropna=True)[source]\n \nReturn DataFrame with counts of unique elements in each position. Parameters \n \ndropna:bool, default True\n\n\nDon’t include NaN in the counts. Returns \n nunique: DataFrame\n Examples ", "title": "pandas.reference.api.pandas.core.groupby.dataframegroupby.nunique" }, { "function": "reset_index", "text": "pandas.DataFrame.reset_index DataFrame.reset_index(level=None, drop=False, inplace=False, col_level=0, col_fill='')[source]\n \nReset the index, or a level of it. Reset the index of the DataFrame, and use the default one instead. If the DataFrame has a MultiIndex, this method can remove one or more levels. Parameters ", "title": "pandas.reference.api.pandas.dataframe.reset_index" } ]
3,735,814
def f_3735814(dict1): return
any(key.startswith('EMP$$') for key in dict1)
def check(candidate):
[ "\n assert candidate({'EMP$$': 1, 'EMP$$112': 4}) == True\n", "\n assert candidate({'EMP$$': 1, 'EM$$112': 4}) == True\n", "\n assert candidate({'EMP$33': 0}) == False\n" ]
f_3735814
Check if any key in the dictionary `dict1` starts with the string `EMP$$`
[]
[]
3,735,814
def f_3735814(dict1): return
[value for key, value in list(dict1.items()) if key.startswith('EMP$$')]
def check(candidate):
[ "\n assert sorted(candidate({'EMP$$': 1, 'EMP$$112': 4})) == [1, 4]\n", "\n assert sorted(candidate({'EMP$$': 1, 'EM$$112': 4})) == [1]\n", "\n assert sorted(candidate({'EMP$33': 0})) == []\n" ]
f_3735814
create list of values from dictionary `dict1` that have a key that starts with 'EMP$$'
[]
[]
26,097,916
def f_26097916(sf):
return df
df = pd.DataFrame({'email': sf.index, 'list': sf.values})
import pandas as pd def check(candidate):
[ "\n dict = {'email1': [1.0, 5.0, 7.0], 'email2': [4.2, 3.6, -0.9]}\n sf = pd.Series(dict)\n k = [['email1', [1.0, 5.0, 7.0]], ['email2', [4.2, 3.6, -0.9]]]\n df1 = pd.DataFrame(k, columns=['email', 'list'])\n df2 = candidate(sf)\n assert pd.DataFrame.equals(df1, df2)\n" ]
f_26097916
convert a pandas series `sf` into a pandas dataframe `df` with columns `email` and `list`
[ "pandas" ]
[]
4,048,964
def f_4048964(list): return
'\t'.join(map(str, list))
def check(candidate):
[ "\n assert candidate(['hello', 'world', '!']) == 'hello\\tworld\\t!'\n", "\n assert candidate([]) == \"\"\n", "\n assert candidate([\"mconala\"]) == \"mconala\"\n", "\n assert candidate([\"MCoNaLa\"]) == \"MCoNaLa\"\n" ]
f_4048964
concatenate elements of list `list` by tabs ` `
[]
[]
3,182,716
def f_3182716(): return
'\xd0\xbf\xd1\x80\xd0\xb8'.encode('raw_unicode_escape')
def check(candidate):
[ "\n assert candidate() == b'\\xd0\\xbf\\xd1\\x80\\xd0\\xb8'\n" ]
f_3182716
print unicode string '\xd0\xbf\xd1\x80\xd0\xb8' with utf-8
[]
[]
3,182,716
def f_3182716(): return
'Sopet\xc3\xb3n'.encode('latin-1').decode('utf-8')
def check(candidate):
[ "\n assert candidate() == \"Sopetón\"\n" ]
f_3182716
Encode a latin character in string `Sopet\xc3\xb3n` properly
[]
[]
35,622,945
def f_35622945(s): return
re.findall('n(?<=[^n]n)n+(?=[^n])(?i)', s)
import re def check(candidate):
[ "\n assert candidate(\"ncnnnne\") == ['nnnn']\n", "\n assert candidate(\"nn\") == []\n", "\n assert candidate(\"ask\") == []\n" ]
f_35622945
regex, find "n"s only in the middle of string `s`
[ "re" ]
[ { "function": "re.findall", "text": "re.findall(pattern, string, flags=0) \nReturn all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result. Changed in version 3.7: Non-empty matches can now start just after a previous empty match.", "title": "python.library.re#re.findall" } ]
5,306,756
def f_5306756(): return
'{0:.0f}%'.format(1.0 / 3 * 100)
def check(candidate):
[ "\n assert(candidate() == \"33%\")\n" ]
f_5306756
display the float `1/3*100` as a percentage
[]
[]
2,878,084
def f_2878084(mylist):
return mylist
mylist.sort(key=lambda x: x['title'])
def check(candidate):
[ "\n input = [\n {'title':'New York Times', 'title_url':'New_York_Times','id':4}, \n {'title':'USA Today','title_url':'USA_Today','id':6}, \n {'title':'Apple News','title_url':'Apple_News','id':2}\n ]\n res = [\n {'title': 'Apple News', 'title_url': 'Apple_News', 'id': 2}, \n {'title': 'New York Times', 'title_url': 'New_York_Times', 'id': 4},\n {'title': 'USA Today', 'title_url': 'USA_Today', 'id': 6}\n ]\n assert candidate(input) == res\n" ]
f_2878084
sort a list of dictionary `mylist` by the key `title`
[]
[]
2,878,084
def f_2878084(l):
return l
l.sort(key=lambda x: x['title'])
def check(candidate):
[ "\n input = [\n {'title':'New York Times', 'title_url':'New_York_Times','id':4}, \n {'title':'USA Today','title_url':'USA_Today','id':6}, \n {'title':'Apple News','title_url':'Apple_News','id':2}\n ]\n res = [\n {'title': 'Apple News', 'title_url': 'Apple_News', 'id': 2}, \n {'title': 'New York Times', 'title_url': 'New_York_Times', 'id': 4},\n {'title': 'USA Today', 'title_url': 'USA_Today', 'id': 6}\n ]\n assert candidate(input) == res\n" ]
f_2878084
sort a list `l` of dicts by dict value 'title'
[]
[]
2,878,084
def f_2878084(l):
return l
l.sort(key=lambda x: (x['title'], x['title_url'], x['id']))
def check(candidate):
[ "\n input = [\n {'title':'New York Times', 'title_url':'New_York_Times','id':4}, \n {'title':'USA Today','title_url':'USA_Today','id':6}, \n {'title':'Apple News','title_url':'Apple_News','id':2}\n ]\n res = [\n {'title': 'Apple News', 'title_url': 'Apple_News', 'id': 2}, \n {'title': 'New York Times', 'title_url': 'New_York_Times', 'id': 4},\n {'title': 'USA Today', 'title_url': 'USA_Today', 'id': 6}\n ]\n assert candidate(input) == res\n" ]
f_2878084
sort a list of dictionaries by the value of keys 'title', 'title_url', 'id' in ascending order.
[]
[]
9,323,159
def f_9323159(l1, l2): return
heapq.nlargest(10, range(len(l1)), key=lambda i: abs(l1[i] - l2[i]))
import heapq def check(candidate):
[ "\n l1 = [99, 86, 90, 70, 86, 95, 56, 98, 80, 81]\n l2 = [21, 11, 21, 1, 26, 40, 4, 50, 34, 37]\n res = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n assert candidate(l1, l2) == res\n" ]
f_9323159
find 10 largest differences between each respective elements of list `l1` and list `l2`
[ "heapq" ]
[ { "function": "heapq.nlargest", "text": "heapq.nlargest(n, iterable, key=None) \nReturn a list with the n largest elements from the dataset defined by iterable. key, if provided, specifies a function of one argument that is used to extract a comparison key from each element in iterable (for example, key=str.lower). Equivalent to: sorted(iterable, key=key,\nreverse=True)[:n].", "title": "python.library.heapq#heapq.nlargest" } ]
29,877,663
def f_29877663(soup): return
soup.find_all('span', {'class': 'starGryB sp'})
import bs4 def check(candidate):
[ "\n html = '''<span class=\"starBig sp\">4.1</span>\n <span class=\"starGryB sp\">2.9</span>\n <span class=\"sp starGryB\">2.9</span>\n <span class=\"sp starBig\">22</span>'''\n soup = bs4.BeautifulSoup(html, features=\"html5lib\")\n res = '''[<span class=\"starGryB sp\">2.9</span>]'''\n assert(str(candidate(soup)) == res)\n" ]
f_29877663
BeautifulSoup find all 'span' elements in HTML string `soup` with class of 'starGryB sp'
[ "bs4" ]
[]
24,189,150
def f_24189150(df, engine):
return
df.to_sql('test', engine)
import pandas as pd from sqlalchemy import create_engine def check(candidate):
[ "\n engine = create_engine('sqlite://', echo=False)\n df = pd.DataFrame({'name' : ['User 1', 'User 2', 'User 3']})\n candidate(df, engine)\n result = pd.read_sql('SELECT name FROM test', engine)\n assert result.equals(df)\n" ]
f_24189150
write records in dataframe `df` to table 'test' in schema 'a_schema' with `engine`
[ "pandas", "sqlalchemy" ]
[ { "function": "df.to_sql", "text": "pandas.DataFrame.to_sql DataFrame.to_sql(name, con, schema=None, if_exists='fail', index=True, index_label=None, chunksize=None, dtype=None, method=None)[source]\n \nWrite records stored in a DataFrame to a SQL database. Databases supported by SQLAlchemy [1] are supported. Tables can be newly created, appended to, or overwritten. Parameters ", "title": "pandas.reference.api.pandas.dataframe.to_sql" } ]
30,766,151
def f_30766151(s): return
re.sub('[^(){}[\]]', '', s)
import re def check(candidate):
[ "\n assert candidate(\"(a(vdwvndw){}]\") == \"((){}]\"\n", "\n assert candidate(\"12345\") == \"\"\n" ]
f_30766151
Extract brackets from string `s`
[ "re" ]
[ { "function": "re.sub", "text": "re.sub(pattern, repl, string, count=0, flags=0) \nReturn the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. If the pattern isn’t found, string is returned unchanged. repl can be a string or a function; if it is a string, any backslash escapes in it are processed. That is, \\n is converted to a single newline character, \\r is converted to a carriage return, and so forth. Unknown escapes of ASCII letters are reserved for future use and treated as errors. Other unknown escapes such as \\& are left alone. Backreferences, such as \\6, are replaced with the substring matched by group 6 in the pattern. For example: >>> re.sub(r'def\\s+([a-zA-Z_][a-zA-Z_0-9]*)\\s*\\(\\s*\\):',\n... r'static PyObject*\\npy_\\1(void)\\n{',\n... 'def myfunc():')\n'static PyObject*\\npy_myfunc(void)\\n{'\n If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string. For example: >>> def dashrepl(matchobj):\n... if matchobj.group(0) == '-': return ' '\n... else: return '-'", "title": "python.library.re#re.sub" } ]
1,143,379
def f_1143379(L): return
list(dict((x[0], x) for x in L).values())
def check(candidate):
[ "\n L = [['14', '65', 76], ['2', '5', 6], ['7', '12', 33], ['14', '22', 46]]\n res = [['14', '22', 46], ['2', '5', 6], ['7', '12', 33]]\n assert(candidate(L) == res)\n", "\n assert candidate([\"a\", \"aa\", \"abc\", \"bac\"]) == [\"abc\", \"bac\"]\n" ]
f_1143379
remove duplicate elements from list 'L'
[]
[]
12,330,522
def f_12330522(file): return
[line.rstrip('\n') for line in file]
def check(candidate):
[ "\n res = ['1', '2', '3']\n f = open(\"myfile.txt\", \"a\")\n f.write(\"1\\n2\\n3\")\n f.close()\n f = open(\"myfile.txt\", \"r\")\n assert candidate(f) == res\n" ]
f_12330522
read a file `file` without newlines
[]
[]
364,621
def f_364621(testlist): return
[i for (i, x) in enumerate(testlist) if (x == 1)]
def check(candidate):
[ "\n testlist = [1,2,3,5,3,1,2,1,6]\n assert candidate(testlist) == [0, 5, 7]\n", "\n testlist = [0, -1]\n assert candidate(testlist) == []\n" ]
f_364621
get the position of item 1 in `testlist`
[]
[]
364,621
def f_364621(testlist): return
[i for (i, x) in enumerate(testlist) if (x == 1)]
def check(candidate):
[ "\n testlist = [1,2,3,5,3,1,2,1,6]\n assert candidate(testlist) == [0, 5, 7]\n", "\n testlist = [0, -1]\n assert candidate(testlist) == []\n" ]
f_364621
get the position of item 1 in `testlist`
[]
[]
364,621
def f_364621(testlist, element): return
testlist.index(element)
def check(candidate):
[ "\n testlist = [1,2,3,5,3,1,2,1,6]\n assert candidate(testlist, 1) == 0\n", "\n testlist = [1,2,3,5,3,1,2,1,6]\n try:\n candidate(testlist, 14)\n except:\n assert True\n" ]
f_364621
get the position of item `element` in list `testlist`
[]
[]
13,145,368
def f_13145368(lis): return
max(lis, key=lambda item: item[1])[0]
def check(candidate):
[ "\n lis = [(101, 153), (255, 827), (361, 961)]\n assert candidate(lis) == 361\n" ]
f_13145368
find the first element of the tuple with the maximum second element in a list of tuples `lis`
[]
[]
13,145,368
def f_13145368(lis): return
max(lis, key=itemgetter(1))[0]
from operator import itemgetter def check(candidate):
[ "\n lis = [(101, 153), (255, 827), (361, 961)]\n assert candidate(lis) == 361\n" ]
f_13145368
get the item at index 0 from the tuple that has maximum value at index 1 in list `lis`
[ "operator" ]
[ { "function": "operator.itemgetter", "text": "operator.itemgetter(item) \noperator.itemgetter(*items) \nReturn a callable object that fetches item from its operand using the operand’s __getitem__() method. If multiple items are specified, returns a tuple of lookup values. For example: After f = itemgetter(2), the call f(r) returns r[2]. After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3]). Equivalent to: def itemgetter(*items):", "title": "python.library.operator#operator.itemgetter" } ]
2,689,189
def f_2689189():
return
time.sleep(1)
import time def check(candidate):
[ "\n t1 = time.time()\n candidate()\n t2 = time.time()\n assert t2 - t1 > 1\n" ]
f_2689189
Make a delay of 1 second
[ "time" ]
[ { "function": "time.sleep", "text": "time.sleep(secs) \nSuspend execution of the calling thread for the given number of seconds. The argument may be a floating point number to indicate a more precise sleep time. The actual suspension time may be less than that requested because any caught signal will terminate the sleep() following execution of that signal’s catching routine. Also, the suspension time may be longer than requested by an arbitrary amount because of the scheduling of other activity in the system. Changed in version 3.5: The function now sleeps at least secs even if the sleep is interrupted by a signal, except if the signal handler raises an exception (see PEP 475 for the rationale).", "title": "python.library.time#time.sleep" } ]
12,485,244
def f_12485244(L): return
""", """.join('(' + ', '.join(i) + ')' for i in L)
def check(candidate):
[ "\n L = [(\"abc\", \"def\"), (\"hij\", \"klm\")]\n assert candidate(L) == '(abc, def), (hij, klm)'\n" ]
f_12485244
convert list of tuples `L` to a string
[]
[]
755,857
def f_755857():
return b
b = models.CharField(max_length=7, default='0000000', editable=False)
from django.db import models def check(candidate):
[ "\n assert candidate().get_default() == '0000000'\n" ]
f_755857
Django set default value of field `b` equal to '0000000'
[ "django" ]
[ { "function": "models.CharField", "text": "class CharField(max_length=None, **options)", "title": "django.ref.models.fields#django.db.models.CharField" } ]
16,193,578
def f_16193578(list5): return
sorted(list5, key = lambda x: (degrees(x), x))
from math import degrees def check(candidate):
[ "\n list5 = [4, 1, 2, 3, 9, 5]\n assert candidate(list5) == [1, 2, 3, 4, 5, 9]\n" ]
f_16193578
Sort lis `list5` in ascending order based on the degrees value of its elements
[ "math" ]
[ { "function": "math.degrees", "text": "math.degrees(x) \nConvert angle x from radians to degrees.", "title": "python.library.math#math.degrees" } ]
16,041,405
def f_16041405(l): return
(n for n in l)
def check(candidate):
[ "\n generator = candidate([1,2,3,5])\n assert str(type(generator)) == \"<class 'generator'>\"\n assert [x for x in generator] == [1, 2, 3, 5]\n" ]
f_16041405
convert a list `l` into a generator object
[]
[]
18,837,607
def f_18837607(oldlist, removelist): return
[v for i, v in enumerate(oldlist) if i not in removelist]
def check(candidate):
[ "\n assert candidate([\"asdf\",\"ghjk\",\"qwer\",\"tyui\"], [1,3]) == ['asdf', 'qwer']\n", "\n assert candidate([1,2,3,4,5], [0,4]) == [2,3,4]\n" ]
f_18837607
remove elements from list `oldlist` that have an index number mentioned in list `removelist`
[]
[]
4,710,067
def f_4710067(): return
open('yourfile.txt', 'w')
def check(candidate):
[ "\n fw = candidate()\n assert fw.name == \"yourfile.txt\"\n assert fw.mode == 'w'\n" ]
f_4710067
Open a file `yourfile.txt` in write mode
[]
[]
7,373,219
def f_7373219(obj, attr): return
getattr(obj, attr)
def check(candidate):
[ "\n class Student:\n student_id = \"\"\n student_name = \"\"\n\n def __init__(self, student_id=101, student_name=\"Adam\"):\n self.student_id = student_id\n self.student_name = student_name\n\n student = Student()\n\n assert(candidate(student, 'student_name') == \"Adam\")\n assert(candidate(student, 'student_id') == 101)\n", "\n class Student:\n student_id = \"\"\n student_name = \"\"\n\n def __init__(self, student_id=101, student_name=\"Adam\"):\n self.student_id = student_id\n self.student_name = student_name\n\n student = Student()\n\n try:\n value = candidate(student, 'student_none')\n except: \n assert True\n" ]
f_7373219
get attribute 'attr' from object `obj`
[]
[]
8,171,751
def f_8171751(): return
reduce(lambda a, b: a + b, (('aa',), ('bb',), ('cc',)))
from functools import reduce def check(candidate):
[ "\n assert candidate() == ('aa', 'bb', 'cc')\n" ]
f_8171751
convert tuple of tuples `(('aa',), ('bb',), ('cc',))` to tuple
[ "functools" ]
[ { "function": "reduce", "text": "functools.reduce(function, iterable[, initializer]) \nApply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). The left argument, x, is the accumulated value and the right argument, y, is the update value from the iterable. If the optional initializer is present, it is placed before the items of the iterable in the calculation, and serves as a default when the iterable is empty. If initializer is not given and iterable contains only one item, the first item is returned. Roughly equivalent to: def reduce(function, iterable, initializer=None):\n it = iter(iterable)", "title": "python.library.functools#functools.reduce" } ]
8,171,751
def f_8171751(): return
list(map(lambda a: a[0], (('aa',), ('bb',), ('cc',))))
def check(candidate):
[ "\n assert candidate() == ['aa', 'bb', 'cc']\n" ]
f_8171751
convert tuple of tuples `(('aa',), ('bb',), ('cc',))` to list in one line
[]
[]
28,986,489
def f_28986489(df):
return df
df['range'].replace(',', '-', inplace=True)
import pandas as pd def check(candidate):
[ "\n df = pd.DataFrame({'range' : [\",\", \"(50,290)\", \",,,\"]})\n res = pd.DataFrame({'range' : [\"-\", \"(50,290)\", \",,,\"]})\n assert candidate(df).equals(res)\n" ]
f_28986489
replace a characters in a column of a dataframe `df`
[ "pandas" ]
[ { "function": "pandas.dataframe.replace", "text": "pandas.DataFrame.replace DataFrame.replace(to_replace=None, value=NoDefault.no_default, inplace=False, limit=None, regex=False, method=NoDefault.no_default)[source]\n \nReplace values given in to_replace with value. Values of the DataFrame are replaced with other values dynamically. This differs from updating with .loc or .iloc, which require you to specify a location to update with some value. Parameters ", "title": "pandas.reference.api.pandas.dataframe.replace" } ]
19,339
def f_19339(): return
zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)])
def check(candidate):
[ "\n assert [a for a in candidate()] == [('a', 'b', 'c', 'd'), (1, 2, 3, 4)]\n" ]
f_19339
unzip the list `[('a', 1), ('b', 2), ('c', 3), ('d', 4)]`
[]
[]
19,339
def f_19339(original): return
([a for (a, b) in original], [b for (a, b) in original])
def check(candidate):
[ "\n original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]\n assert candidate(original) == (['a', 'b', 'c', 'd'], [1, 2, 3, 4])\n", "\n original2 = [([], 1), ([], 2), (5, 3), (6, 4)]\n assert candidate(original2) == ([[], [], 5, 6], [1, 2, 3, 4])\n" ]
f_19339
unzip list `original`
[]
[]
19,339
def f_19339(original): return
((a for (a, b) in original), (b for (a, b) in original))
def check(candidate):
[ "\n original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]\n result = candidate(original)\n assert [a for gen in result for a in gen] == ['a','b','c','d',1,2,3,4]\n", "\n original2 = [([], 1), ([], 2), (5, 3), (6, 4)]\n result2 = candidate(original2)\n assert [a for gen in result2 for a in gen] == [[], [], 5, 6, 1, 2, 3, 4]\n" ]
f_19339
unzip list `original` and return a generator
[]
[]
19,339
def f_19339(): return
zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e',)])
def check(candidate):
[ "\n assert list(candidate()) == [('a', 'b', 'c', 'd', 'e')]\n" ]
f_19339
unzip list `[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', )]`
[]
[]
19,339
def f_19339(): return
list(zip_longest(('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e',)))
from itertools import zip_longest def check(candidate):
[ "\n assert(candidate() == [('a', 'b', 'c', 'd', 'e'), (1, 2, 3, 4, None)])\n" ]
f_19339
unzip list `[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', )]` and fill empty results with None
[ "itertools" ]
[ { "function": "itertools.zip_longest", "text": "itertools.zip_longest(*iterables, fillvalue=None) \nMake an iterator that aggregates elements from each of the iterables. If the iterables are of uneven length, missing values are filled-in with fillvalue. Iteration continues until the longest iterable is exhausted. Roughly equivalent to: def zip_longest(*args, fillvalue=None):\n # zip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-", "title": "python.library.itertools#itertools.zip_longest" } ]
1,960,516
def f_1960516(): return
json.dumps('3.9')
import json def check(candidate):
[ "\n data = candidate()\n assert json.loads(data) == '3.9'\n" ]
f_1960516
encode `Decimal('3.9')` to a JSON string
[ "json" ]
[ { "function": "json.dumps", "text": "json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw) \nSerialize obj to a JSON formatted str using this conversion table. The arguments have the same meaning as in dump(). Note Keys in key/value pairs of JSON are always of the type str. When a dictionary is converted into JSON, all the keys of the dictionary are coerced to strings. As a result of this, if a dictionary is converted into JSON and then back into a dictionary, the dictionary may not equal the original one. That is, loads(dumps(x)) != x if x has non-string keys.", "title": "python.library.json#json.dumps" } ]
1,024,847
def f_1024847(d):
return d
d['mynewkey'] = 'mynewvalue'
def check(candidate):
[ "\n assert candidate({'key': 'value'}) == {'key': 'value', 'mynewkey': 'mynewvalue'}\n" ]
f_1024847
Add key "mynewkey" to dictionary `d` with value "mynewvalue"
[]
[]
1,024,847
def f_1024847(data):
return data
data.update({'a': 1, })
def check(candidate):
[ "\n assert candidate({'key': 'value'}) == {'key': 'value', 'a': 1}\n", "\n assert candidate({'key': 'value', 'a' : 2}) == {'key': 'value', 'a': 1}\n" ]
f_1024847
Add key 'a' to dictionary `data` with value 1
[]
[]
1,024,847
def f_1024847(data):
return data
data.update(dict(a=1))
def check(candidate):
[ "\n assert candidate({'key': 'value'}) == {'key': 'value', 'a': 1}\n", "\n assert candidate({'key': 'value', 'a' : 2}) == {'key': 'value', 'a': 1}\n" ]
f_1024847
Add key 'a' to dictionary `data` with value 1
[]
[]
1,024,847
def f_1024847(data):
return data
data.update(a=1)
def check(candidate):
[ "\n assert candidate({'key': 'value'}) == {'key': 'value', 'a': 1}\n", "\n assert candidate({'key': 'value', 'a' : 2}) == {'key': 'value', 'a': 1}\n" ]
f_1024847
Add key 'a' to dictionary `data` with value 1
[]
[]
35,837,346
def f_35837346(matrix): return
max([max(i) for i in matrix])
def check(candidate):
[ "\n assert candidate([[1,2,3],[4,5,6],[7,8,9]]) == 9\n", "\n assert candidate([[1.3,2.8],[4.2,10],[7.9,8.1,5]]) == 10\n" ]
f_35837346
find maximal value in matrix `matrix`
[]
[]
20,457,038
def f_20457038(answer):
return answer
answer = str(round(answer, 2))
def check(candidate):
[ "\n assert candidate(2.34351) == \"2.34\"\n", "\n assert candidate(99.375) == \"99.38\"\n", "\n assert candidate(4.1) == \"4.1\"\n", "\n assert candidate(3) == \"3\"\n" ]
f_20457038
Round number `answer` to 2 precision after the decimal point
[]
[]
2,890,896
def f_2890896(s):
return ip
ip = re.findall('[0-9]+(?:\\.[0-9]+){3}', s)
import re def check(candidate):
[ "\n assert candidate(\"<html><head><title>Current IP Check</title></head><body>Current IP Address: 165.91.15.131</body></html>\") == [\"165.91.15.131\"]\n", "\n assert candidate(\"<html><head><title>Current IP Check</title></head><body>Current IP Address: 165.91.15.131 and this is not a IP Address: 165.91.15</body></html>\") == [\"165.91.15.131\"]\n", "\n assert candidate(\"<html><head><title>Current IP Check</title></head><body>Current IP Address: 192.168.1.1 & this is another IP address: 192.168.1.2</body></html>\") == [\"192.168.1.1\", \"192.168.1.2\"]\n" ]
f_2890896
extract ip address `ip` from an html string `s`
[ "re" ]
[ { "function": "re.findall", "text": "re.findall(pattern, string, flags=0) \nReturn all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result. Changed in version 3.7: Non-empty matches can now start just after a previous empty match.", "title": "python.library.re#re.findall" } ]
29,836,836
def f_29836836(df): return
df.groupby('A').filter(lambda x: len(x) > 1)
import pandas as pd def check(candidate):
[ "\n assert candidate(pd.DataFrame([[1, 2], [1, 4], [5, 6]], columns=['A', 'B'])).equals(pd.DataFrame([[1, 2], [1, 4]], columns=['A', 'B'])) is True\n", "\n assert candidate(pd.DataFrame([[1, 2], [1, 4], [1, 6]], columns=['A', 'B'])).equals(pd.DataFrame([[1, 2], [1, 4], [1, 6]], columns=['A', 'B'])) is True\n" ]
f_29836836
filter dataframe `df` by values in column `A` that appear more than once
[ "pandas" ]
[ { "function": "pandas.dataframe.groupby", "text": "pandas.DataFrame.groupby DataFrame.groupby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=NoDefault.no_default, observed=False, dropna=True)[source]\n \nGroup DataFrame using a mapper or by a Series of columns. A groupby operation involves some combination of splitting the object, applying a function, and combining the results. This can be used to group large amounts of data and compute operations on these groups. Parameters ", "title": "pandas.reference.api.pandas.dataframe.groupby" }, { "function": "dataframegroupby.filter", "text": "pandas.core.groupby.DataFrameGroupBy.filter DataFrameGroupBy.filter(func, dropna=True, *args, **kwargs)[source]\n \nReturn a copy of a DataFrame excluding filtered elements. Elements from groups are filtered if they do not satisfy the boolean criterion specified by func. Parameters ", "title": "pandas.reference.api.pandas.core.groupby.dataframegroupby.filter" } ]
2,545,397
def f_2545397(myfile): return
[x for x in myfile if x != '']
def check(candidate):
[ "\n with open('./tmp.txt', 'w') as fw: \n for s in [\"hello\", \"world\", \"!!!\"]:\n fw.write(f\"{s}\\n\")\n\n with open('./tmp.txt', 'r') as myfile:\n lines = candidate(myfile)\n assert isinstance(lines, list)\n assert len(lines) == 3\n assert lines[0].strip() == \"hello\"\n" ]
f_2545397
append each line in file `myfile` into a list
[]
[]
2,545,397
def f_2545397():
return lst
lst = list(map(int, open('filename.txt').readlines()))
import pandas as pd def check(candidate):
[ "\n with open('./filename.txt', 'w') as fw: \n for s in [\"1\", \"2\", \"100\"]:\n fw.write(f\"{s}\\n\")\n\n assert candidate() == [1, 2, 100]\n" ]
f_2545397
Get a list of integers `lst` from a file `filename.txt`
[ "pandas" ]
[]
35,420,052
def f_35420052(plt, mappable, ax3):
return plt
plt.colorbar(mappable=mappable, cax=ax3)
import numpy as np import matplotlib.pyplot as plt from obspy.core.trace import Trace from obspy.imaging.spectrogram import spectrogram def check(candidate):
[ "\n spl1 = Trace(data=np.arange(0, 10))\n fig = plt.figure()\n ax1 = fig.add_axes([0.1, 0.75, 0.7, 0.2]) #[left bottom width height]\n ax2 = fig.add_axes([0.1, 0.1, 0.7, 0.60], sharex=ax1)\n ax3 = fig.add_axes([0.83, 0.1, 0.03, 0.6])\n\n #make time vector\n t = np.arange(spl1.stats.npts) / spl1.stats.sampling_rate\n\n #plot waveform (top subfigure) \n ax1.plot(t, spl1.data, 'k')\n\n #plot spectrogram (bottom subfigure)\n spl2 = spl1\n fig = spl2.spectrogram(show=False, axes=ax2, wlen=10)\n mappable = ax2.images[0]\n candidate(plt, mappable, ax3)\n \n im=ax2.images\n assert im[-1].colorbar is not None\n" ]
f_35420052
add color bar with image `mappable` to plot `plt`
[ "matplotlib", "numpy", "obspy" ]
[ { "function": "plt.colorbar", "text": "matplotlib.pyplot.colorbar matplotlib.pyplot.colorbar(mappable=None, cax=None, ax=None, **kw)[source]\n \nAdd a colorbar to a plot. Parameters ", "title": "matplotlib._as_gen.matplotlib.pyplot.colorbar" } ]
29,903,025
def f_29903025(df): return
Counter(' '.join(df['text']).split()).most_common(100)
import pandas as pd from collections import Counter def check(candidate):
[ "\n df = pd.DataFrame({\"text\": [\n 'Python is a high-level, general-purpose programming language.', \n 'Its design philosophy emphasizes code readability with the use of significant indentation. Python is dynamically-typed and garbage-collected.'\n ]})\n assert candidate(df) == [('Python', 2),('is', 2),('a', 1),('high-level,', 1),('general-purpose', 1),\n ('programming', 1),('language.', 1),('Its', 1),('design', 1),('philosophy', 1),('emphasizes', 1),\n ('code', 1),('readability', 1),('with', 1), ('the', 1),('use', 1),('of', 1),('significant', 1),\n ('indentation.', 1),('dynamically-typed', 1),('and', 1),('garbage-collected.', 1)]\n" ]
f_29903025
count most frequent 100 words in column 'text' of dataframe `df`
[ "collections", "pandas" ]
[ { "function": "Counter.most_common", "text": "most_common([n]) \nReturn a list of the n most common elements and their counts from the most common to the least. If n is omitted or None, most_common() returns all elements in the counter. Elements with equal counts are ordered in the order first encountered: >>> Counter('abracadabra').most_common(3)\n[('a', 5), ('b', 2), ('r', 2)]", "title": "python.library.collections#collections.Counter.most_common" } ]
7,378,180
def f_7378180(): return
list(itertools.combinations((1, 2, 3), 2))
import itertools def check(candidate):
[ "\n assert candidate() == [(1, 2), (1, 3), (2, 3)]\n" ]
f_7378180
generate all 2-element subsets of tuple `(1, 2, 3)`
[ "itertools" ]
[ { "function": "itertools.combinations", "text": "itertools.combinations(iterable, r) \nReturn r length subsequences of elements from the input iterable. The combination tuples are emitted in lexicographic ordering according to the order of the input iterable. So, if the input iterable is sorted, the combination tuples will be produced in sorted order. Elements are treated as unique based on their position, not on their value. So if the input elements are unique, there will be no repeat values in each combination. Roughly equivalent to: def combinations(iterable, r):\n # combinations('ABCD', 2) --> AB AC AD BC BD CD", "title": "python.library.itertools#itertools.combinations" } ]
4,530,069
def f_4530069(): return
datetime.now(pytz.utc)
import pytz import time from datetime import datetime, timezone def check(candidate):
[ "\n assert (candidate() - datetime(1970, 1, 1).replace(tzinfo=timezone.utc)).total_seconds() - time.time() <= 1\n" ]
f_4530069
get a value of datetime.today() in the UTC time zone
[ "datetime", "pytz", "time" ]
[ { "function": "datetime.now", "text": "classmethod datetime.now(tz=None) \nReturn the current local date and time. If optional argument tz is None or not specified, this is like today(), but, if possible, supplies more precision than can be gotten from going through a time.time() timestamp (for example, this may be possible on platforms supplying the C gettimeofday() function). If tz is not None, it must be an instance of a tzinfo subclass, and the current date and time are converted to tz’s time zone. This function is preferred over today() and utcnow().", "title": "python.library.datetime#datetime.datetime.now" } ]
4,842,956
def f_4842956(list1):
return list2
list2 = [x for x in list1 if x != []]
def check(candidate):
[ "\n assert candidate([[\"a\"], [], [\"b\"]]) == [[\"a\"], [\"b\"]]\n", "\n assert candidate([[], [1,2,3], [], [\"b\"]]) == [[1,2,3], [\"b\"]]\n" ]
f_4842956
Get a new list `list2`by removing empty list from a list of lists `list1`
[]
[]
4,842,956
def f_4842956(list1):
return list2
list2 = [x for x in list1 if x]
def check(candidate):
[ "\n assert candidate([[\"a\"], [], [\"b\"]]) == [[\"a\"], [\"b\"]]\n", "\n assert candidate([[], [1,2,3], [], [\"b\"]]) == [[1,2,3], [\"b\"]]\n" ]
f_4842956
Create `list2` to contain the lists from list `list1` excluding the empty lists from `list1`
[]
[]
9,262,278
def f_9262278(data): return
HttpResponse(data, content_type='application/json')
import os import json from django.http import HttpResponse from django.conf import settings if not settings.configured: settings.configure(DEBUG=True) def check(candidate):
[ "\n if settings.DEBUG:\n assert candidate(json.dumps({\"Sample-Key\": \"Sample-Value\"})).content == b'{\"Sample-Key\": \"Sample-Value\"}'\n", "\n if settings.DEBUG:\n assert candidate(json.dumps({\"Sample-Key\": \"Sample-Value\"}))['content-type'] == 'application/json'\n" ]
f_9262278
Django response with JSON `data`
[ "django", "json", "os" ]
[ { "function": "HttpResponse", "text": "class HttpResponse", "title": "django.ref.request-response#django.http.HttpResponse" } ]
17,284,947
def f_17284947(example_str): return
re.findall('(.*?)\\[.*?\\]', example_str)
import re def check(candidate):
[ "\n list_elems = candidate(\"Josie Smith [3996 COLLEGE AVENUE, SOMETOWN, MD 21003]Mugsy Dog Smith [2560 OAK ST, GLENMEADE, WI 14098]\")\n assert \"\".join(list_elems).strip() == 'Josie Smith Mugsy Dog Smith'\n" ]
f_17284947
get all text that is not enclosed within square brackets in string `example_str`
[ "re" ]
[ { "function": "re.findall", "text": "re.findall(pattern, string, flags=0) \nReturn all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result. Changed in version 3.7: Non-empty matches can now start just after a previous empty match.", "title": "python.library.re#re.findall" } ]
17,284,947
def f_17284947(example_str): return
re.findall('(.*?)(?:\\[.*?\\]|$)', example_str)
import re def check(candidate):
[ "\n list_elems = candidate(\"Josie Smith [3996 COLLEGE AVENUE, SOMETOWN, MD 21003]Mugsy Dog Smith [2560 OAK ST, GLENMEADE, WI 14098]\")\n assert \"\".join(list_elems).strip() == 'Josie Smith Mugsy Dog Smith'\n" ]
f_17284947
Use a regex to get all text in a string `example_str` that is not surrounded by square brackets
[ "re" ]
[ { "function": "re.findall", "text": "re.findall(pattern, string, flags=0) \nReturn all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result. Changed in version 3.7: Non-empty matches can now start just after a previous empty match.", "title": "python.library.re#re.findall" } ]
14,182,339
def f_14182339(): return
re.findall('\\(.+?\\)|\\w', '(zyx)bc')
import re def check(candidate):
[ "\n assert candidate() == ['(zyx)', 'b', 'c']\n" ]
f_14182339
get whatever is between parentheses as a single match, and any char outside as an individual match in string '(zyx)bc'
[ "re" ]
[ { "function": "re.findall", "text": "re.findall(pattern, string, flags=0) \nReturn all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result. Changed in version 3.7: Non-empty matches can now start just after a previous empty match.", "title": "python.library.re#re.findall" } ]
14,182,339
def f_14182339(): return
re.findall('\\((.*?)\\)|(\\w)', '(zyx)bc')
import re def check(candidate):
[ "\n assert candidate() == [('zyx', ''), ('', 'b'), ('', 'c')]\n" ]
f_14182339
match regex '\\((.*?)\\)|(\\w)' with string '(zyx)bc'
[ "re" ]
[ { "function": "re.findall", "text": "re.findall(pattern, string, flags=0) \nReturn all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result. Changed in version 3.7: Non-empty matches can now start just after a previous empty match.", "title": "python.library.re#re.findall" } ]
14,182,339
def f_14182339(): return
re.findall('\\(.*?\\)|\\w', '(zyx)bc')
import re def check(candidate):
[ "\n assert candidate() == ['(zyx)', 'b', 'c']\n" ]
f_14182339
match multiple regex patterns with the alternation operator `|` in a string `(zyx)bc`
[ "re" ]
[ { "function": "re.findall", "text": "re.findall(pattern, string, flags=0) \nReturn all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result. Changed in version 3.7: Non-empty matches can now start just after a previous empty match.", "title": "python.library.re#re.findall" } ]
7,126,916
def f_7126916(elements):
return elements
elements = ['%{0}%'.format(element) for element in elements]
def check(candidate):
[ "\n elements = ['abc', 'def', 'ijk', 'mno']\n assert candidate(elements) == ['%abc%', '%def%', '%ijk%', '%mno%']\n", "\n elements = [1, 2, 3, 4, 500]\n assert candidate(elements) == ['%1%', '%2%', '%3%', '%4%', '%500%']\n" ]
f_7126916
formate each string cin list `elements` into pattern '%{0}%'
[]
[]
3,595,685
def f_3595685(): return
subprocess.Popen(['background-process', 'arguments'])
import subprocess from unittest.mock import Mock def check(candidate):
[ "\n subprocess.Popen = Mock(return_value = 0)\n assert candidate() == 0\n" ]
f_3595685
Open a background process 'background-process' with arguments 'arguments'
[ "subprocess" ]
[ { "function": "subprocess.Popen", "text": "class subprocess.Popen(args, bufsize=-1, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, universal_newlines=None, startupinfo=None, creationflags=0, restore_signals=True, start_new_session=False, pass_fds=(), *, group=None, extra_groups=None, user=None, umask=-1, encoding=None, errors=None, text=None) \nExecute a child program in a new process. On POSIX, the class uses os.execvp()-like behavior to execute the child program. On Windows, the class uses the Windows CreateProcess() function. The arguments to Popen are as follows. args should be a sequence of program arguments or else a single string or path-like object. By default, the program to execute is the first item in args if args is a sequence. If args is a string, the interpretation is platform-dependent and described below. See the shell and executable arguments for additional differences from the default behavior. Unless otherwise stated, it is recommended to pass args as a sequence. An example of passing some arguments to an external program as a sequence is: Popen([\"/usr/bin/git\", \"commit\", \"-m\", \"Fixes a bug.\"])\n On POSIX, if args is a string, the string is interpreted as the name or path of the program to execute. However, this can only be done if not passing arguments to the program. Note It may not be obvious how to break a shell command into a sequence of arguments, especially in complex cases. shlex.split() can illustrate how to determine the correct tokenization for args: >>> import shlex, subprocess", "title": "python.library.subprocess#subprocess.Popen" } ]
18,453,566
def f_18453566(mydict, mykeys): return
[mydict[x] for x in mykeys]
def check(candidate):
[ "\n mydict = {'one': 1, 'two': 2, 'three': 3}\n mykeys = ['three', 'one']\n assert candidate(mydict, mykeys) == [3, 1]\n", "\n mydict = {'one': 1.0, 'two': 2.0, 'three': 3.0}\n mykeys = ['one']\n assert candidate(mydict, mykeys) == [1.0]\n" ]
f_18453566
get list of values from dictionary 'mydict' w.r.t. list of keys 'mykeys'
[]
[]
12,692,135
def f_12692135(): return
dict([('Name', 'Joe'), ('Age', 22)])
def check(candidate):
[ "\n assert candidate() == {'Name': 'Joe', 'Age': 22}\n" ]
f_12692135
convert list `[('Name', 'Joe'), ('Age', 22)]` into a dictionary
[]
[]
14,401,047
def f_14401047(data): return
data.mean(axis=1).reshape(data.shape[0], -1)
import numpy as np def check(candidate):
[ "\n data = np.array([[1, 2, 3, 4, 4, 3, 7, 1], [6, 2, 3, 4, 3, 4, 4, 1]])\n expected_res = np.array([[3.125], [3.375]])\n assert np.array_equal(candidate(data), expected_res)\n" ]
f_14401047
average each two columns of array `data`
[ "numpy" ]
[ { "function": "numpy.ndarray.mean", "text": "numpy.ndarray.mean method ndarray.mean(axis=None, dtype=None, out=None, keepdims=False, *, where=True)\n \nReturns the average of the array elements along given axis. Refer to numpy.mean for full documentation. See also numpy.mean\n\nequivalent function", "title": "numpy.reference.generated.numpy.ndarray.mean" }, { "function": "numpy.ndarray.reshape", "text": "numpy.ndarray.reshape method ndarray.reshape(shape, order='C')\n \nReturns an array containing the same data with a new shape. Refer to numpy.reshape for full documentation. See also numpy.reshape\n\nequivalent function Notes Unlike the free function numpy.reshape, this method on ndarray allows the elements of the shape parameter to be passed in as separate arguments. For example, a.reshape(10, 11) is equivalent to a.reshape((10, 11)).", "title": "numpy.reference.generated.numpy.ndarray.reshape" } ]
18,886,596
def f_18886596(s): return
s.replace('"', '\"')
def check(candidate):
[ "\n s = 'This sentence has some \"quotes\" in it'\n assert candidate(s) == 'This sentence has some \\\"quotes\\\" in it'\n" ]
f_18886596
double backslash escape all double quotes in string `s`
[]
[]
5,932,059
def f_5932059(s): return
re.split('(\\W+)', s)
import re def check(candidate):
[ "\n s = \"this is a\\nsentence\"\n assert candidate(s) == ['this', ' ', 'is', ' ', 'a', '\\n', 'sentence']\n" ]
f_5932059
split a string `s` into a list of words and whitespace
[ "re" ]
[ { "function": "re.split", "text": "re.split(pattern, string, maxsplit=0, flags=0) \nSplit string by the occurrences of pattern. If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list. If maxsplit is nonzero, at most maxsplit splits occur, and the remainder of the string is returned as the final element of the list. >>> re.split(r'\\W+', 'Words, words, words.')\n['Words', 'words', 'words', '']", "title": "python.library.re#re.split" } ]
9,938,130
def f_9938130(df): return
df.plot(kind='barh', stacked=True)
import pandas as pd def check(candidate):
[ "\n data = [[1, 3], [2, 5], [4, 8]]\n df = pd.DataFrame(data, columns = ['a', 'b'])\n assert str(candidate(df)).split('(')[0] == 'AxesSubplot'\n" ]
f_9938130
plotting stacked barplots on a panda data frame `df`
[ "pandas" ]
[ { "function": "df.plot", "text": "pandas.DataFrame.plot DataFrame.plot(*args, **kwargs)[source]\n \nMake plots of Series or DataFrame. Uses the backend specified by the option plotting.backend. By default, matplotlib is used. Parameters ", "title": "pandas.reference.api.pandas.dataframe.plot" } ]
35,945,473
def f_35945473(myDictionary): return
{i[1]: i[0] for i in list(myDictionary.items())}
def check(candidate):
[ "\n assert candidate({'a' : 'b', 'c' : 'd'}) == {'b': 'a', 'd': 'c'}\n" ]
f_35945473
reverse the keys and values in a dictionary `myDictionary`
[]
[]
30,729,735
def f_30729735(myList): return
[i for i, j in enumerate(myList) if 'how' in j.lower() or 'what' in j.lower()]
def check(candidate):
[ "\n assert candidate(['abc', 'how', 'what', 'def']) == [1, 2]\n" ]
f_30729735
finding the index of elements containing substring 'how' and 'what' in a list of strings 'myList'.
[]
[]
1,303,243
def f_1303243(obj): return
isinstance(obj, str)
def check(candidate):
[ "\n assert candidate('python3') == True\n", "\n assert candidate(1.23) == False\n" ]
f_1303243
check if object `obj` is a string
[]
[]
1,303,243
def f_1303243(o): return
isinstance(o, str)
def check(candidate):
[ "\n assert candidate(\"hello\") == True\n", "\n assert candidate(123) == False\n", "\n assert candidate([]) == False\n", "\n assert candidate({\"aa\", \"v\"}) == False\n", "\n assert candidate(\"123\") == True\n" ]
f_1303243
check if object `o` is a string
[]
[]
1,303,243
def f_1303243(o): return
(type(o) is str)
def check(candidate):
[ "\n assert candidate(\"hello\") == True\n", "\n assert candidate(123) == False\n", "\n assert candidate([]) == False\n", "\n assert candidate({\"aa\", \"v\"}) == False\n", "\n assert candidate(\"123\") == True\n" ]
f_1303243
check if object `o` is a string
[]
[]
1,303,243
def f_1303243(obj_to_test): return
isinstance(obj_to_test, str)
def check(candidate):
[ "\n assert candidate(\"hello\") == True\n", "\n assert candidate(123) == False\n", "\n assert candidate([]) == False\n", "\n assert candidate({\"aa\", \"v\"}) == False\n", "\n assert candidate(\"123\") == True\n" ]
f_1303243
check if `obj_to_test` is a string
[]
[]
8,177,079
def f_8177079(list1, list2):
return
list2.extend(list1)
def check(candidate):
[ "\n a, b = [1, 2, 3], [4, 5, 6]\n candidate(a, b)\n assert b == [4, 5, 6, 1, 2, 3]\n", "\n a, c = [1, 2, 3], [7, 8, 9]\n candidate(a, c)\n assert c == [7, 8, 9, 1, 2, 3] \n", "\n b = [4, 5, 6, 1, 2, 3]\n c = [7, 8, 9, 1, 2, 3] \n candidate(b, c)\n assert c == [7, 8, 9, 1, 2, 3, 4, 5, 6, 1, 2, 3]\n" ]
f_8177079
append list `list1` to `list2`
[]
[]
8,177,079
def f_8177079(mylog, list1):
return
list1.extend(mylog)
def check(candidate):
[ "\n a, b = [1, 2, 3], [4, 5, 6]\n candidate(a, b)\n assert b == [4, 5, 6, 1, 2, 3]\n", "\n a, c = [1, 2, 3], [7, 8, 9]\n candidate(a, c)\n assert c == [7, 8, 9, 1, 2, 3] \n", "\n b = [4, 5, 6, 1, 2, 3]\n c = [7, 8, 9, 1, 2, 3] \n candidate(b, c)\n assert c == [7, 8, 9, 1, 2, 3, 4, 5, 6, 1, 2, 3]\n" ]
f_8177079
append list `mylog` to `list1`
[]
[]
8,177,079
def f_8177079(a, c):
return
c.extend(a)
def check(candidate):
[ "\n a, b = [1, 2, 3], [4, 5, 6]\n candidate(a, b)\n assert b == [4, 5, 6, 1, 2, 3]\n", "\n a, c = [1, 2, 3], [7, 8, 9]\n candidate(a, c)\n assert c == [7, 8, 9, 1, 2, 3] \n", "\n b = [4, 5, 6, 1, 2, 3]\n c = [7, 8, 9, 1, 2, 3] \n candidate(b, c)\n assert c == [7, 8, 9, 1, 2, 3, 4, 5, 6, 1, 2, 3]\n" ]
f_8177079
append list `a` to `c`
[]
[]
8,177,079
def f_8177079(mylog, list1):
return
for line in mylog: list1.append(line)
def check(candidate):
[ "\n a, b = [1, 2, 3], [4, 5, 6]\n candidate(a, b)\n assert b == [4, 5, 6, 1, 2, 3]\n", "\n a, c = [1, 2, 3], [7, 8, 9]\n candidate(a, c)\n assert c == [7, 8, 9, 1, 2, 3] \n", "\n b = [4, 5, 6, 1, 2, 3]\n c = [7, 8, 9, 1, 2, 3] \n candidate(b, c)\n assert c == [7, 8, 9, 1, 2, 3, 4, 5, 6, 1, 2, 3]\n" ]
f_8177079
append items in list `mylog` to `list1`
[]
[]
4,126,227
def f_4126227(a, b):
return
b.append((a[0][0], a[0][2]))
def check(candidate):
[ "\n a = [(1,2,3),(4,5,6)]\n b = [(0,0)]\n candidate(a, b)\n assert(b == [(0, 0), (1, 3)])\n" ]
f_4126227
append a tuple of elements from list `a` with indexes '[0][0] [0][2]' to list `b`
[]
[]
34,902,378
def f_34902378(app):
return
app.config['SECRET_KEY'] = 'Your_secret_string'
from flask import Flask def check(candidate):
[ "\n app = Flask(\"test\")\n candidate(app)\n assert app.config['SECRET_KEY'] == 'Your_secret_string'\n" ]
f_34902378
Initialize `SECRET_KEY` in flask config with `Your_secret_string `
[ "flask" ]
[ { "function": "flask.Flask.config", "text": "config \nThe configuration dictionary as Config. This behaves exactly like a regular dictionary but supports additional methods to load a config from files.", "title": "flask.api.index#flask.Flask.config" } ]
22,799,300
def f_22799300(out): return
pd.DataFrame(out.tolist(), columns=['out-1', 'out-2'], index=out.index)
import numpy as np import pandas as pd from scipy import stats def check(candidate):
[ "\n df = pd.DataFrame(dict(x=np.random.randn(100), y=np.repeat(list(\"abcd\"), 25)))\n out = df.groupby(\"y\").x.apply(stats.ttest_1samp, 0)\n test = pd.DataFrame(out.tolist())\n test.columns = ['out-1', 'out-2']\n test.index = out.index\n res = candidate(out)\n assert(test.equals(res))\n" ]
f_22799300
unpack a series of tuples in pandas `out` into a DataFrame with column names 'out-1' and 'out-2'
[ "numpy", "pandas", "scipy" ]
[ { "function": "pandas.dataframe", "text": "pandas.DataFrame classpandas.DataFrame(data=None, index=None, columns=None, dtype=None, copy=None)[source]\n \nTwo-dimensional, size-mutable, potentially heterogeneous tabular data. Data structure also contains labeled axes (rows and columns). Arithmetic operations align on both row and column labels. Can be thought of as a dict-like container for Series objects. The primary pandas data structure. Parameters ", "title": "pandas.reference.api.pandas.dataframe" } ]