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
sequencelengths
1
7
entry_point
stringlengths
7
10
intent
stringlengths
19
200
library
sequencelengths
0
3
docs
listlengths
0
3
2,011,048
def f_2011048(filepath): return
os.stat(filepath).st_size
import os def check(candidate):
[ "\n with open(\"tmp.txt\", 'w') as fw: fw.write(\"hello world!\")\n assert candidate(\"tmp.txt\") == 12\n", "\n with open(\"tmp.txt\", 'w') as fw: fw.write(\"\")\n assert candidate(\"tmp.txt\") == 0\n", "\n with open(\"tmp.txt\", 'w') as fw: fw.write('\\n')\n assert candidate(\"tmp.txt\") == 1\n", "\n filename = 'o.txt'\n with open (filename, 'w') as f:\n f.write('a')\n assert candidate(filename) == 1\n" ]
f_2011048
Get the characters count in a file `filepath`
[ "os" ]
[ { "function": "os.stat", "text": "os.stat(path, *, dir_fd=None, follow_symlinks=True) \nGet the status of a file or a file descriptor. Perform the equivalent of a stat() system call on the given path. path may be specified as either a string or bytes – directly or indirectly through the PathLike interface – or as an open file descriptor. Return a stat_result object. This function normally follows symlinks; to stat a symlink add the argument follow_symlinks=False, or use lstat(). This function can support specifying a file descriptor and not following symlinks. On Windows, passing follow_symlinks=False will disable following all name-surrogate reparse points, which includes symlinks and directory junctions. Other types of reparse points that do not resemble links or that the operating system is unable to follow will be opened directly. When following a chain of multiple links, this may result in the original link being returned instead of the non-link that prevented full traversal. To obtain stat results for the final path in this case, use the os.path.realpath() function to resolve the path name as far as possible and call lstat() on the result. This does not apply to dangling symlinks or junction points, which will raise the usual exceptions. Example: >>> import os", "title": "python.library.os#os.stat" } ]
2,600,191
def f_2600191(l): return
l.count('a')
def check(candidate):
[ "\n assert candidate(\"123456asf\") == 1\n", "\n assert candidate(\"123456gyjnccfgsf\") == 0\n", "\n assert candidate(\"aA\"*10) == 10\n" ]
f_2600191
count the occurrences of item "a" in list `l`
[]
[]
2,600,191
def f_2600191(l): return
Counter(l)
from collections import Counter def check(candidate):
[ "\n assert dict(candidate(\"123456asf\")) == {'1': 1, '2': 1, '3': 1, '4': 1, '5': 1, '6': 1, 'a': 1, 's': 1, 'f': 1}\n", "\n assert candidate(\"123456gyjnccfgsf\") == {'1': 1,'2': 1,'3': 1,'4': 1,'5': 1,'6': 1,'g': 2,'y': 1,'j': 1,'n': 1,'c': 2,'f': 2,'s': 1}\n", "\n assert candidate(\"aA\"*10) == {'a': 10, 'A': 10}\n", "\n y = candidate([1, 6])\n assert y[1] == 1\n assert y[6] == 1\n" ]
f_2600191
count the occurrences of items in list `l`
[ "collections" ]
[ { "function": "Counter", "text": "class collections.Counter([iterable-or-mapping]) \nA Counter is a dict subclass for counting hashable objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages. Elements are counted from an iterable or initialized from another mapping (or counter): >>> c = Counter() # a new, empty counter", "title": "python.library.collections#collections.Counter" } ]
2,600,191
def f_2600191(l): return
[[x, l.count(x)] for x in set(l)]
from collections import Counter def check(candidate):
[ "\n assert sorted(candidate(\"123456asf\")) == [['1', 1],['2', 1],['3', 1],['4', 1],['5', 1],['6', 1],['a', 1],['f', 1],['s', 1]]\n", "\n assert sorted(candidate(\"aA\"*10)) == [['A', 10], ['a', 10]]\n" ]
f_2600191
count the occurrences of items in list `l`
[ "collections" ]
[ { "function": "l.count", "text": "count(x) \nCount the number of deque elements equal to x. New in version 3.2.", "title": "python.library.collections#collections.deque.count" } ]
2,600,191
def f_2600191(l): return
dict(((x, l.count(x)) for x in set(l)))
from collections import Counter def check(candidate):
[ "\n assert candidate(\"123456asf\") == {'4': 1, 'a': 1, '1': 1, 's': 1, '6': 1, 'f': 1, '3': 1, '5': 1, '2': 1}\n", "\n assert candidate(\"aA\"*10) == {'A': 10, 'a': 10}\n", "\n assert candidate([1, 6]) == {1: 1, 6: 1}\n" ]
f_2600191
count the occurrences of items in list `l`
[ "collections" ]
[]
2,600,191
def f_2600191(l): return
l.count('b')
def check(candidate):
[ "\n assert candidate(\"123456abbbsf\") == 3\n", "\n assert candidate(\"123456gyjnccfgsf\") == 0\n", "\n assert candidate(\"Ab\"*10) == 10\n" ]
f_2600191
count the occurrences of item "b" in list `l`
[]
[]
12,842,997
def f_12842997(srcfile, dstdir):
return
shutil.copy(srcfile, dstdir)
import shutil from unittest.mock import Mock def check(candidate):
[ "\n shutil.copy = Mock()\n try:\n candidate('opera.txt', '/')\n except:\n return False \n" ]
f_12842997
copy file `srcfile` to directory `dstdir`
[ "shutil" ]
[ { "function": "shutil.copy", "text": "shutil.copy(src, dst, *, follow_symlinks=True) \nCopies the file src to the file or directory dst. src and dst should be path-like objects or strings. If dst specifies a directory, the file will be copied into dst using the base filename from src. Returns the path to the newly created file. If follow_symlinks is false, and src is a symbolic link, dst will be created as a symbolic link. If follow_symlinks is true and src is a symbolic link, dst will be a copy of the file src refers to. copy() copies the file data and the file’s permission mode (see os.chmod()). Other metadata, like the file’s creation and modification times, is not preserved. To preserve all file metadata from the original, use copy2() instead. Raises an auditing event shutil.copyfile with arguments src, dst. Raises an auditing event shutil.copymode with arguments src, dst. Changed in version 3.3: Added follow_symlinks argument. Now returns path to the newly created file. Changed in version 3.8: Platform-specific fast-copy syscalls may be used internally in order to copy the file more efficiently. See Platform-dependent efficient copy operations section.", "title": "python.library.shutil#shutil.copy" } ]
1,555,968
def f_1555968(x): return
max(k for k, v in x.items() if v != 0)
def check(candidate):
[ "\n assert candidate({'a': 1, 'b': 2, 'c': 2000}) == 'c'\n", "\n assert candidate({'a': 0., 'b': 0, 'c': 200.02}) == 'c'\n", "\n assert candidate({'key1': -100, 'key2': 0.}) == 'key1'\n", "\n x = {1:\"g\", 2:\"a\", 5:\"er\", -4:\"dr\"}\n assert candidate(x) == 5\n" ]
f_1555968
find the key associated with the largest value in dictionary `x` whilst key is non-zero value
[]
[]
17,021,863
def f_17021863(file):
return
file.seek(0)
def check(candidate):
[ "\n with open ('a.txt', 'w') as f:\n f.write('kangaroo\\nkoala\\noxford\\n')\n f = open('a.txt', 'r')\n f.read()\n candidate(f)\n assert f.readline() == 'kangaroo\\n'\n" ]
f_17021863
Put the curser at beginning of the file
[]
[]
38,152,389
def f_38152389(df):
return df
df['c'] = np.where(df['a'].isnull, df['b'], df['a'])
import numpy as np import pandas as pd def check(candidate):
[ "\n df = pd.DataFrame({'a': [1,2,3], 'b': [0,0,0]})\n assert np.allclose(candidate(df), pd.DataFrame({'a': [1,2,3], 'b': [0,0,0], 'c': [0,0,0]}))\n", "\n df = pd.DataFrame({'a': [0,2,3], 'b': [4,5,6]})\n assert np.allclose(candidate(df), pd.DataFrame({'a': [0,2,3], 'b': [4,5,6], 'c': [4,5,6]}))\n" ]
f_38152389
combine values from column 'b' and column 'a' of dataframe `df` into column 'c' of datafram `df`
[ "numpy", "pandas" ]
[ { "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": "pandas.dataframe.isnull", "text": "pandas.DataFrame.isnull DataFrame.isnull()[source]\n \nDataFrame.isnull is an alias for DataFrame.isna. Detect missing values. Return a boolean same-sized object indicating if the values are NA. NA values, such as None or numpy.NaN, gets mapped to True values. Everything else gets mapped to False values. Characters such as empty strings '' or numpy.inf are not considered NA values (unless you set pandas.options.mode.use_inf_as_na = True). Returns ", "title": "pandas.reference.api.pandas.dataframe.isnull" } ]
4,175,686
def f_4175686(d):
return d
del d['ele']
def check(candidate):
[ "\n assert candidate({\"ale\":1, \"ele\": 2}) == {\"ale\": 1}\n" ]
f_4175686
remove key 'ele' from dictionary `d`
[]
[]
11,574,195
def f_11574195(): return
['it'] + ['was'] + ['annoying']
def check(candidate):
[ "\n assert candidate() == ['it', 'was', 'annoying']\n" ]
f_11574195
merge list `['it']` and list `['was']` and list `['annoying']` into one list
[]
[]
587,647
def f_587647(x): return
str(int(x) + 1).zfill(len(x))
def check(candidate):
[ "\n assert candidate(\"001\") == \"002\"\n", "\n assert candidate(\"100\") == \"101\"\n" ]
f_587647
increment a value with leading zeroes in a number `x`
[]
[]
17,315,881
def f_17315881(df): return
all(df.index[:-1] <= df.index[1:])
import pandas as pd def check(candidate):
[ "\n df1 = pd.DataFrame({'a': [1,2], 'bb': [0,2]})\n assert candidate(df1) == True\n", "\n df2 = pd.DataFrame({'a': [1,2,3,4,5], 'bb': [0,3,5,7,9]})\n shuffled = df2.sample(frac=3, replace=True)\n assert candidate(shuffled) == False\n", "\n df = pd.DataFrame([[1, 2], [5, 4]], columns=['a', 'b'])\n assert candidate(df)\n" ]
f_17315881
check if a pandas dataframe `df`'s index is sorted
[ "pandas" ]
[ { "function": "pandas.dataframe.index", "text": "pandas.DataFrame.index DataFrame.index\n \nThe index (row labels) of the DataFrame.", "title": "pandas.reference.api.pandas.dataframe.index" } ]
16,296,643
def f_16296643(t): return
list(t)
def check(candidate):
[ "\n assert candidate((0, 1, 2)) == [0,1,2]\n", "\n assert candidate(('a', [], 100)) == ['a', [], 100]\n" ]
f_16296643
Convert tuple `t` to list
[]
[]
16,296,643
def f_16296643(t): return
tuple(t)
def check(candidate):
[ "\n assert candidate([0,1,2]) == (0, 1, 2)\n", "\n assert candidate(['a', [], 100]) == ('a', [], 100)\n" ]
f_16296643
Convert list `t` to tuple
[]
[]
16,296,643
def f_16296643(level1):
return level1
level1 = map(list, level1)
def check(candidate):
[ "\n t = ((1, 2), (3, 4))\n t = candidate(t)\n assert list(t) == [[1, 2], [3, 4]]\n" ]
f_16296643
Convert tuple `level1` to list
[]
[]
3,880,399
def f_3880399(dataobject, logFile): return
pprint.pprint(dataobject, logFile)
import pprint def check(candidate):
[ "\n f = open('kkk.txt', 'w')\n candidate('hello', f)\n f.close()\n with open('kkk.txt', 'r') as f:\n assert 'hello' in f.readline()\n" ]
f_3880399
send the output of pprint object `dataobject` to file `logFile`
[ "pprint" ]
[ { "function": "pprint.pprint", "text": "pprint.pprint(object, stream=None, indent=1, width=80, depth=None, *, compact=False, sort_dicts=True) \nPrints the formatted representation of object on stream, followed by a newline. If stream is None, sys.stdout is used. This may be used in the interactive interpreter instead of the print() function for inspecting values (you can even reassign print = pprint.pprint for use within a scope). indent, width, depth, compact and sort_dicts will be passed to the PrettyPrinter constructor as formatting parameters. Changed in version 3.4: Added the compact parameter. Changed in version 3.8: Added the sort_dicts parameter. >>> import pprint", "title": "python.library.pprint#pprint.pprint" } ]
21,800,169
def f_21800169(df): return
df.loc[df['BoolCol']]
import pandas as pd def check(candidate):
[ "\n df = pd.DataFrame([[True, 2, 3], [False, 5, 6]], columns = ['BoolCol', 'a', 'b'])\n y = candidate(df)\n assert y['a'][0] == 2\n assert y['b'][0] == 3\n" ]
f_21800169
get index of rows in column 'BoolCol'
[ "pandas" ]
[ { "function": "pandas.dataframe.loc", "text": "pandas.DataFrame.loc propertyDataFrame.loc\n \nAccess a group of rows and columns by label(s) or a boolean array. .loc[] is primarily label based, but may also be used with a boolean array. Allowed inputs are: A single label, e.g. 5 or 'a', (note that 5 is interpreted as a label of the index, and never as an integer position along the index). A list or array of labels, e.g. ['a', 'b', 'c']. ", "title": "pandas.reference.api.pandas.dataframe.loc" } ]
21,800,169
def f_21800169(df): return
df.iloc[np.flatnonzero(df['BoolCol'])]
import numpy as np import pandas as pd def check(candidate):
[ "\n df = pd.DataFrame([[True, 2, 3], [False, 5, 6]], columns = ['BoolCol', 'a', 'b'])\n y = candidate(df)\n assert y['a'][0] == 2\n assert y['b'][0] == 3\n" ]
f_21800169
Create a list containing the indexes of rows where the value of column 'BoolCol' in dataframe `df` are equal to True
[ "numpy", "pandas" ]
[ { "function": "numpy.flatnonzero", "text": "numpy.flatnonzero numpy.flatnonzero(a)[source]\n \nReturn indices that are non-zero in the flattened version of a. This is equivalent to np.nonzero(np.ravel(a))[0]. Parameters ", "title": "numpy.reference.generated.numpy.flatnonzero" }, { "function": "pandas.dataframe.loc", "text": "pandas.DataFrame.iloc propertyDataFrame.iloc\n \nPurely integer-location based indexing for selection by position. .iloc[] is primarily integer position based (from 0 to length-1 of the axis), but may also be used with a boolean array. Allowed inputs are: An integer, e.g. 5. A list or array of integers, e.g. [4, 3, 0]. A slice object with ints, e.g. 1:7. A boolean array. A callable function with one argument (the calling Series or DataFrame) and that returns valid output for indexing (one of the above). This is useful in method chains, when you don’t have a reference to the calling object, but would like to base your selection on some value. .iloc will raise IndexError if a requested indexer is out-of-bounds, except slice indexers which allow out-of-bounds indexing (this conforms with python/numpy slice semantics). See more at Selection by Position. See also DataFrame.iat\n\nFast integer location scalar accessor. DataFrame.loc\n\nPurely label-location based indexer for selection by label. Series.iloc\n\nPurely integer-location based indexing for selection by position. Examples ", "title": "pandas.reference.api.pandas.dataframe.iloc" } ]
21,800,169
def f_21800169(df): return
df[df['BoolCol'] == True].index.tolist()
import pandas as pd def check(candidate):
[ "\n df = pd.DataFrame([[True, 2, 3], [False, 5, 6]], columns = ['BoolCol', 'a', 'b'])\n y = candidate(df)\n assert y == [0]\n" ]
f_21800169
from dataframe `df` get list of indexes of rows where column 'BoolCol' values match True
[ "pandas" ]
[ { "function": "pandas.dataframe.index", "text": "pandas.DataFrame.index DataFrame.index\n \nThe index (row labels) of the DataFrame.", "title": "pandas.reference.api.pandas.dataframe.index" }, { "function": "pandas.index.tolist()", "text": "pandas.Index.tolist Index.tolist()[source]\n \nReturn a list of the values. These are each a scalar type, which is a Python scalar (for str, int, float) or a pandas scalar (for Timestamp/Timedelta/Interval/Period) Returns \n list\n See also numpy.ndarray.tolist\n\nReturn the array as an a.ndim-levels deep nested list of Python scalars.", "title": "pandas.reference.api.pandas.index.tolist" } ]
21,800,169
def f_21800169(df): return
df[df['BoolCol']].index.tolist()
import pandas as pd def check(candidate):
[ "\n df = pd.DataFrame([[True, 2, 3], [False, 5, 6]], columns = ['BoolCol', 'a', 'b'])\n y = candidate(df)\n assert y == [0]\n" ]
f_21800169
get index of rows in dataframe `df` which column 'BoolCol' matches value True
[ "pandas" ]
[ { "function": "pandas.index.tolist", "text": "pandas.Index.tolist Index.tolist()[source]\n \nReturn a list of the values. These are each a scalar type, which is a Python scalar (for str, int, float) or a pandas scalar (for Timestamp/Timedelta/Interval/Period) Returns \n list\n See also numpy.ndarray.tolist\n\nReturn the array as an a.ndim-levels deep nested list of Python scalars.", "title": "pandas.reference.api.pandas.index.tolist" }, { "function": "pandas.dataframe.index", "text": "pandas.DataFrame.index DataFrame.index\n \nThe index (row labels) of the DataFrame.", "title": "pandas.reference.api.pandas.dataframe.index" } ]
299,446
def f_299446(owd):
return
os.chdir(owd)
import os from unittest.mock import Mock def check(candidate):
[ "\n os.chdir = Mock()\n try:\n candidate('/')\n except:\n assert False\n" ]
f_299446
change working directory to the directory `owd`
[ "os" ]
[ { "function": "os.chdir", "text": "os.chdir(path) \nChange the current working directory to path. This function can support specifying a file descriptor. The descriptor must refer to an opened directory, not an open file. This function can raise OSError and subclasses such as FileNotFoundError, PermissionError, and NotADirectoryError. Raises an auditing event os.chdir with argument path. New in version 3.3: Added support for specifying path as a file descriptor on some platforms. Changed in version 3.6: Accepts a path-like object.", "title": "python.library.os#os.chdir" } ]
14,695,134
def f_14695134(c, testfield):
return
c.execute("INSERT INTO test VALUES (?, 'bar')", (testfield,))
import sqlite3 def check(candidate):
[ "\n conn = sqlite3.connect('dev.db')\n cur = conn.cursor()\n cur.execute(\"CREATE TABLE test (x VARCHAR(10), y VARCHAR(10))\")\n candidate(cur, 'kang')\n cur.execute(\"SELECT * FROM test\")\n rows = cur.fetchall()\n assert len(rows) == 1\n" ]
f_14695134
insert data from a string `testfield` to sqlite db `c`
[ "sqlite3" ]
[ { "function": "c.execute", "text": "execute(sql[, parameters]) \nExecutes an SQL statement. Values may be bound to the statement using placeholders. execute() will only execute a single SQL statement. If you try to execute more than one statement with it, it will raise a Warning. Use executescript() if you want to execute multiple SQL statements with one call.", "title": "python.library.sqlite3#sqlite3.Cursor.execute" } ]
24,242,433
def f_24242433(): return
b'\\x89\\n'.decode('unicode_escape')
import sqlite3 def check(candidate):
[ "\n assert candidate() == '\\x89\\n'\n" ]
f_24242433
decode string "\\x89\\n" into a normal string
[ "sqlite3" ]
[]
24,242,433
def f_24242433(raw_string): return
raw_string.decode('unicode_escape')
def check(candidate):
[ "\n assert candidate(b\"Hello\") == \"Hello\"\n", "\n assert candidate(b\"hello world!\") == \"hello world!\"\n", "\n assert candidate(b\". ?? !!x\") == \". ?? !!x\"\n" ]
f_24242433
convert a raw string `raw_string` into a normal string
[]
[]
24,242,433
def f_24242433(raw_byte_string): return
raw_byte_string.decode('unicode_escape')
def check(candidate):
[ "\n assert candidate(b\"Hello\") == \"Hello\"\n", "\n assert candidate(b\"hello world!\") == \"hello world!\"\n", "\n assert candidate(b\". ?? !!x\") == \". ?? !!x\"\n" ]
f_24242433
convert a raw string `raw_byte_string` into a normal string
[]
[]
22,882,922
def f_22882922(s): return
[m.group(0) for m in re.finditer('(\\d)\\1*', s)]
import re def check(candidate):
[ "\n assert candidate('111234') == ['111', '2', '3', '4']\n" ]
f_22882922
split a string `s` with into all strings of repeated characters
[ "re" ]
[ { "function": "re.finditer", "text": "re.finditer(pattern, string, flags=0) \nReturn an iterator yielding match objects over all non-overlapping matches for the RE pattern in string. The string is scanned left-to-right, and matches are returned in the order found. 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.finditer" } ]
4,143,502
def f_4143502(): return
plt.scatter(np.random.randn(100), np.random.randn(100), facecolors='none')
import numpy as np import matplotlib.pyplot as plt def check(candidate):
[ "\n assert 'matplotlib' in str(type(candidate()))\n" ]
f_4143502
scatter a plot with x, y position of `np.random.randn(100)` and face color equal to none
[ "matplotlib", "numpy" ]
[ { "function": "plt.scatter", "text": "matplotlib.pyplot.scatter matplotlib.pyplot.scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, *, edgecolors=None, plotnonfinite=False, data=None, **kwargs)[source]\n \nA scatter plot of y vs. x with varying marker size and/or color. Parameters ", "title": "matplotlib._as_gen.matplotlib.pyplot.scatter" }, { "function": "numpy.random.randn", "text": "numpy.random.randn random.randn(d0, d1, ..., dn)\n \nReturn a sample (or samples) from the “standard normal” distribution. Note This is a convenience function for users porting code from Matlab, and wraps standard_normal. That function takes a tuple to specify the size of the output, which is consistent with other NumPy functions like numpy.zeros and numpy.ones. Note New code should use the standard_normal method of a default_rng() instance instead; please see the Quick Start. If positive int_like arguments are provided, randn generates an array of shape (d0, d1, ..., dn), filled with random floats sampled from a univariate “normal” (Gaussian) distribution of mean 0 and variance 1. A single float randomly sampled from the distribution is returned if no argument is provided. Parameters ", "title": "numpy.reference.random.generated.numpy.random.randn" } ]
4,143,502
def f_4143502(): return
plt.plot(np.random.randn(100), np.random.randn(100), 'o', mfc='none')
import numpy as np import matplotlib.pyplot as plt def check(candidate):
[ "\n assert 'matplotlib' in str(type(candidate()[0]))\n" ]
f_4143502
do a scatter plot with empty circles
[ "matplotlib", "numpy" ]
[ { "function": "plt.plot", "text": "matplotlib.pyplot.plot matplotlib.pyplot.plot(*args, scalex=True, scaley=True, data=None, **kwargs)[source]\n \nPlot y versus x as lines and/or markers. Call signatures: plot([x], y, [fmt], *, data=None, **kwargs)\nplot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)\n The coordinates of the points or line nodes are given by x, y. The optional parameter fmt is a convenient way for defining basic formatting like color, marker and linestyle. It's a shortcut string notation described in the Notes section below. >>> plot(x, y) # plot x and y using default line style and color", "title": "matplotlib._as_gen.matplotlib.pyplot.plot" }, { "function": "numpy.random.randn", "text": "numpy.random.randn random.randn(d0, d1, ..., dn)\n \nReturn a sample (or samples) from the “standard normal” distribution. Note This is a convenience function for users porting code from Matlab, and wraps standard_normal. That function takes a tuple to specify the size of the output, which is consistent with other NumPy functions like numpy.zeros and numpy.ones. Note New code should use the standard_normal method of a default_rng() instance instead; please see the Quick Start. If positive int_like arguments are provided, randn generates an array of shape (d0, d1, ..., dn), filled with random floats sampled from a univariate “normal” (Gaussian) distribution of mean 0 and variance 1. A single float randomly sampled from the distribution is returned if no argument is provided. Parameters ", "title": "numpy.reference.random.generated.numpy.random.randn" } ]
32,063,985
def f_32063985(soup): return
soup.find('div', id='main-content').decompose()
from bs4 import BeautifulSoup def check(candidate):
[ "\n markup = \"<a>This is not div <div>This is div 1</div><div id='main-content'>This is div 2</div></a>\"\n soup = BeautifulSoup(markup,\"html.parser\")\n candidate(soup)\n assert str(soup) == '<a>This is not div <div>This is div 1</div></a>'\n" ]
f_32063985
remove a div from `soup` with a id `main-content` using beautifulsoup
[ "bs4" ]
[]
27,975,069
def f_27975069(df): return
df[df['ids'].str.contains('ball')]
import pandas as pd def check(candidate):
[ "\n f = pd.DataFrame([[\"ball1\", 1, 2], [\"hall\", 5, 4]], columns = ['ids', 'x', 'y'])\n f1 = candidate(f)\n assert f1['x'][0] == 1\n assert f1['y'][0] == 2\n" ]
f_27975069
filter rows of datafram `df` containing key word `ball` in column `ids`
[ "pandas" ]
[ { "function": "pandas.series.str.contains", "text": "pandas.Series.str.contains Series.str.contains(pat, case=True, flags=0, na=None, regex=True)[source]\n \nTest if pattern or regex is contained within a string of a Series or Index. Return boolean Series or Index based on whether a given pattern or regex is contained within a string of a Series or Index. Parameters ", "title": "pandas.reference.api.pandas.series.str.contains" } ]
20,461,165
def f_20461165(df): return
df.reset_index(level=0, inplace=True)
import pandas as pd def check(candidate):
[ "\n df = pd.DataFrame([[384, 593], [781, 123]], columns = ['gi', 'ptt_loc'])\n candidate(df)\n assert df['index'][0] == 0\n assert df['index'][1] == 1\n" ]
f_20461165
convert index at level 0 into a column in dataframe `df`
[ "pandas" ]
[ { "function": "df.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" } ]
20,461,165
def f_20461165(df):
return
df['index1'] = df.index
import pandas as pd def check(candidate):
[ "\n df = pd.DataFrame([[384, 593], [781, 123]], columns = ['gi', 'ptt_loc'])\n candidate(df)\n assert df['index1'][0] == 0\n assert df['index1'][1] == 1\n" ]
f_20461165
Add indexes in a data frame `df` to a column `index1`
[ "pandas" ]
[ { "function": "pandas.dataframe.index", "text": "pandas.DataFrame.index DataFrame.index\n \nThe index (row labels) of the DataFrame.", "title": "pandas.reference.api.pandas.dataframe.index" } ]
20,461,165
def f_20461165(df): return
df.reset_index(level=['tick', 'obs'])
import pandas as pd def check(candidate):
[ "\n df = pd.DataFrame([['2016-09-13', 'C', 2, 0.0139], ['2016-07-17', 'A', 2, 0.5577]], columns = ['tick', 'tag', 'obs', 'val'])\n df = df.set_index(['tick', 'tag', 'obs'])\n df = candidate(df)\n assert df['tick']['C'] == '2016-09-13'\n" ]
f_20461165
convert pandas index in a dataframe `df` to columns
[ "pandas" ]
[ { "function": "df.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" } ]
4,685,571
def f_4685571(b): return
[x[::-1] for x in b]
def check(candidate):
[ "\n b = [('spam',0), ('eggs',1)]\n b1 = candidate(b)\n assert b1 == [(0, 'spam'), (1, 'eggs')]\n" ]
f_4685571
Get reverse of list items from list 'b' using extended slicing
[]
[]
17,960,441
def f_17960441(a, b): return
np.array([zip(x, y) for x, y in zip(a, b)])
import numpy as np def check(candidate):
[ "\n a = np.array([[9, 8], [7, 6]])\n b = np.array([[7, 1], [5, 2]])\n c = candidate(a, b)\n expected = [(9, 7), (8, 1)]\n ctr = 0\n for i in c[0]:\n assert i == expected[ctr]\n ctr += 1\n" ]
f_17960441
join each element in array `a` with element at the same index in array `b` as a tuple
[ "numpy" ]
[ { "function": "numpy.array", "text": "numpy.array numpy.array(object, dtype=None, *, copy=True, order='K', subok=False, ndmin=0, like=None)\n \nCreate an array. Parameters ", "title": "numpy.reference.generated.numpy.array" } ]
17,960,441
def f_17960441(a, b): return
np.array(list(zip(a.ravel(),b.ravel())), dtype=('i4,i4')).reshape(a.shape)
import numpy as np def check(candidate):
[ "\n a = np.array([[9, 8], [7, 6]])\n b = np.array([[7, 1], [5, 2]])\n c = candidate(a, b)\n e = np.array([[(9, 7), (8, 1)], [(7, 5), (6, 2)]], dtype=[('f0', '<i4'), ('f1', '<i4')])\n assert np.array_equal(c, e)\n" ]
f_17960441
zip two 2-d arrays `a` and `b`
[ "numpy" ]
[ { "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" } ]
438,684
def f_438684(list_of_ints): return
""",""".join([str(i) for i in list_of_ints])
def check(candidate):
[ "\n list_of_ints = [8, 7, 6]\n assert candidate(list_of_ints) == '8,7,6'\n", "\n list_of_ints = [0, 1, 6]\n assert candidate(list_of_ints) == '0,1,6'\n" ]
f_438684
convert list `list_of_ints` into a comma separated string
[]
[]
8,519,922
def f_8519922(url, DATA, HEADERS_DICT, username, password): return
requests.post(url, data=DATA, headers=HEADERS_DICT, auth=(username, password))
import requests from unittest.mock import Mock def check(candidate):
[ "\n url='https://www.google.com'\n HEADERS_DICT = {'Accept':'text/json'}\n requests.post = Mock()\n try:\n candidate(url, \"{'name': 'abc'}\", HEADERS_DICT, 'admin', 'admin123')\n except:\n assert False\n" ]
f_8519922
Send a post request with raw data `DATA` and basic authentication with `username` and `password`
[ "requests" ]
[]
26,443,308
def f_26443308(): return
'abcd}def}'.rfind('}')
def check(candidate):
[ "\n assert candidate() == 8\n" ]
f_26443308
Find last occurrence of character '}' in string "abcd}def}"
[]
[]
22,365,172
def f_22365172(): return
[item for item in [1, 2, 3]]
def check(candidate):
[ "\n assert candidate() == [1,2,3]\n" ]
f_22365172
Iterate ove list `[1, 2, 3]` using list comprehension
[]
[]
12,300,912
def f_12300912(d): return
[(x['x'], x['y']) for x in d]
def check(candidate):
[ "\n data = [{'x': 1, 'y': 10}, {'x': 3, 'y': 15}, {'x': 2, 'y': 1}]\n res = candidate(data)\n assert res == [(1, 10), (3, 15), (2, 1)]\n" ]
f_12300912
extract all the values with keys 'x' and 'y' from a list of dictionaries `d` to list of tuples
[]
[]
678,236
def f_678236(): return
os.path.splitext(os.path.basename('hemanth.txt'))[0]
import os def check(candidate):
[ "\n assert candidate() == \"hemanth\"\n" ]
f_678236
get the filename without the extension from file 'hemanth.txt'
[ "os" ]
[ { "function": "os.splitext", "text": "os.path.splitext(path) \nSplit the pathname path into a pair (root, ext) such that root + ext ==\npath, and ext is empty or begins with a period and contains at most one period. Leading periods on the basename are ignored; splitext('.cshrc') returns ('.cshrc', ''). Changed in version 3.6: Accepts a path-like object.", "title": "python.library.os.path#os.path.splitext" } ]
7,895,449
def f_7895449(): return
sum([['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']], [])
def check(candidate):
[ "\n assert candidate() == ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']\n" ]
f_7895449
create a list containing flattened list `[['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']]`
[]
[]
31,617,845
def f_31617845(df):
return df
df = df[(df['closing_price'] >= 99) & (df['closing_price'] <= 101)]
import pandas as pd def check(candidate):
[ "\n df = pd.DataFrame([67, 68, 69, 70, 99, 100, 101, 102], columns = ['closing_price'])\n assert candidate(df).shape[0] == 3\n" ]
f_31617845
select rows in a dataframe `df` column 'closing_price' between two values 99 and 101
[ "pandas" ]
[]
25,698,710
def f_25698710(df): return
df.replace({'\n': '<br>'}, regex=True)
import pandas as pd def check(candidate):
[ "\n df = pd.DataFrame(['klm\\npqr', 'wxy\\njkl'], columns = ['val'])\n expected = pd.DataFrame(['klm<br>pqr', 'wxy<br>jkl'], columns = ['val'])\n assert pd.DataFrame.equals(candidate(df), expected)\n" ]
f_25698710
replace all occurences of newlines `\n` with `<br>` in dataframe `df`
[ "pandas" ]
[ { "function": "df.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" } ]
25,698,710
def f_25698710(df): return
df.replace({'\n': '<br>'}, regex=True)
import pandas as pd def check(candidate):
[ "\n df = pd.DataFrame(['klm\\npqr', 'wxy\\njkl'], columns = ['val'])\n expected = pd.DataFrame(['klm<br>pqr', 'wxy<br>jkl'], columns = ['val'])\n assert pd.DataFrame.equals(candidate(df), expected)\n" ]
f_25698710
replace all occurrences of a string `\n` by string `<br>` in a pandas data frame `df`
[ "pandas" ]
[ { "function": "df.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" } ]
41,923,858
def f_41923858(word): return
[(x + y) for x, y in zip(word, word[1:])]
def check(candidate):
[ "\n assert candidate('abcdef') == ['ab', 'bc', 'cd', 'de', 'ef']\n", "\n assert candidate([\"hello\", \"world\", \"!\"]) == [\"helloworld\", \"world!\"]\n" ]
f_41923858
create a list containing each two adjacent letters in string `word` as its elements
[]
[]
41,923,858
def f_41923858(word): return
list(map(lambda x, y: x + y, word[:-1], word[1:]))
def check(candidate):
[ "\n assert candidate('abcdef') == ['ab', 'bc', 'cd', 'de', 'ef']\n" ]
f_41923858
Get a list of pairs from a string `word` using lambda function
[]
[]
9,760,588
def f_9760588(myString): return
re.findall('(https?://[^\\s]+)', myString)
import re def check(candidate):
[ "\n assert candidate(\"This is a link http://www.google.com\") == [\"http://www.google.com\"]\n", "\n assert candidate(\"Please refer to the website: http://www.google.com\") == [\"http://www.google.com\"]\n" ]
f_9760588
extract a url from a string `myString`
[ "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" } ]
9,760,588
def f_9760588(myString): return
re.search('(?P<url>https?://[^\\s]+)', myString).group('url')
import re def check(candidate):
[ "\n assert candidate(\"This is a link http://www.google.com\") == \"http://www.google.com\"\n", "\n assert candidate(\"Please refer to the website: http://www.google.com\") == \"http://www.google.com\"\n" ]
f_9760588
extract a url from a string `myString`
[ "re" ]
[ { "function": "re.search", "text": "re.search(pattern, string, flags=0) \nScan through string looking for the first location where the regular expression pattern produces a match, and return a corresponding match object. Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string.", "title": "python.library.re#re.search" }, { "function": "re.Match.group", "text": "Match.group([group1, ...]) \nReturns one or more subgroups of the match. If there is a single argument, the result is a single string; if there are multiple arguments, the result is a tuple with one item per argument. Without arguments, group1 defaults to zero (the whole match is returned). If a groupN argument is zero, the corresponding return value is the entire matching string; if it is in the inclusive range [1..99], it is the string matching the corresponding parenthesized group. If a group number is negative or larger than the number of groups defined in the pattern, an IndexError exception is raised. If a group is contained in a part of the pattern that did not match, the corresponding result is None. If a group is contained in a part of the pattern that matched multiple times, the last match is returned. >>> m = re.match(r\"(\\w+) (\\w+)\", \"Isaac Newton, physicist\")", "title": "python.library.re#re.Match.group" } ]
5,843,518
def f_5843518(mystring): return
re.sub('[^A-Za-z0-9]+', '', mystring)
import re def check(candidate):
[ "\n assert candidate('Special $#! characters spaces 888323') == 'Specialcharactersspaces888323'\n" ]
f_5843518
remove all special characters, punctuation and spaces from a string `mystring` using regex
[ "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" } ]
36,674,519
def f_36674519(): return
pd.date_range('2016-01-01', freq='WOM-2FRI', periods=13)
import pandas as pd import datetime def check(candidate):
[ "\n actual = candidate() \n expected = [[2016, 1, 8], [2016, 2, 12],\n [2016, 3, 11], [2016, 4, 8],\n [2016, 5, 13], [2016, 6, 10],\n [2016, 7, 8], [2016, 8, 12],\n [2016, 9, 9], [2016, 10, 14],\n [2016, 11, 11], [2016, 12, 9],\n [2017, 1, 13]]\n for i in range(0, len(expected)):\n d = datetime.date(expected[i][0], expected[i][1], expected[i][2])\n assert d == actual[i].date()\n" ]
f_36674519
create a DatetimeIndex containing 13 periods of the second friday of each month starting from date '2016-01-01'
[ "datetime", "pandas" ]
[ { "function": "pandas.date_range", "text": "pandas.date_range pandas.date_range(start=None, end=None, periods=None, freq=None, tz=None, normalize=False, name=None, closed=NoDefault.no_default, inclusive=None, **kwargs)[source]\n \nReturn a fixed frequency DatetimeIndex. Returns the range of equally spaced time points (where the difference between any two adjacent points is specified by the given frequency) such that they all satisfy start <[=] x <[=] end, where the first one and the last one are, resp., the first and last time points in that range that fall on the boundary of freq (if given as a frequency string) or that are valid for freq (if given as a pandas.tseries.offsets.DateOffset). (If exactly one of start, end, or freq is not specified, this missing parameter can be computed given periods, the number of timesteps in the range. See the note below.) Parameters ", "title": "pandas.reference.api.pandas.date_range" } ]
508,657
def f_508657():
return matrix
matrix = [['a', 'b'], ['c', 'd'], ['e', 'f']]
def check(candidate):
[ "\n matrix = candidate()\n assert len(matrix) == 3\n assert all([len(row)==2 for row in matrix])\n" ]
f_508657
Create multidimensional array `matrix` with 3 rows and 2 columns in python
[]
[]
1,007,481
def f_1007481(mystring): return
mystring.replace(' ', '_')
def check(candidate):
[ "\n assert candidate(' ') == '_'\n", "\n assert candidate(' _ ') == '___'\n", "\n assert candidate('') == ''\n", "\n assert candidate('123123') == '123123'\n", "\n assert candidate('\\_ ') == '\\__'\n" ]
f_1007481
replace spaces with underscore in string `mystring`
[]
[]
1,249,786
def f_1249786(my_string): return
""" """.join(my_string.split())
def check(candidate):
[ "\n assert candidate('hello world ') == 'hello world'\n", "\n assert candidate('') == ''\n", "\n assert candidate(' ') == ''\n", "\n assert candidate(' hello') == 'hello'\n", "\n assert candidate(' h e l l o ') == 'h e l l o'\n" ]
f_1249786
split string `my_string` on white spaces
[]
[]
4,444,923
def f_4444923(filename): return
os.path.splitext(filename)[0]
import os def check(candidate):
[ "\n assert candidate('/Users/test/hello.txt') == '/Users/test/hello'\n", "\n assert candidate('hello.txt') == 'hello'\n", "\n assert candidate('hello') == 'hello'\n", "\n assert candidate('.gitignore') == '.gitignore'\n" ]
f_4444923
get filename without extension from file `filename`
[ "os" ]
[ { "function": "os.splitext", "text": "os.path.splitext(path) \nSplit the pathname path into a pair (root, ext) such that root + ext ==\npath, and ext is empty or begins with a period and contains at most one period. Leading periods on the basename are ignored; splitext('.cshrc') returns ('.cshrc', ''). Changed in version 3.6: Accepts a path-like object.", "title": "python.library.os.path#os.path.splitext" } ]
13,728,486
def f_13728486(l): return
[sum(l[:i]) for i, _ in enumerate(l)]
def check(candidate):
[ "\n assert candidate([1,2,3]) == [0,1,3]\n", "\n assert candidate([]) == []\n", "\n assert candidate([1]) == [0]\n" ]
f_13728486
get a list containing the sum of each element `i` in list `l` plus the previous elements
[]
[]
9,743,134
def f_9743134(): return
"""Docs/src/Scripts/temp""".replace('/', '/\x00/').split('\x00')
def check(candidate):
[ "\n assert candidate() == ['Docs/', '/src/', '/Scripts/', '/temp']\n", "\n assert candidate() != ['Docs', 'src', 'Scripts', 'temp']\n" ]
f_9743134
split a string `Docs/src/Scripts/temp` by `/` keeping `/` in the result
[]
[]
20,546,419
def f_20546419(r): return
np.random.shuffle(np.transpose(r))
import numpy as np def check(candidate):
[ "\n a1 = np.array([[ 1, 20], [ 2, 30]])\n candidate(a1)\n assert np.array_equal(a1, np.array([[ 1, 20],[ 2, 30]])) or np.array_equal(a1, np.array([[ 20, 1], [ 30, 2]]))\n", "\n a2 = np.array([[ 1], [ 2]])\n candidate(a2) \n assert np.array_equal(a2,np.array([[ 1], [ 2]]) )\n", "\n a3 = np.array([[ 1,2,3]])\n candidate(a3)\n assert np.array_equal(a3,np.array([[ 1,2,3]])) or np.array_equal(a3,np.array([[ 2,1,3]])) or np.array_equal(a3,np.array([[ 1,3,2]])) or np.array_equal(a3,np.array([[3,2,1]])) or np.array_equal(a3,np.array([[3,1,2]])) or np.array_equal(a3,np.array([[2,3,1]])) \n", "\n a4 = np.zeros(shape=(5,2))\n candidate(a4)\n assert np.array_equal(a4, np.zeros(shape=(5,2)))\n" ]
f_20546419
shuffle columns of an numpy array 'r'
[ "numpy" ]
[ { "function": "numpy.shuffle", "text": "numpy.random.shuffle random.shuffle(x)\n \nModify a sequence in-place by shuffling its contents. This function only shuffles the array along the first axis of a multi-dimensional array. The order of sub-arrays is changed but their contents remains the same. Note New code should use the shuffle method of a default_rng() instance instead; please see the Quick Start. Parameters ", "title": "numpy.reference.random.generated.numpy.random.shuffle" } ]
32,675,861
def f_32675861(df):
return df
df['D'] = df['B']
import pandas as pd def check(candidate):
[ "\n df_1 = pd.DataFrame({'A': [1,2,3], 'B': ['a', 'b', 'c']})\n candidate(df_1)\n assert (df_1['D'] == df_1['B']).all()\n", "\n df_2 = pd.DataFrame({'A': [1,2,3], 'B': [1, 'A', 'B']})\n candidate(df_2)\n assert (df_2['D'] == df_2['B']).all()\n", "\n df_3 = pd.DataFrame({'B': [1]})\n candidate(df_3)\n assert df_3['D'][0] == 1\n", "\n df_4 = pd.DataFrame({'B': []})\n candidate(df_4)\n assert len(df_4['D']) == 0\n" ]
f_32675861
copy all values in a column 'B' to a new column 'D' in a pandas data frame 'df'
[ "pandas" ]
[]
14,227,561
def f_14227561(data): return
list(data['A']['B'].values())[0]['maindata'][0]['Info']
import json def check(candidate):
[ "\n s1 = '{\"A\":{\"B\":{\"unknown\":{\"1\":\"F\",\"maindata\":[{\"Info\":\"TEXT\"}]}}}}'\n data = json.loads(s1)\n assert candidate(data) == 'TEXT'\n", "\n s2 = '{\"A\":{\"B\":{\"sample1\":{\"1\":\"F\",\"maindata\":[{\"Info\":\"TEXT!\"}]}}}}'\n data = json.loads(s2)\n assert candidate(data) == 'TEXT!'\n", "\n s3 = '{\"A\":{\"B\":{\"sample_weird_un\":{\"1\":\"F\",\"maindata\":[{\"Info\":\"!\"}]}}}}'\n data = json.loads(s3)\n assert candidate(data) == '!'\n", "\n s4 = '{\"A\":{\"B\":{\"sample_weird_un\":{\"1\":\"F\",\"maindata\":[{\"Info\":\"\"}]}}}}'\n data = json.loads(s4)\n assert candidate(data) == ''\n" ]
f_14227561
find a value within nested json 'data' where the key inside another key 'B' is unknown.
[ "json" ]
[]
14,858,916
def f_14858916(string, predicate): return
all(predicate(x) for x in string)
def check(candidate):
[ "\n def predicate(x):\n if x == 'a':\n return True\n else:\n return False\n assert candidate('aab', predicate) == False\n", "\n def predicate(x):\n if x == 'a':\n return True\n else:\n return False\n assert candidate('aa', predicate) == True\n", "\n def predicate(x):\n if x == 'a':\n return True\n else:\n return False\n assert candidate('', predicate) == True\n", "\n def predicate(x):\n if x.islower():\n return True\n else:\n return False\n assert candidate('abc', predicate) == True\n", "\n def predicate(x):\n if x.islower():\n return True\n else:\n return False\n assert candidate('Ab', predicate) == False\n", "\n def predicate(x):\n if x.islower():\n return True\n else:\n return False\n assert candidate('ABCD', predicate) == False\n" ]
f_14858916
check characters of string `string` are true predication of function `predicate`
[]
[]
574,236
def f_574236(): return
os.statvfs('/').f_files - os.statvfs('/').f_ffree
import os def check(candidate):
[ "\n assert candidate() == (os.statvfs('/').f_files - os.statvfs('/').f_ffree)\n" ]
f_574236
determine number of files on a drive with python
[ "os" ]
[ { "function": "os.statvfs", "text": "os.statvfs(path) \nPerform a statvfs() system call on the given path. The return value is an object whose attributes describe the filesystem on the given path, and correspond to the members of the statvfs structure, namely: f_bsize, f_frsize, f_blocks, f_bfree, f_bavail, f_files, f_ffree, f_favail, f_flag, f_namemax, f_fsid. Two module-level constants are defined for the f_flag attribute’s bit-flags: if ST_RDONLY is set, the filesystem is mounted read-only, and if ST_NOSUID is set, the semantics of setuid/setgid bits are disabled or not supported. Additional module-level constants are defined for GNU/glibc based systems. These are ST_NODEV (disallow access to device special files), ST_NOEXEC (disallow program execution), ST_SYNCHRONOUS (writes are synced at once), ST_MANDLOCK (allow mandatory locks on an FS), ST_WRITE (write on file/directory/symlink), ST_APPEND (append-only file), ST_IMMUTABLE (immutable file), ST_NOATIME (do not update access times), ST_NODIRATIME (do not update directory access times), ST_RELATIME (update atime relative to mtime/ctime). This function can support specifying a file descriptor. Availability: Unix. Changed in version 3.2: The ST_RDONLY and ST_NOSUID constants were added. New in version 3.3: Added support for specifying path as an open file descriptor. Changed in version 3.4: The ST_NODEV, ST_NOEXEC, ST_SYNCHRONOUS, ST_MANDLOCK, ST_WRITE, ST_APPEND, ST_IMMUTABLE, ST_NOATIME, ST_NODIRATIME, and ST_RELATIME constants were added. Changed in version 3.6: Accepts a path-like object. New in version 3.7: Added f_fsid.", "title": "python.library.os#os.statvfs" } ]
7,011,291
def f_7011291(cursor): return
cursor.fetchone()[0]
import sqlite3 def check(candidate):
[ "\n conn = sqlite3.connect('main')\n cursor = conn.cursor()\n cursor.execute(\"CREATE TABLE student (name VARCHAR(10))\")\n cursor.execute(\"INSERT INTO student VALUES('abc')\")\n cursor.execute(\"SELECT * FROM student\")\n assert candidate(cursor) == 'abc'\n" ]
f_7011291
how to get a single result from a SQLite query from `cursor`
[ "sqlite3" ]
[ { "function": "cursor.fetchone", "text": "fetchone() \nFetches the next row of a query result set, returning a single sequence, or None when no more data is available.", "title": "python.library.sqlite3#sqlite3.Cursor.fetchone" } ]
6,378,889
def f_6378889(user_input):
return user_list
user_list = [int(number) for number in user_input.split(',')]
def check(candidate):
[ "\n assert candidate('0') == [0]\n", "\n assert candidate('12') == [12]\n", "\n assert candidate('12,33,223') == [12, 33, 223]\n" ]
f_6378889
convert string `user_input` into a list of integers `user_list`
[]
[]
6,378,889
def f_6378889(user): return
[int(s) for s in user.split(',')]
def check(candidate):
[ "\n assert candidate('0') == [0]\n", "\n assert candidate('12') == [12]\n", "\n assert candidate('12,33,223') == [12, 33, 223]\n" ]
f_6378889
Get a list of integers by splitting a string `user` with comma
[]
[]
5,212,870
def f_5212870(list): return
sorted(list, key=lambda x: (x[0], -x[1]))
def check(candidate):
[ "\n list = [(9, 0), (9, 1), (9, -1), (8, 5), (4, 5)]\n assert candidate(list) == [(4, 5), (8, 5), (9, 1), (9, 0), (9, -1)]\n" ]
f_5212870
Sorting a Python list `list` by the first item ascending and last item descending
[]
[]
403,421
def f_403421(ut, cmpfun):
return ut
ut.sort(key=cmpfun, reverse=True)
def check(candidate):
[ "\n assert candidate([], lambda x: x) == []\n", "\n assert candidate(['a', 'b', 'c'], lambda x: x) == ['c', 'b', 'a']\n", "\n assert candidate([2, 1, 3], lambda x: -x) == [1, 2, 3]\n" ]
f_403421
sort a list of objects `ut`, based on a function `cmpfun` in descending order
[]
[]
403,421
def f_403421(ut):
return ut
ut.sort(key=lambda x: x.count, reverse=True)
class Tag: def __init__(self, name, count): self.name = name self.count = count def __str__(self): return f"[{self.name}]-[{self.count}]" def check(candidate):
[ "\n result = candidate([Tag(\"red\", 1), Tag(\"blue\", 22), Tag(\"black\", 0)])\n assert (result[0].name == \"blue\") and (result[0].count == 22)\n assert (result[1].name == \"red\") and (result[1].count == 1)\n assert (result[2].name == \"black\") and (result[2].count == 0)\n" ]
f_403421
reverse list `ut` based on the `count` attribute of each object
[]
[]
3,944,876
def f_3944876(i): return
'ME' + str(i)
def check(candidate):
[ "\n assert candidate(100) == \"ME100\"\n", "\n assert candidate(0.22) == \"ME0.22\"\n", "\n assert candidate(\"text\") == \"MEtext\"\n" ]
f_3944876
cast an int `i` to a string and concat to string 'ME'
[]
[]
40,903,174
def f_40903174(df): return
df.sort_values(['System_num', 'Dis'])
import pandas as pd def check(candidate):
[ "\n df1 = pd.DataFrame([[6, 1, 1], [5, 1, 1], [4, 1, 1], [3, 2, 1], [2, 2, 1], [1, 2, 1]], columns = ['Dis', 'System_num', 'Energy'])\n df_ans1 = pd.DataFrame([[4, 1, 1], [5, 1, 1], [6, 1, 1], [1, 2, 1], [2, 2, 1], [3, 2, 1]], columns = ['Dis', 'System_num', 'Energy'])\n assert (df_ans1.equals(candidate(df1).reset_index(drop = True))) == True\n", "\n df2 = pd.DataFrame([[6, 3, 1], [5, 2, 1], [4, 1, 1]], columns = ['Dis', 'System_num', 'Energy'])\n df_ans2 = pd.DataFrame([[4, 1, 1], [5, 2, 1], [6, 3, 1]], columns = ['Dis', 'System_num', 'Energy'])\n assert (df_ans2.equals(candidate(df2).reset_index(drop = True))) == True\n", "\n df3 = pd.DataFrame([[1, 3, 1], [3, 3, 1], [2, 3, 1], [6, 1, 1], [4, 1, 1], [5, 2, 1], [3, 2, 1]], columns = ['Dis', 'System_num', 'Energy'])\n df_ans3 = pd.DataFrame([[4, 1,1], [6, 1, 1], [3, 2, 1], [5, 2, 1], [1, 3, 1], [2, 3, 1], [3, 3, 1]], columns = ['Dis', 'System_num', 'Energy'])\n assert (df_ans3.equals(candidate(df3).reset_index(drop = True))) == True \n", "\n df4 = pd.DataFrame([[1, 2, 3], [1, 2, 3], [4, 1, 3]], columns = ['Dis', 'System_num', 'Energy'])\n df_ans4 = pd.DataFrame([[1, 2, 3], [1, 2, 3], [4, 1, 3]])\n assert (df_ans4.equals(candidate(df4).reset_index(drop = True))) == False\n" ]
f_40903174
Sorting data in Pandas DataFrame `df` with columns 'System_num' and 'Dis'
[ "pandas" ]
[ { "function": "df.sort_values", "text": "pandas.DataFrame.sort_values DataFrame.sort_values(by, axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last', ignore_index=False, key=None)[source]\n \nSort by the values along either axis. Parameters ", "title": "pandas.reference.api.pandas.dataframe.sort_values" } ]
4,454,298
def f_4454298(infile, outfile):
return
open(outfile, 'w').write('#test firstline\n' + open(infile).read())
import filecmp def check(candidate):
[ "\n open('test1.txt', 'w').write('test1')\n candidate('test1.txt', 'test1_out.txt')\n open('test1_ans.txt', 'w').write('#test firstline\\ntest1')\n assert filecmp.cmp('test1_out.txt', 'test1_ans.txt') == True\n", "\n open('test2.txt', 'w').write('\\ntest2\\n')\n candidate('test2.txt', 'test2_out.txt')\n open('test2_ans.txt', 'w').write('#test firstline\\n\\ntest2\\n')\n assert filecmp.cmp('test2_out.txt', 'test2_ans.txt') == True\n", "\n open('test3.txt', 'w').write(' \\n \\n')\n candidate('test3.txt', 'test3_out.txt')\n open('test3_ans.txt', 'w').write('#test firstline\\n \\n \\n')\n assert filecmp.cmp('test3_out.txt', 'test3_ans.txt') == True\n", "\n open('test4.txt', 'w').write('hello')\n candidate('test4.txt', 'test4_out.txt')\n open('test4_ans.txt', 'w').write('hello')\n assert filecmp.cmp('test4_out.txt', 'test4_ans.txt') == False\n" ]
f_4454298
prepend the line '#test firstline\n' to the contents of file 'infile' and save as the file 'outfile'
[ "filecmp" ]
[]
19,729,928
def f_19729928(l):
return l
l.sort(key=lambda t: len(t[1]), reverse=True)
def check(candidate):
[ "\n assert candidate([(\"a\", [1]), (\"b\", [1,2]), (\"c\", [1,2,3])]) == [(\"c\", [1,2,3]), (\"b\", [1,2]), (\"a\", [1])]\n", "\n assert candidate([(\"a\", [1]), (\"b\", [2]), (\"c\", [1,2,3])]) == [(\"c\", [1,2,3]), (\"a\", [1]), (\"b\", [2])]\n", "\n assert candidate([(\"a\", [1]), (\"b\", [2]), (\"c\", [3])]) == [(\"a\", [1]), (\"b\", [2]), (\"c\", [3])]\n" ]
f_19729928
sort a list `l` by length of value in tuple
[]
[]
31,371,879
def f_31371879(s): return
re.findall('\\b(\\w+)d\\b', s)
import re def check(candidate):
[ "\n assert candidate(\"this is good\") == [\"goo\"]\n", "\n assert candidate(\"this is interesting\") == []\n", "\n assert candidate(\"good bad dd\") == [\"goo\", \"ba\", \"d\"]\n" ]
f_31371879
split string `s` by words that ends with 'd'
[ "re" ]
[ { "function": "re.findall", "text": "Pattern.findall(string[, pos[, endpos]]) \nSimilar to the findall() function, using the compiled pattern, but also accepts optional pos and endpos parameters that limit the search region like for search().", "title": "python.library.re#re.Pattern.findall" } ]
9,012,008
def f_9012008(): return
bool(re.search('ba[rzd]', 'foobarrrr'))
import re def check(candidate):
[ "\n assert candidate() == True\n" ]
f_9012008
return `True` if string `foobarrrr` contains regex `ba[rzd]`
[ "re" ]
[ { "function": "re.search", "text": "re.search(pattern, string, flags=0) \nScan through string looking for the first location where the regular expression pattern produces a match, and return a corresponding match object. Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string.", "title": "python.library.re#re.search" } ]
7,961,363
def f_7961363(t): return
list(set(t))
def check(candidate):
[ "\n assert candidate([1,2,3]) == [1,2,3]\n", "\n assert candidate([1,1,1,1,1,1,1,1,1,1]) == [1] \n", "\n assert candidate([1,2,2,2,2,2,3,3,3,3,3]) == [1,2,3]\n", "\n assert (candidate([1, '1']) == [1, '1']) or (candidate([1, '1']) == ['1', 1])\n", "\n assert candidate([1.0, 1]) == [1.0] \n", "\n assert candidate([]) == [] \n", "\n assert candidate([None]) == [None] \n" ]
f_7961363
Removing duplicates in list `t`
[]
[]
7,961,363
def f_7961363(source_list): return
list(set(source_list))
def check(candidate):
[ "\n assert candidate([1,2,3]) == [1,2,3]\n", "\n assert candidate([1,1,1,1,1,1,1,1,1,1]) == [1] \n", "\n assert candidate([1,2,2,2,2,2,3,3,3,3,3]) == [1,2,3]\n", "\n assert (candidate([1, '1']) == [1, '1']) or (candidate([1, '1']) == ['1', 1])\n", "\n assert candidate([1.0, 1]) == [1.0] \n", "\n assert candidate([]) == [] \n", "\n assert candidate([None]) == [None] \n" ]
f_7961363
Removing duplicates in list `source_list`
[]
[]
7,961,363
def f_7961363(): return
list(OrderedDict.fromkeys('abracadabra'))
from collections import OrderedDict def check(candidate):
[ "\n assert candidate() == ['a', 'b', 'r', 'c', 'd']\n" ]
f_7961363
Removing duplicates in list `abracadabra`
[ "collections" ]
[ { "function": "collections.OrderedDict", "text": "class collections.OrderedDict([items]) \nReturn an instance of a dict subclass that has methods specialized for rearranging dictionary order. New in version 3.1. \npopitem(last=True) \nThe popitem() method for ordered dictionaries returns and removes a (key, value) pair. The pairs are returned in LIFO order if last is true or FIFO order if false. \n \nmove_to_end(key, last=True) \nMove an existing key to either end of an ordered dictionary. The item is moved to the right end if last is true (the default) or to the beginning if last is false. Raises KeyError if the key does not exist: >>> d = OrderedDict.fromkeys('abcde')", "title": "python.library.collections#collections.OrderedDict" } ]
5,183,533
def f_5183533(a): return
numpy.array(a).reshape(-1).tolist()
import numpy def check(candidate):
[ "\n assert candidate([[1,2,3],[4,5,6]]) == [1,2,3,4,5,6]\n", "\n assert candidate(['a', 'aa', 'abc']) == ['a', 'aa', 'abc']\n" ]
f_5183533
Convert array `a` into a list
[ "numpy" ]
[ { "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" }, { "function": "numpy.ndarray.tolist", "text": "numpy.ndarray.tolist method ndarray.tolist()\n \nReturn the array as an a.ndim-levels deep nested list of Python scalars. Return a copy of the array data as a (nested) Python list. Data items are converted to the nearest compatible builtin Python type, via the item function. If a.ndim is 0, then since the depth of the nested list is 0, it will not be a list at all, but a simple Python scalar. Parameters \n none\n Returns \n \nyobject, or list of object, or list of list of object, or …\n\n\nThe possibly nested list of array elements. Notes The array may be recreated via a = np.array(a.tolist()), although this may sometimes lose precision. Examples For a 1D array, a.tolist() is almost the same as list(a), except that tolist changes numpy scalars to Python scalars: >>> a = np.uint32([1, 2])", "title": "numpy.reference.generated.numpy.ndarray.tolist" } ]
5,183,533
def f_5183533(a): return
numpy.array(a)[0].tolist()
import numpy def check(candidate):
[ "\n assert candidate([[1,2,3],[4,5,6]]) == [1,2,3]\n", "\n assert candidate(['a', 'aa', 'abc']) == 'a'\n" ]
f_5183533
Convert the first row of numpy matrix `a` to a list
[ "numpy" ]
[ { "function": "numpy.ndarray.tolist", "text": "numpy.ndarray.tolist method ndarray.tolist()\n \nReturn the array as an a.ndim-levels deep nested list of Python scalars. Return a copy of the array data as a (nested) Python list. Data items are converted to the nearest compatible builtin Python type, via the item function. If a.ndim is 0, then since the depth of the nested list is 0, it will not be a list at all, but a simple Python scalar. Parameters \n none\n Returns \n \nyobject, or list of object, or list of list of object, or …\n\n\nThe possibly nested list of array elements. Notes The array may be recreated via a = np.array(a.tolist()), although this may sometimes lose precision. Examples For a 1D array, a.tolist() is almost the same as list(a), except that tolist changes numpy scalars to Python scalars: >>> a = np.uint32([1, 2])", "title": "numpy.reference.generated.numpy.ndarray.tolist" } ]
5,999,747
def f_5999747(soup): return
soup.find(text='Address:').findNext('td').contents[0]
from bs4 import BeautifulSoup def check(candidate):
[ "\n assert candidate(BeautifulSoup(\"<td><b>Address:</b></td><td>My home address</td>\")) == \"My home address\"\n", "\n assert candidate(BeautifulSoup(\"<td><b>Address:</b></td><td>This is my home address</td><td>Not my home address</td>\")) == \"This is my home address\"\n", "\n assert candidate(BeautifulSoup(\"<td><b>Address:</b></td><td>My home address<li>My home address in a list</li></td>\")) == \"My home address\"\n" ]
f_5999747
In `soup`, get the content of the sibling of the `td` tag with text content `Address:`
[ "bs4" ]
[]
4,284,648
def f_4284648(l): return
""" """.join([('%d@%d' % t) for t in l])
def check(candidate):
[ "\n assert candidate([(1, 2), (3, 4)]) == \"1@2 3@4\"\n", "\n assert candidate([(10, 11), (12, 13)]) == \"10@11 12@13\"\n", "\n assert candidate([(10.2, 11.4), (12.14, 13.13)]) == \"10@11 12@13\"\n" ]
f_4284648
convert elements of each tuple in list `l` into a string separated by character `@`
[]
[]
4,284,648
def f_4284648(l): return
""" """.join([('%d@%d' % (t[0], t[1])) for t in l])
def check(candidate):
[ "\n assert candidate([(1, 2), (3, 4)]) == \"1@2 3@4\"\n", "\n assert candidate([(10, 11), (12, 13)]) == \"10@11 12@13\"\n", "\n assert candidate([(10.2, 11.4), (12.14, 13.13)]) == \"10@11 12@13\"\n" ]
f_4284648
convert each tuple in list `l` to a string with '@' separating the tuples' elements
[]
[]
29,696,641
def f_29696641(teststr): return
[i for i in teststr if re.search('\\d+[xX]', i)]
import re def check(candidate):
[ "\n assert candidate(['1 FirstString', '2x Sec String', '3rd String', 'x forString', '5X fifth']) == ['2x Sec String', '5X fifth']\n", "\n assert candidate(['1x', '2', '3X', '4x random', '5X random']) == ['1x', '3X', '4x random', '5X random']\n", "\n assert candidate(['1x', '2', '3X', '4xrandom', '5Xrandom']) == ['1x', '3X', '4xrandom', '5Xrandom']\n" ]
f_29696641
Get all matches with regex pattern `\\d+[xX]` in list of string `teststr`
[ "re" ]
[ { "function": "re.search", "text": "re.search(pattern, string, flags=0) \nScan through string looking for the first location where the regular expression pattern produces a match, and return a corresponding match object. Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string.", "title": "python.library.re#re.search" } ]
15,315,452
def f_15315452(df): return
df['A'][(df['B'] > 50) & (df['C'] == 900)]
import pandas as pd def check(candidate):
[ "\n df = pd.DataFrame({'A': [7, 7, 4, 4, 7, 7, 3, 9, 6, 3], 'B': [20, 80, 90, 30, 80, 60, 80, 40, 40 ,10], 'C': [300, 700, 100, 900, 200, 800, 900, 100, 100, 600]})\n assert candidate(df).to_dict() == {6: 3}\n", "\n df1 = pd.DataFrame({'A': [9, 9, 5, 8, 7, 9, 2, 2, 5, 7], 'B': [40, 70, 70, 80, 50, 30, 80, 80, 80, 70], 'C': [300, 700, 900, 900, 200, 900, 700, 400, 300, 800]})\n assert candidate(df1).to_dict() == {2: 5, 3: 8}\n", "\n df2 = pd.DataFrame({'A': [3, 4, 5, 6], 'B': [-10, 50, 20, 10], 'C': [900, 800, 900, 900]})\n assert candidate(df2).to_dict() == {}\n" ]
f_15315452
select values from column 'A' for which corresponding values in column 'B' will be greater than 50, and in column 'C' - equal 900 in dataframe `df`
[ "pandas" ]
[]
4,642,501
def f_4642501(o): return
sorted(o.items())
import pandas as pd def check(candidate):
[ "\n assert candidate({1:\"abc\", 5:\"klm\", 2:\"pqr\"}) == [(1, \"abc\"), (2, \"pqr\"), (5, \"klm\")]\n", "\n assert candidate({4.221:\"uwv\", -1.009:\"pow\"}) == [(-1.009, 'pow'), (4.221, 'uwv')]\n", "\n assert candidate({\"as2q\":\"piqr\", \"#wwq\":\"say\", \"Rwc\":\"koala\", \"35\":\"kangaroo\"}) == [('#wwq', 'say'), ('35', 'kangaroo'), ('Rwc', 'koala'), ('as2q', 'piqr')]\n" ]
f_4642501
Sort dictionary `o` in ascending order based on its keys and items
[ "pandas" ]
[]
4,642,501
def f_4642501(d): return
sorted(d)
def check(candidate):
[ "\n assert candidate({1:\"abc\", 5:\"klm\", 2:\"pqr\"}) == [1, 2, 5]\n", "\n assert candidate({4.221:\"uwv\", -1.009:\"pow\"}) == [-1.009, 4.221]\n", "\n assert candidate({\"as2q\":\"piqr\", \"#wwq\":\"say\", \"Rwc\":\"koala\", \"35\":\"kangaroo\"}) == ['#wwq', '35', 'Rwc', 'as2q']\n" ]
f_4642501
get sorted list of keys of dict `d`
[]
[]
4,642,501
def f_4642501(d): return
sorted(d.items())
def check(candidate):
[ "\n d = {'a': [1, 2, 3], 'c': ['one', 'two'], 'b': ['blah', 'bhasdf', 'asdf'], 'd': ['asdf', 'wer', 'asdf', 'zxcv']}\n assert candidate(d) == [('a', [1, 2, 3]), ('b', ['blah', 'bhasdf', 'asdf']), ('c', ['one', 'two']), ('d', ['asdf', 'wer', 'asdf', 'zxcv'])]\n" ]
f_4642501
sort dictionaries `d` by keys
[]
[]
642,154
def f_642154(): return
int('1')
def check(candidate):
[ "\n assert candidate() == 1\n", "\n assert candidate() + 1 == 2\n" ]
f_642154
convert string "1" into integer
[]
[]
642,154
def f_642154(T1): return
[list(map(int, x)) for x in T1]
def check(candidate):
[ "\n T1 = (('13', '17', '18', '21', '32'), ('07', '11', '13', '14', '28'), ('01', '05', '06', '08', '15', '16'))\n assert candidate(T1) == [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]\n" ]
f_642154
convert items in `T1` to integers
[]
[]
3,777,301
def f_3777301():
return
subprocess.call(['./test.sh'])
import subprocess from unittest.mock import Mock def check(candidate):
[ "\n subprocess.call = Mock()\n try:\n candidate()\n except:\n assert False\n" ]
f_3777301
call a shell script `./test.sh` using subprocess
[ "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" } ]
3,777,301
def f_3777301():
return
subprocess.call(['notepad'])
import subprocess from unittest.mock import Mock def check(candidate):
[ "\n subprocess.call = Mock()\n try:\n candidate()\n except:\n assert False\n" ]
f_3777301
call a shell script `notepad` using subprocess
[ "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" } ]
7,946,798
def f_7946798(l1, l2): return
[val for pair in zip(l1, l2) for val in pair]
def check(candidate):
[ "\n assert candidate([1,2,3], [10,20,30]) == [1,10,2,20,3,30]\n", "\n assert candidate([1,2,3], ['c','b','a']) == [1,'c',2,'b',3,'a']\n", "\n assert candidate([1,2,3], ['c','b']) == [1,'c',2,'b']\n" ]
f_7946798
combine lists `l1` and `l2` by alternating their elements
[]
[]
8,908,287
def f_8908287(): return
base64.b64encode(b'data to be encoded')
import base64 def check(candidate):
[ "\n assert candidate() == b'ZGF0YSB0byBiZSBlbmNvZGVk'\n" ]
f_8908287
encode string 'data to be encoded'
[ "base64" ]
[ { "function": "base64.b64encode", "text": "base64.b64encode(s, altchars=None) \nEncode the bytes-like object s using Base64 and return the encoded bytes. Optional altchars must be a bytes-like object of at least length 2 (additional characters are ignored) which specifies an alternative alphabet for the + and / characters. This allows an application to e.g. generate URL or filesystem safe Base64 strings. The default is None, for which the standard Base64 alphabet is used.", "title": "python.library.base64#base64.b64encode" } ]
8,908,287
def f_8908287(): return
'data to be encoded'.encode('ascii')
def check(candidate):
[ "\n assert candidate() == b'data to be encoded'\n" ]
f_8908287
encode a string `data to be encoded` to `ascii` encoding
[]
[]
7,856,296
def f_7856296(): return
list(csv.reader(open('text.txt', 'r'), delimiter='\t'))
import csv def check(candidate):
[ "\n with open('text.txt', 'w', newline='') as csvfile:\n spamwriter = csv.writer(csvfile, delimiter='\t')\n spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])\n spamwriter.writerow(['hello', 'world', '!'])\n\n assert candidate() == [['Spam', 'Lovely Spam', 'Wonderful Spam'], ['hello', 'world', '!']]\n" ]
f_7856296
parse tab-delimited CSV file 'text.txt' into a list
[ "csv" ]
[ { "function": "csv.reader", "text": "csv.reader(csvfile, dialect='excel', **fmtparams) \nReturn a reader object which will iterate over lines in the given csvfile. csvfile can be any object which supports the iterator protocol and returns a string each time its __next__() method is called — file objects and list objects are both suitable. If csvfile is a file object, it should be opened with newline=''. 1 An optional dialect parameter can be given which is used to define a set of parameters specific to a particular CSV dialect. It may be an instance of a subclass of the Dialect class or one of the strings returned by the list_dialects() function. The other optional fmtparams keyword arguments can be given to override individual formatting parameters in the current dialect. For full details about the dialect and formatting parameters, see section Dialects and Formatting Parameters. Each row read from the csv file is returned as a list of strings. No automatic data type conversion is performed unless the QUOTE_NONNUMERIC format option is specified (in which case unquoted fields are transformed into floats). A short usage example: >>> import csv", "title": "python.library.csv#csv.reader" } ]
9,035,479
def f_9035479(my_object, my_str): return
getattr(my_object, my_str)
def check(candidate):
[ "\n class Student:\n id = 9\n name = \"abc\"\n grade = 97.08\n\n s = Student()\n \n assert candidate(s, \"name\") == \"abc\"\n", "\n class Student:\n id = 9\n name = \"abc\"\n grade = 97.08\n\n s = Student()\n \n assert (candidate(s, \"grade\") - 97.08) < 1e-6\n", "\n class Student:\n id = 9\n name = \"abc\"\n grade = 97.08\n\n s = Student()\n \n assert (candidate(s, \"grade\") - 97.07) > 1e-6\n", "\n class Student:\n id = 9\n name = \"abc\"\n grade = 97.08\n\n s = Student()\n \n assert candidate(s, \"id\") == 9\n" ]
f_9035479
Get attribute `my_str` of object `my_object`
[]
[]
5,558,418
def f_5558418(LD): return
dict(zip(LD[0], zip(*[list(d.values()) for d in LD])))
import collections def check(candidate):
[ "\n employees = [{'name' : 'apple', 'id': 60}, {'name' : 'orange', 'id': 65}]\n exp_result = {'name': ('apple', 'orange'), 'id': (60, 65)}\n actual_result = candidate(employees)\n for key in actual_result:\n assert collections.Counter(list(exp_result[key])) == collections.Counter(list(actual_result[key]))\n" ]
f_5558418
group a list of dicts `LD` into one dict by key
[ "collections" ]
[]