Code Generation Datasets
Collection
Dataset files for the code generation task.
•
4 items
•
Updated
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
|
---|---|---|---|---|---|---|---|---|---|
3,283,984 | def f_3283984():
return | bytes.fromhex('4a4b4c').decode('utf-8') |
def check(candidate): | [
"\n assert candidate() == \"JKL\"\n"
] | f_3283984 | decode a hex string '4a4b4c' to UTF-8. | [] | [] |
|
3,844,801 | def f_3844801(myList):
return | all(x == myList[0] for x in myList) |
def check(candidate): | [
"\n assert candidate([1,2,3]) == False\n",
"\n assert candidate([1,1,1,1,1,1]) == True\n",
"\n assert candidate([1]) == True\n",
"\n assert candidate(['k','k','k','k','k']) == True\n",
"\n assert candidate([None,'%$#ga',3]) == False\n"
] | f_3844801 | check if all elements in list `myList` are identical | [] | [] |
|
4,302,166 | def f_4302166():
return | '%*s : %*s' % (20, 'Python', 20, 'Very Good') |
def check(candidate): | [
"\n assert candidate() == ' Python : Very Good'\n"
] | f_4302166 | format number of spaces between strings `Python`, `:` and `Very Good` to be `20` | [] | [] |
|
7,555,335 | def f_7555335(d):
return | d.decode('cp1251').encode('utf8') |
def check(candidate): | [
"\n assert candidate('hello world!'.encode('cp1251')) == b'hello world!'\n",
"\n assert candidate('%*(^O*'.encode('cp1251')) == b'%*(^O*'\n",
"\n assert candidate(''.encode('cp1251')) == b''\n",
"\n assert candidate('hello world!'.encode('cp1251')) != 'hello world!'\n"
] | f_7555335 | convert a string `d` from CP-1251 to UTF-8 | [] | [] |
|
2,544,710 | def f_2544710(kwargs):
return | {k: v for k, v in list(kwargs.items()) if v is not None} |
def check(candidate): | [
"\n assert candidate({i: None for i in range(10)}) == {}\n",
"\n assert candidate({i: min(i,4) for i in range(6)}) == {0:0,1:1,2:2,3:3,4:4,5:4}\n",
"\n assert candidate({'abc': 'abc'})['abc'] == 'abc'\n",
"\n assert candidate({'x': None, 'yy': 234}) == {'yy': 234}\n"
] | f_2544710 | get rid of None values in dictionary `kwargs` | [] | [] |
|
2,544,710 | def f_2544710(kwargs):
return | dict((k, v) for k, v in kwargs.items() if v is not None) |
def check(candidate): | [
"\n assert candidate({i: None for i in range(10)}) == {}\n",
"\n assert candidate({i: min(i,4) for i in range(6)}) == {0:0,1:1,2:2,3:3,4:4,5:4}\n",
"\n assert candidate({'abc': 'abc'})['abc'] == 'abc'\n",
"\n assert candidate({'x': None, 'yy': 234}) == {'yy': 234}\n"
] | f_2544710 | get rid of None values in dictionary `kwargs` | [] | [] |
|
14,971,373 | def f_14971373():
return | subprocess.check_output('ps -ef | grep something | wc -l', shell=True) |
import subprocess
from unittest.mock import Mock
def check(candidate): | [
"\n output = b' PID TTY TIME CMD\\n 226 pts/1 00:00:00 bash\\n 285 pts/1 00:00:00 python3\\n 352 pts/1 00:00:00 ps\\n'\n subprocess.check_output = Mock(return_value = output)\n assert candidate() == output\n"
] | f_14971373 | capture final output of a chain of system commands `ps -ef | grep something | wc -l` | [
"subprocess"
] | [
{
"function": "subprocess.check_output",
"text": "subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, cwd=None, encoding=None, errors=None, universal_newlines=None, timeout=None, text=None, **other_popen_kwargs) \nRun command with arguments and return its output. If the return code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute and any output in the output attribute. This is equivalent to: run(..., check=True, stdout=PIPE).stdout\n The arguments shown above are merely some common ones. The full function signature is largely the same as that of run() - most arguments are passed directly through to that interface. One API deviation from run() behavior exists: passing input=None will behave the same as input=b'' (or input='', depending on other arguments) rather than using the parent’s standard input file handle. By default, this function will return the data as encoded bytes. The actual encoding of the output data may depend on the command being invoked, so the decoding to text will often need to be handled at the application level. This behaviour may be overridden by setting text, encoding, errors, or universal_newlines to True as described in Frequently Used Arguments and run(). To also capture standard error in the result, use stderr=subprocess.STDOUT: >>> subprocess.check_output(\n... \"ls non_existent_file; exit 0\",\n... stderr=subprocess.STDOUT,\n... shell=True)\n'ls: non_existent_file: No such file or directory\\n'\n New in version 3.1. Changed in version 3.3: timeout was added. Changed in version 3.4: Support for the input keyword argument was added. Changed in version 3.6: encoding and errors were added. See run() for details. New in version 3.7: text was added as a more readable alias for universal_newlines.",
"title": "python.library.subprocess#subprocess.check_output"
}
] |
|
6,726,636 | def f_6726636():
return | """""".join(['a', 'b', 'c']) |
def check(candidate): | [
"\n assert candidate() == \"abc\"\n",
"\n assert candidate() == 'a' + 'b' + 'c'\n"
] | f_6726636 | concatenate a list of strings `['a', 'b', 'c']` | [] | [] |
|
18,079,563 | def f_18079563(s1, s2):
return | pd.Series(list(set(s1).intersection(set(s2)))) |
import pandas as pd
def check(candidate): | [
"\n x1, x2 = pd.Series([1,2]), pd.Series([1,3])\n assert candidate(x1, x2).equals(pd.Series([1]))\n",
"\n x1, x2 = pd.Series([1,2]), pd.Series([1,3, 10, 4, 5, 9])\n assert candidate(x1, x2).equals(pd.Series([1]))\n",
"\n x1, x2 = pd.Series([1,2]), pd.Series([1,2, 10])\n assert candidate(x1, x2).equals(pd.Series([1, 2]))\n"
] | f_18079563 | find intersection data between series `s1` and series `s2` | [
"pandas"
] | [
{
"function": "pandas.series",
"text": "Series Constructor \nSeries([data, index, dtype, name, copy, ...]) One-dimensional ndarray with axis labels (including time series). Attributes Axes \nSeries.index The index (axis labels) of the Series. ",
"title": "pandas.reference.series"
}
] |
|
8,315,209 | def f_8315209(client):
|
return | client.send('HTTP/1.0 200 OK\r\n') |
import socket
from unittest.mock import Mock
import mock
def check(candidate): | [
"\n with mock.patch('socket.socket') as mock_socket:\n mock_socket.return_value.recv.return_value = ''\n mock_socket.bind(('', 8080))\n mock_socket.listen(5)\n mock_socket.accept = Mock(return_value = mock_socket)\n mock_socket.send = Mock()\n try:\n candidate(mock_socket)\n except:\n assert False\n"
] | f_8315209 | sending http headers to `client` | [
"socket"
] | [
{
"function": "client.send",
"text": "socket.send(bytes[, flags]) \nSend data to the socket. The socket must be connected to a remote socket. The optional flags argument has the same meaning as for recv() above. Returns the number of bytes sent. Applications are responsible for checking that all data has been sent; if only some of the data was transmitted, the application needs to attempt delivery of the remaining data. For further information on this topic, consult the Socket Programming HOWTO. Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an exception, the method now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale).",
"title": "python.library.socket#socket.socket.send"
}
] |
26,153,795 | def f_26153795(when):
return | datetime.datetime.strptime(when, '%Y-%m-%d').date() |
import datetime
def check(candidate): | [
"\n assert candidate('2013-05-07') == datetime.date(2013, 5, 7)\n",
"\n assert candidate('2000-02-29') == datetime.date(2000, 2, 29)\n",
"\n assert candidate('1990-01-08') == datetime.date(1990, 1, 8)\n",
"\n assert candidate('1990-1-08') == datetime.date(1990, 1, 8)\n",
"\n assert candidate('1990-1-8') == datetime.date(1990, 1, 8)\n",
"\n assert candidate('1990-01-8') == datetime.date(1990, 1, 8)\n"
] | f_26153795 | Format a datetime string `when` to extract date only | [
"datetime"
] | [
{
"function": "datetime.datetime.strptime",
"text": "classmethod datetime.strptime(date_string, format) \nReturn a datetime corresponding to date_string, parsed according to format. This is equivalent to: datetime(*(time.strptime(date_string, format)[0:6]))\n ValueError is raised if the date_string and format can’t be parsed by time.strptime() or if it returns a value which isn’t a time tuple. For a complete list of formatting directives, see strftime() and strptime() Behavior.",
"title": "python.library.datetime#datetime.datetime.strptime"
}
] |
|
172,439 | def f_172439(inputString):
return | inputString.split('\n') |
def check(candidate): | [
"\n assert candidate('line a\\nfollows by line b\t...bye\\n') == ['line a', 'follows by line b\t...bye', '']\n",
"\n assert candidate('no new line in this sentence. ') == ['no new line in this sentence. ']\n",
"\n assert candidate('a\tbfs hhhdf\tsfdas') == ['a\tbfs hhhdf\tsfdas']\n",
"\n assert candidate('') == ['']\n"
] | f_172439 | split a multi-line string `inputString` into separate strings | [] | [] |
|
172,439 | def f_172439():
return | ' a \n b \r\n c '.split('\n') |
def check(candidate): | [
"\n assert candidate() == [' a ', ' b \\r', ' c ']\n"
] | f_172439 | Split a multi-line string ` a \n b \r\n c ` by new line character `\n` | [] | [] |
|
13,954,222 | def f_13954222(b):
return | """:""".join(str(x) for x in b) |
def check(candidate): | [
"\n assert candidate(['x','y','zzz']) == 'x:y:zzz'\n",
"\n assert candidate(['111','22','3']) == '111:22:3'\n",
"\n assert candidate(['']) == ''\n",
"\n assert candidate([':',':']) == ':::'\n",
"\n assert candidate([',','#','#$%']) == ',:#:#$%'\n",
"\n assert candidate(['a','b','c']) != 'abc'\n"
] | f_13954222 | concatenate elements of list `b` by a colon ":" | [] | [] |
|
13,567,345 | def f_13567345(a):
return | a.sum(axis=1) |
import numpy as np
def check(candidate): | [
"\n a1 = np.array([[i for i in range(3)] for j in range(5)])\n assert np.array_equal(candidate(a1), np.array([3, 3, 3, 3, 3]))\n",
"\n a2 = np.array([[i+j for i in range(3)] for j in range(5)])\n assert np.array_equal(candidate(a2), np.array([ 3, 6, 9, 12, 15]))\n",
"\n a3 = np.array([[i*j for i in range(3)] for j in range(5)])\n assert np.array_equal(candidate(a3), np.array([ 0, 3, 6, 9, 12]))\n"
] | f_13567345 | Calculate sum over all rows of 2D numpy array `a` | [
"numpy"
] | [
{
"function": "a.sum",
"text": "numpy.sum numpy.sum(a, axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)[source]\n \nSum of array elements over a given axis. Parameters ",
"title": "numpy.reference.generated.numpy.sum"
}
] |
|
29,784,889 | def f_29784889():
|
return | warnings.simplefilter('always') |
import warnings
def check(candidate): | [
"\n candidate() \n assert any([(wf[0] == 'always') for wf in warnings.filters])\n"
] | f_29784889 | enable warnings using action 'always' | [
"warnings"
] | [
{
"function": "warnings.simplefilter",
"text": "warnings.simplefilter(action, category=Warning, lineno=0, append=False) \nInsert a simple entry into the list of warnings filter specifications. The meaning of the function parameters is as for filterwarnings(), but regular expressions are not needed as the filter inserted always matches any message in any module as long as the category and line number match.",
"title": "python.library.warnings#warnings.simplefilter"
}
] |
13,550,423 | def f_13550423(l):
return | ' '.join(map(str, l)) |
def check(candidate): | [
"\n assert candidate(['x','y','zzz']) == 'x y zzz'\n",
"\n assert candidate(['111','22','3']) == '111 22 3'\n",
"\n assert candidate(['']) == ''\n",
"\n assert candidate([':',':']) == ': :'\n",
"\n assert candidate([',','#','#$%']) == ', # #$%'\n",
"\n assert candidate(['a','b','c']) != 'abc'\n"
] | f_13550423 | concatenate items of list `l` with a space ' ' | [] | [] |
|
698,223 | def f_698223():
return | time.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S.%f') |
import time
def check(candidate): | [
"\n answer = time.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S.%f')\n assert candidate() == answer\n false_1 = time.strptime('30/03/09 17:31:32.123', '%d/%m/%y %H:%M:%S.%f')\n assert candidate() != false_1\n false_2 = time.strptime('20/03/09 17:31:32.123', '%d/%m/%y %H:%M:%S.%f')\n assert candidate() != false_2\n"
] | f_698223 | parse a time string '30/03/09 16:31:32.123' containing milliseconds in it | [
"time"
] | [
{
"function": "time.strptime",
"text": "time.strptime(string[, format]) \nParse a string representing a time according to a format. The return value is a struct_time as returned by gmtime() or localtime(). The format parameter uses the same directives as those used by strftime(); it defaults to \"%a %b %d %H:%M:%S %Y\" which matches the formatting returned by ctime(). If string cannot be parsed according to format, or if it has excess data after parsing, ValueError is raised. The default values used to fill in any missing data when more accurate values cannot be inferred are (1900, 1, 1, 0, 0, 0, 0, 1, -1). Both string and format must be strings. For example: >>> import time",
"title": "python.library.time#time.strptime"
}
] |
|
6,633,523 | def f_6633523(my_string):
|
return my_float | my_float = float(my_string.replace(',', '')) |
def check(candidate): | [
"\n assert (candidate('1,234.00') - 1234.0) < 1e-6\n",
"\n assert (candidate('0.00') - 0.00) < 1e-6\n",
"\n assert (candidate('1,000,000.00') - 1000000.00) < 1e-6\n",
"\n assert (candidate('1,000,000.00') - 999999.98) > 1e-6\n",
"\n assert (candidate('1') - 1.00) < 1e-6\n"
] | f_6633523 | convert a string `my_string` with dot and comma into a float number `my_float` | [] | [] |
6,633,523 | def f_6633523():
return | float('123,456.908'.replace(',', '')) |
def check(candidate): | [
"\n assert (candidate() - 123456.908) < 1e-6\n assert (candidate() - 123456.9) > 1e-6\n assert (candidate() - 1234.908) > 1e-6\n assert type(candidate()) == float\n assert int(candidate()) == 123456\n"
] | f_6633523 | convert a string `123,456.908` with dot and comma into a floating number | [] | [] |
|
3,108,285 | def f_3108285():
|
return | sys.path.append('/path/to/whatever') |
import sys
def check(candidate): | [
"\n original_paths = [sp for sp in sys.path]\n candidate()\n assert '/path/to/whatever' in sys.path\n"
] | f_3108285 | set python path '/path/to/whatever' in python script | [
"sys"
] | [
{
"function": "sys.append",
"text": "sys — System-specific parameters and functions This module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter. It is always available. \nsys.abiflags \nOn POSIX systems where Python was built with the standard configure script, this contains the ABI flags as specified by PEP 3149. Changed in version 3.8: Default flags became an empty string (m flag for pymalloc has been removed). New in version 3.2. \n ",
"title": "python.library.sys"
}
] |
2,195,340 | def f_2195340():
return | re.split('(\\W+)', 'Words, words, words.') |
import re
def check(candidate): | [
"\n assert candidate() == ['Words', ', ', 'words', ', ', 'words', '.', '']\n assert candidate() == ['Words', ', '] + ['words', ', ', 'words', '.', '']\n"
] | f_2195340 | split string 'Words, words, words.' using a regex '(\\W+)' | [
"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"
}
] |
|
17,977,584 | def f_17977584():
return | open('Output.txt', 'a') |
def check(candidate): | [
"\n f = candidate()\n assert str(f.__class__) == \"<class '_io.TextIOWrapper'>\"\n assert f.name == 'Output.txt'\n assert f.mode == 'a'\n"
] | f_17977584 | open a file `Output.txt` in append mode | [] | [] |
|
22,676 | def f_22676():
return | urllib.request.urlretrieve('https://github.com/zorazrw/multilingual-conala/blob/master/dataset/test/es_test.json', 'mp3.mp3') |
import urllib
def check(candidate): | [
"\n results = candidate()\n assert len(results) == 2\n assert results[0] == \"mp3.mp3\"\n assert results[1].values()[0] == \"GitHub.com\"\n"
] | f_22676 | download a file "http://www.example.com/songs/mp3.mp3" over HTTP and save to "mp3.mp3" | [
"urllib"
] | [
{
"function": "urllib.urlretrieve",
"text": "urllib.request.urlretrieve(url, filename=None, reporthook=None, data=None) \nCopy a network object denoted by a URL to a local file. If the URL points to a local file, the object will not be copied unless filename is supplied. Return a tuple (filename, headers) where filename is the local file name under which the object can be found, and headers is whatever the info() method of the object returned by urlopen() returned (for a remote object). Exceptions are the same as for urlopen(). The second argument, if present, specifies the file location to copy to (if absent, the location will be a tempfile with a generated name). The third argument, if present, is a callable that will be called once on establishment of the network connection and once after each block read thereafter. The callable will be passed three arguments; a count of blocks transferred so far, a block size in bytes, and the total size of the file. The third argument may be -1 on older FTP servers which do not return a file size in response to a retrieval request. The following example illustrates the most common usage scenario: >>> import urllib.request",
"title": "python.library.urllib.request#urllib.request.urlretrieve"
}
] |
|
22,676 | def f_22676(url):
|
return html | html = urllib.request.urlopen(url).read() |
import urllib
def check(candidate): | [
"\n html = candidate(\"https://github.com/zorazrw/multilingual-conala/blob/master/dataset/test/es_test.json\")\n assert b\"zorazrw/multilingual-conala\" in html\n"
] | f_22676 | download a file 'http://www.example.com/' over HTTP | [
"urllib"
] | [
{
"function": "urllib.request.urlopen",
"text": "urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None) \nOpen the URL url, which can be either a string or a Request object. data must be an object specifying additional data to be sent to the server, or None if no such data is needed. See Request for details. urllib.request module uses HTTP/1.1 and includes Connection:close header in its HTTP requests. The optional timeout parameter specifies a timeout in seconds for blocking operations like the connection attempt (if not specified, the global default timeout setting will be used). This actually only works for HTTP, HTTPS and FTP connections. If context is specified, it must be a ssl.SSLContext instance describing the various SSL options. See HTTPSConnection for more details. The optional cafile and capath parameters specify a set of trusted CA certificates for HTTPS requests. cafile should point to a single file containing a bundle of CA certificates, whereas capath should point to a directory of hashed certificate files. More information can be found in ssl.SSLContext.load_verify_locations(). The cadefault parameter is ignored. This function always returns an object which can work as a context manager and has the properties url, headers, and status. See urllib.response.addinfourl for more detail on these properties. For HTTP and HTTPS URLs, this function returns a http.client.HTTPResponse object slightly modified. In addition to the three new methods above, the msg attribute contains the same information as the reason attribute — the reason phrase returned by server — instead of the response headers as it is specified in the documentation for HTTPResponse. For FTP, file, and data URLs and requests explicitly handled by legacy URLopener and FancyURLopener classes, this function returns a urllib.response.addinfourl object. Raises URLError on protocol errors. Note that None may be returned if no handler handles the request (though the default installed global OpenerDirector uses UnknownHandler to ensure this never happens). In addition, if proxy settings are detected (for example, when a *_proxy environment variable like http_proxy is set), ProxyHandler is default installed and makes sure the requests are handled through the proxy. The legacy urllib.urlopen function from Python 2.6 and earlier has been discontinued; urllib.request.urlopen() corresponds to the old urllib2.urlopen. Proxy handling, which was done by passing a dictionary parameter to urllib.urlopen, can be obtained by using ProxyHandler objects.\nThe default opener raises an auditing event urllib.Request with arguments fullurl, data, headers, method taken from the request object. Changed in version 3.2: cafile and capath were added. Changed in version 3.2: HTTPS virtual hosts are now supported if possible (that is, if ssl.HAS_SNI is true). New in version 3.2: data can be an iterable object. Changed in version 3.3: cadefault was added. Changed in version 3.4.3: context was added. Deprecated since version 3.6: cafile, capath and cadefault are deprecated in favor of context. Please use ssl.SSLContext.load_cert_chain() instead, or let ssl.create_default_context() select the system’s trusted CA certificates for you.",
"title": "python.library.urllib.request#urllib.request.urlopen"
}
] |
22,676 | def f_22676(url):
return | requests.get(url) |
import requests
def check(candidate): | [
"\n assert candidate(\"https://github.com/\").url == \"https://github.com/\"\n",
"\n assert candidate(\"https://google.com/\").url == \"https://www.google.com/\"\n"
] | f_22676 | download a file `url` over HTTP | [
"requests"
] | [] |
|
22,676 | def f_22676(url):
|
return |
response = requests.get(url, stream=True)
with open('10MB', 'wb') as handle:
for data in response.iter_content():
handle.write(data)
|
import requests
def check(candidate): | [
"\n candidate(\"https://github.com/\")\n with open(\"10MB\", 'rb') as fr: \n all_data = [data for data in fr]\n assert all_data[: 2] == [b'\\n', b'\\n']\n"
] | f_22676 | download a file `url` over HTTP and save to "10MB" | [
"requests"
] | [] |
15,405,636 | def f_15405636(parser):
return | parser.add_argument('--version', action='version', version='%(prog)s 2.0') |
import argparse
def check(candidate): | [
"\n parser = argparse.ArgumentParser()\n output = candidate(parser)\n assert output.option_strings == ['--version']\n assert output.dest == 'version'\n assert output.nargs == 0\n"
] | f_15405636 | argparse add argument with flag '--version' and version action of '%(prog)s 2.0' to parser `parser` | [
"argparse"
] | [
{
"function": "parser.add_argument",
"text": "ArgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest]) \nDefine how a single command-line argument should be parsed. Each parameter has its own more detailed description below, but in short they are: \nname or flags - Either a name or a list of option strings, e.g. foo or -f, --foo. ",
"title": "python.library.argparse#argparse.ArgumentParser.add_argument"
}
] |
|
17,665,809 | def f_17665809(d):
return | {i: d[i] for i in d if i != 'c'} |
def check(candidate): | [
"\n assert candidate({'a': 1 , 'b': 2, 'c': 3}) == {'a': 1 , 'b': 2}\n",
"\n assert candidate({'c': None}) == {}\n",
"\n assert candidate({'a': 1 , 'b': 2, 'c': 3}) != {'a': 1 , 'b': 2, 'c': 3}\n",
"\n assert candidate({'c': 1, 'cc': 2, 'ccc':3}) == {'cc': 2, 'ccc':3}\n",
"\n assert 'c' not in candidate({'c':i for i in range(10)})\n"
] | f_17665809 | remove key 'c' from dictionary `d` | [] | [] |
|
41,861,705 | def f_41861705(split_df, csv_df):
return | pd.merge(split_df, csv_df, on=['key'], suffixes=('_left', '_right')) |
import pandas as pd
def check(candidate): | [
"\n split_df = pd.DataFrame({'key': ['foo', 'bar'], 'value': [1, 2]})\n csv_df = pd.DataFrame({'key': ['foo', 'baz'], 'value': [3, 4]})\n result = pd.DataFrame({'key': ['foo'], 'value_left': [1],'value_right': [3]})\n assert all(candidate(csv_df, split_df) == result)\n"
] | f_41861705 | Create new DataFrame object by merging columns "key" of dataframes `split_df` and `csv_df` and rename the columns from dataframes `split_df` and `csv_df` with suffix `_left` and `_right` respectively | [
"pandas"
] | [
{
"function": "pandas.merge",
"text": "pandas.merge pandas.merge(left, right, how='inner', on=None, left_on=None, right_on=None, left_index=False, right_index=False, sort=False, suffixes=('_x', '_y'), copy=True, indicator=False, validate=None)[source]\n \nMerge DataFrame or named Series objects with a database-style join. A named Series object is treated as a DataFrame with a single named column. The join is done on columns or indexes. If joining columns on columns, the DataFrame indexes will be ignored. Otherwise if joining indexes on indexes or indexes on a column or columns, the index will be passed on. When performing a cross merge, no column specifications to merge on are allowed. Warning If both key columns contain rows where the key is a null value, those rows will be matched against each other. This is different from usual SQL join behaviour and can lead to unexpected results. Parameters ",
"title": "pandas.reference.api.pandas.merge"
}
] |
|
10,697,757 | def f_10697757(s):
return | s.split(' ', 4) |
def check(candidate): | [
"\n assert candidate('1 0 A10B 100 Description: This is a description with spaces') == ['1', '0', 'A10B', '100', 'Description: This is a description with spaces']\n",
"\n assert candidate('this-is-a-continuous-sequence') == ['this-is-a-continuous-sequence']\n",
"\n assert candidate('') == ['']\n",
"\n assert candidate('\t') == ['\t']\n"
] | f_10697757 | Split a string `s` by space with `4` splits | [] | [] |
|
16,344,756 | def f_16344756(app):
return | app.run(debug=True) |
from flask import Flask
from unittest.mock import Mock
def check(candidate): | [
"\n Flask = Mock()\n app = Flask('mai')\n try:\n candidate(app)\n except:\n return False\n"
] | f_16344756 | enable debug mode on Flask application `app` | [
"flask"
] | [
{
"function": "app.run",
"text": "run(host=None, port=None, debug=None, load_dotenv=True, **options) \nRuns the application on a local development server. Do not use run() in a production setting. It is not intended to meet security and performance requirements for a production server. Instead, see Deployment Options for WSGI server recommendations. If the debug flag is set the server will automatically reload for code changes and show a debugger in case an exception happened. If you want to run the application in debug mode, but disable the code execution on the interactive debugger, you can pass use_evalex=False as parameter. This will keep the debugger’s traceback screen active, but disable code execution. It is not recommended to use this function for development with automatic reloading as this is badly supported. Instead you should be using the flask command line script’s run support. Keep in Mind Flask will suppress any server error with a generic error page unless it is in debug mode. As such to enable just the interactive debugger without the code reloading, you have to invoke run() with debug=True and use_reloader=False. Setting use_debugger to True without being in debug mode won’t catch any exceptions because there won’t be any to catch. Parameters \n \nhost (Optional[str]) – the hostname to listen on. Set this to '0.0.0.0' to have the server available externally as well. Defaults to '127.0.0.1' or the host in the SERVER_NAME config variable if present. \nport (Optional[int]) – the port of the webserver. Defaults to 5000 or the port defined in the SERVER_NAME config variable if present. \ndebug (Optional[bool]) – if given, enable or disable debug mode. See debug. \nload_dotenv (bool) – Load the nearest .env and .flaskenv files to set environment variables. Will also change the working directory to the directory containing the first file found. \noptions (Any) – the options to be forwarded to the underlying Werkzeug server. See werkzeug.serving.run_simple() for more information. Return type \nNone Changelog Changed in version 1.0: If installed, python-dotenv will be used to load environment variables from .env and .flaskenv files. If set, the FLASK_ENV and FLASK_DEBUG environment variables will override env and debug. Threaded mode is enabled by default. Changed in version 0.10: The default port is now picked from the SERVER_NAME variable.",
"title": "flask.api.index#flask.Flask.run"
}
] |
|
40,133,826 | def f_40133826(mylist):
|
return | pickle.dump(mylist, open('save.txt', 'wb')) |
import pickle
def check(candidate): | [
"\n candidate([i for i in range(10)])\n data = pickle.load(open('save.txt', 'rb'))\n assert data == [i for i in range(10)]\n",
"\n candidate([\"hello\", \"world\", \"!\"])\n data = pickle.load(open('save.txt', 'rb'))\n assert data == [\"hello\", \"world\", \"!\"]\n"
] | f_40133826 | python save list `mylist` to file object 'save.txt' | [
"pickle"
] | [
{
"function": "pickle.dump",
"text": "pickle.dump(obj, file, protocol=None, *, fix_imports=True, buffer_callback=None) \nWrite the pickled representation of the object obj to the open file object file. This is equivalent to Pickler(file, protocol).dump(obj). Arguments file, protocol, fix_imports and buffer_callback have the same meaning as in the Pickler constructor. Changed in version 3.8: The buffer_callback argument was added.",
"title": "python.library.pickle#pickle.dump"
}
] |
4,490,961 | def f_4490961(P, T):
return | scipy.tensordot(P, T, axes=[1, 1]).swapaxes(0, 1) |
import scipy
import numpy as np
def check(candidate): | [
"\n P = np.array([[6, 2, 7], [1, 1, 8], [8, 7, 1], [9, 6, 4], [2, 1, 1]])\n T = np.array([[[9, 7, 2, 3], [9, 6, 8, 2], [6, 6, 2, 8]],\n [[4, 5, 5, 3], [1, 8, 3, 5], [2, 8, 1, 6]]])\n result = np.array([[[114, 96, 42, 78], [ 66, 61, 26, 69], [141, 104, 74, 46], [159, 123, 74, 71], [ 33, 26, 14, 16]], \n [[ 40, 102, 43, 70], [ 21, 77, 16, 56], [ 41, 104, 62, 65], [ 50, 125, 67, 81], [ 11, 26, 14, 17]]])\n assert np.array_equal(candidate(P, T), result)\n"
] | f_4490961 | Multiply a matrix `P` with a 3d tensor `T` in scipy | [
"numpy",
"scipy"
] | [] |
|
2,173,087 | def f_2173087():
return | numpy.zeros((3, 3, 3)) |
import numpy
import numpy as np
def check(candidate): | [
"\n result = np.array([[[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]],\n [[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]],\n [[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]]])\n assert np.array_equal(candidate(), result)\n"
] | f_2173087 | Create 3d array of zeroes of size `(3,3,3)` | [
"numpy"
] | [
{
"function": "numpy.zeros",
"text": "numpy.zeros numpy.zeros(shape, dtype=float, order='C', *, like=None)\n \nReturn a new array of given shape and type, filled with zeros. Parameters ",
"title": "numpy.reference.generated.numpy.zeros"
}
] |
|
6,266,727 | def f_6266727(content):
return | """ """.join(content.split(' ')[:-1]) |
def check(candidate): | [
"\n assert candidate('test') == ''\n",
"\n assert candidate('this is an example content') == 'this is an example'\n",
"\n assert candidate(' ') == ' '\n",
"\n assert candidate('') == ''\n",
"\n assert candidate('blank and tab\t') == 'blank and'\n"
] | f_6266727 | cut off the last word of a sentence `content` | [] | [] |
|
30,385,151 | def f_30385151(x):
|
return x | x = np.asarray(x).reshape(1, -1)[(0), :] |
import numpy as np
def check(candidate): | [
"\n assert all(candidate(1.) == np.asarray(1.))\n",
"\n assert all(candidate(123) == np.asarray(123))\n",
"\n assert all(candidate('a') == np.asarray('a'))\n",
"\n assert all(candidate(False) == np.asarray(False))\n"
] | f_30385151 | convert scalar `x` to array | [
"numpy"
] | [
{
"function": "numpy.asarray",
"text": "numpy.asarray numpy.asarray(a, dtype=None, order=None, *, like=None)\n \nConvert the input to an array. Parameters ",
"title": "numpy.reference.generated.numpy.asarray"
},
{
"function": "numpy.reshape",
"text": "numpy.reshape numpy.reshape(a, newshape, order='C')[source]\n \nGives a new shape to an array without changing its data. Parameters ",
"title": "numpy.reference.generated.numpy.reshape"
}
] |
15,856,127 | def f_15856127(L):
return | sum(sum(i) if isinstance(i, list) else i for i in L) |
def check(candidate): | [
"\n assert candidate([1,2,3,4]) == 10\n",
"\n assert candidate([[1],[2],[3],[4]]) == 10\n",
"\n assert candidate([1,1,1,1]) == 4\n",
"\n assert candidate([1,[2,3],[4]]) == 10\n",
"\n assert candidate([]) == 0\n",
"\n assert candidate([[], []]) == 0\n"
] | f_15856127 | sum all elements of nested list `L` | [] | [] |
|
1,592,158 | def f_1592158():
return | struct.unpack('!f', bytes.fromhex('470FC614'))[0] |
import struct
def check(candidate): | [
"\n assert (candidate() - 36806.078125) < 1e-6\n",
"\n assert (candidate() - 32806.079125) > 1e-6\n"
] | f_1592158 | convert hex string '470FC614' to a float number | [
"struct"
] | [
{
"function": "struct.unpack",
"text": "struct.unpack(format, buffer) \nUnpack from the buffer buffer (presumably packed by pack(format, ...)) according to the format string format. The result is a tuple even if it contains exactly one item. The buffer’s size in bytes must match the size required by the format, as reflected by calcsize().",
"title": "python.library.struct#struct.unpack"
}
] |
|
5,010,536 | def f_5010536(my_dict):
|
return my_dict | my_dict.update((x, y * 2) for x, y in list(my_dict.items())) |
def check(candidate): | [
"\n assert candidate({'a': [1], 'b': 4.9}) == {'a': [1, 1], 'b': 9.8}\n",
"\n assert candidate({1:1}) == {1:2}\n",
"\n assert candidate({(1,2):[1]}) == {(1,2):[1,1]}\n",
"\n assert candidate({'asd':0}) == {'asd':0}\n",
"\n assert candidate({}) == {}\n"
] | f_5010536 | Multiple each value by `2` for all keys in a dictionary `my_dict` | [] | [] |
13,745,648 | def f_13745648():
return | subprocess.call('sleep.sh', shell=True) |
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_13745648 | running bash script 'sleep.sh' | [
"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"
}
] |
|
44,778 | def f_44778(l):
return | """,""".join(l) |
def check(candidate): | [
"\n assert candidate(['a','b','c']) == 'a,b,c'\n",
"\n assert candidate(['a','b']) == 'a,b'\n",
"\n assert candidate([',',',',',']) == ',,,,,'\n",
"\n assert candidate([' ',' ','c']) == ' , ,c'\n",
"\n assert candidate([]) == ''\n"
] | f_44778 | Join elements of list `l` with a comma `,` | [] | [] |
|
44,778 | def f_44778(myList):
|
return myList | myList = ','.join(map(str, myList)) |
def check(candidate): | [
"\n assert candidate([1,2,3]) == '1,2,3'\n",
"\n assert candidate([1,2,'a']) == '1,2,a'\n",
"\n assert candidate([]) == ''\n",
"\n assert candidate(['frg',3253]) == 'frg,3253'\n"
] | f_44778 | make a comma-separated string from a list `myList` | [] | [] |
7,286,365 | def f_7286365():
return | list(reversed(list(range(10)))) |
def check(candidate): | [
"\n assert candidate() == [9,8,7,6,5,4,3,2,1,0]\n",
"\n assert len(candidate()) == 10\n",
"\n assert min(candidate()) == 0\n",
"\n assert type(candidate()) == list\n",
"\n assert type(candidate()[-2]) == int\n"
] | f_7286365 | reverse the list that contains 1 to 10 | [] | [] |
|
18,454,570 | def f_18454570():
return | 'lamp, bag, mirror'.replace('bag,', '') |
def check(candidate): | [
"\n assert candidate() == 'lamp, mirror'\n assert type(candidate()) == str\n assert len(candidate()) == 13\n assert candidate().startswith('lamp')\n"
] | f_18454570 | remove substring 'bag,' from a string 'lamp, bag, mirror' | [] | [] |
|
4,357,787 | def f_4357787(s):
return | """.""".join(s.split('.')[::-1]) |
def check(candidate): | [
"\n assert candidate('apple.orange.red.green.yellow') == 'yellow.green.red.orange.apple'\n",
"\n assert candidate('apple') == 'apple'\n",
"\n assert candidate('apple.orange') == 'orange.apple'\n",
"\n assert candidate('123.456') == '456.123'\n",
"\n assert candidate('.') == '.'\n"
] | f_4357787 | Reverse the order of words, delimited by `.`, in string `s` | [] | [] |
|
21,787,496 | def f_21787496(s):
return | datetime.datetime.fromtimestamp(s).strftime('%Y-%m-%d %H:%M:%S.%f') |
import time
import datetime
def check(candidate): | [
"\n assert candidate(1236472) == '1970-01-15 07:27:52.000000'\n",
"\n assert candidate(0) == '1970-01-01 00:00:00.000000'\n",
"\n assert candidate(5.3) == '1970-01-01 00:00:05.300000'\n"
] | f_21787496 | convert epoch time represented as milliseconds `s` to string using format '%Y-%m-%d %H:%M:%S.%f' | [
"datetime",
"time"
] | [
{
"function": "datetime.fromtimestamp",
"text": "classmethod datetime.fromtimestamp(timestamp, tz=None) \nReturn the local date and time corresponding to the POSIX timestamp, such as is returned by time.time(). If optional argument tz is None or not specified, the timestamp is converted to the platform’s local date and time, and the returned datetime object is naive. If tz is not None, it must be an instance of a tzinfo subclass, and the timestamp is converted to tz’s time zone. fromtimestamp() may raise OverflowError, if the timestamp is out of the range of values supported by the platform C localtime() or gmtime() functions, and OSError on localtime() or gmtime() failure. It’s common for this to be restricted to years in 1970 through 2038. Note that on non-POSIX systems that include leap seconds in their notion of a timestamp, leap seconds are ignored by fromtimestamp(), and then it’s possible to have two timestamps differing by a second that yield identical datetime objects. This method is preferred over utcfromtimestamp(). Changed in version 3.3: Raise OverflowError instead of ValueError if the timestamp is out of the range of values supported by the platform C localtime() or gmtime() functions. Raise OSError instead of ValueError on localtime() or gmtime() failure. Changed in version 3.6: fromtimestamp() may return instances with fold set to 1.",
"title": "python.library.datetime#datetime.datetime.fromtimestamp"
},
{
"function": "datetime.strftime",
"text": "datetime.strftime(format) \nReturn a string representing the date and time, controlled by an explicit format string. For a complete list of formatting directives, see strftime() and strptime() Behavior.",
"title": "python.library.datetime#datetime.datetime.strftime"
}
] |
|
21,787,496 | def f_21787496():
return | time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(1236472051807 / 1000.0)) |
import time
def check(candidate): | [
"\n assert candidate() == '2009-03-08 00:27:31'\n"
] | f_21787496 | parse milliseconds epoch time '1236472051807' to format '%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"
}
] |
|
20,573,459 | def f_20573459():
return | (datetime.datetime.now() - datetime.timedelta(days=7)).date() |
import datetime
def check(candidate): | [
"\n assert datetime.datetime.now().date() - candidate() < datetime.timedelta(days = 7, seconds = 1)\n",
"\n assert datetime.datetime.now().date() - candidate() >= datetime.timedelta(days = 7)\n"
] | f_20573459 | get the date 7 days before the current date | [
"datetime"
] | [
{
"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"
},
{
"function": "datetime.timedelta",
"text": "class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0) \nAll arguments are optional and default to 0. Arguments may be integers or floats, and may be positive or negative. Only days, seconds and microseconds are stored internally. Arguments are converted to those units: A millisecond is converted to 1000 microseconds. A minute is converted to 60 seconds. An hour is converted to 3600 seconds. A week is converted to 7 days. and days, seconds and microseconds are then normalized so that the representation is unique, with 0 <= microseconds < 1000000 \n0 <= seconds < 3600*24 (the number of seconds in one day) -999999999 <= days <= 999999999 The following example illustrates how any arguments besides days, seconds and microseconds are “merged” and normalized into those three resulting attributes: >>> from datetime import timedelta",
"title": "python.library.datetime#datetime.timedelta"
}
] |
|
15,352,457 | def f_15352457(column, data):
return | sum(row[column] for row in data) |
def check(candidate): | [
"\n assert candidate(1, [[1,2,3], [4,5,6]]) == 7\n",
"\n assert candidate(0, [[1,1,1], [0,1,1]]) == 1\n",
"\n assert candidate(5, [[1,1,1,1,1,2], [0,1,1,1,1,1,1,1,1,1,1]]) == 3\n",
"\n assert candidate(0, [[1],[2],[3],[4]]) == 10\n"
] | f_15352457 | sum elements at index `column` of each list in list `data` | [] | [] |
|
15,352,457 | def f_15352457(array):
return | [sum(row[i] for row in array) for i in range(len(array[0]))] |
def check(candidate): | [
"\n assert candidate([[1,2,3], [4,5,6]]) == [5, 7, 9]\n",
"\n assert candidate([[1,1,1], [0,1,1]]) == [1, 2, 2]\n",
"\n assert candidate([[1,1,1,1,1,2], [0,1,1,1,1,1,1,1,1,1,1]]) == [1, 2, 2, 2, 2, 3]\n",
"\n assert candidate([[1],[2],[3],[4]]) == [10]\n"
] | f_15352457 | sum columns of a list `array` | [] | [] |
|
23,164,058 | def f_23164058():
return | base64.b64encode(bytes('your string', 'utf-8')) |
import base64
def check(candidate): | [
"\n assert candidate() == b'eW91ciBzdHJpbmc='\n"
] | f_23164058 | encode binary string 'your string' to base64 code | [
"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"
}
] |
|
11,533,274 | def f_11533274(dicts):
return | dict((k, [d[k] for d in dicts]) for k in dicts[0]) |
def check(candidate): | [
"\n assert candidate([{'cat': 1, 'dog': 3}, {'cat' : 2, 'dog': ['happy']}]) == {'cat': [1, 2], 'dog': [3, ['happy']]}\n",
"\n assert candidate([{'cat': 1}, {'cat' : 2}]) != {'cat': 3}\n"
] | f_11533274 | combine list of dictionaries `dicts` with the same keys in each list to a single dictionary | [] | [] |
|
11,533,274 | def f_11533274(dicts):
return | {k: [d[k] for d in dicts] for k in dicts[0]} |
def check(candidate): | [
"\n assert candidate([{'cat': 1, 'dog': 3}, {'cat' : 2, 'dog': ['happy']}]) == {'cat': [1, 2], 'dog': [3, ['happy']]}\n",
"\n assert candidate([{'cat': 1}, {'cat' : 2}]) != {'cat': 3}\n"
] | f_11533274 | Merge a nested dictionary `dicts` into a flat dictionary by concatenating nested values with the same key `k` | [] | [] |
|
14,026,704 | def f_14026704(request):
return | request.args['myParam'] |
import multidict
class Request:
def __init__(self, args):
self.args = args
def check(candidate): | [
"\n args = multidict.MultiDict([('myParam' , 'popeye')])\n request = Request(args)\n assert candidate(request) == 'popeye'\n"
] | f_14026704 | get the url parameter 'myParam' in a Flask view | [
"multidict"
] | [] |
|
11,236,006 | def f_11236006(mylist):
return | [k for k, v in list(Counter(mylist).items()) if v > 1] |
from collections import Counter
def check(candidate): | [
"\n assert candidate([1,3,2,2,1,4]) == [1, 2]\n",
"\n assert candidate([1,3,2,2,1,4]) != [3,4]\n",
"\n assert candidate([]) == []\n",
"\n assert candidate([1,1,1,1,1]) == [1]\n",
"\n assert candidate([1.,1.,1.]) == [1.]\n"
] | f_11236006 | identify duplicate values in list `mylist` | [
"collections"
] | [
{
"function": "collections.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"
}
] |
|
20,211,942 | def f_20211942(db):
return | db.execute("INSERT INTO present VALUES('test2', ?, 10)", (None,)) |
import sqlite3
def check(candidate): | [
"\n sqliteConnection = sqlite3.connect('dev.db')\n db = sqliteConnection.cursor()\n print(\"Database created and Successfully Connected to SQLite\")\n db.execute(\"CREATE TABLE present (name VARCHAR(5), age INTEGER, height INTEGER)\")\n try:\n candidate(db)\n except:\n assert False\n"
] | f_20211942 | Insert a 'None' value into a SQLite3 table. | [
"sqlite3"
] | [
{
"function": "db.execute",
"text": "execute(sql[, parameters]) \nThis is a nonstandard shortcut that creates a cursor object by calling the cursor() method, calls the cursor’s execute() method with the parameters given, and returns the cursor.",
"title": "python.library.sqlite3#sqlite3.Connection.execute"
}
] |
|
406,121 | def f_406121(list_of_menuitems):
return | [image for menuitem in list_of_menuitems for image in menuitem] |
from collections import Counter
def check(candidate): | [
"\n assert candidate([[1,2],[3,4,5]]) == [1,2,3,4,5]\n",
"\n assert candidate([[],[]]) == []\n",
"\n assert candidate([[1,1,1], []]) == [1,1,1]\n",
"\n assert candidate([['1'],['2']]) == ['1','2']\n"
] | f_406121 | flatten list `list_of_menuitems` | [
"collections"
] | [] |
|
4,741,537 | def f_4741537(a, b):
|
return a | a.extend(b) |
def check(candidate): | [
"\n assert candidate([1, 2, 2, 3], {4, 5, 2}) == [1, 2, 2, 3, 2, 4, 5]\n",
"\n assert candidate([], {4,5,2}) == [2,4,5]\n",
"\n assert candidate([1,2,3,4],{2}) == [1,2,3,4,2]\n",
"\n assert candidate([1], {'a'}) == [1, 'a']\n"
] | f_4741537 | append elements of a set `b` to a list `a` | [] | [] |
15,851,568 | def f_15851568(x):
return | x.rpartition('-')[0] |
def check(candidate): | [
"\n assert candidate('djhajhdjk-dadwqd-dahdjkahsk') == 'djhajhdjk-dadwqd'\n",
"\n assert candidate('/-/') == '/'\n",
"\n assert candidate('---') == '--'\n",
"\n assert candidate('') == ''\n"
] | f_15851568 | Split a string `x` by last occurrence of character `-` | [] | [] |
|
15,851,568 | def f_15851568(x):
return | x.rsplit('-', 1)[0] |
def check(candidate): | [
"\n assert candidate('2022-03-01') == '2022-03'\n",
"\n assert candidate('2020-2022') == '2020'\n"
] | f_15851568 | get the last part of a string before the character '-' | [] | [] |
|
17,438,096 | def f_17438096(filename, ftp):
|
return | ftp.storlines('STOR ' + filename, open(filename, 'r')) |
import ftplib
from unittest.mock import Mock
def check(candidate): | [
"\n ftplib.FTP = Mock()\n ftp = ftplib.FTP(\"10.10.10.10\")\n ftp.storlines = Mock()\n file_name = 'readme.txt'\n with open (file_name, 'a') as f:\n f.write('apple')\n candidate(file_name, ftp)\n"
] | f_17438096 | upload file using FTP | [
"ftplib"
] | [
{
"function": "ftp.storlines",
"text": "FTP.storlines(cmd, fp, callback=None) \nStore a file in line mode. cmd should be an appropriate STOR command (see storbinary()). Lines are read until EOF from the file object fp (opened in binary mode) using its readline() method to provide the data to be stored. callback is an optional single parameter callable that is called on each line after it is sent.",
"title": "python.library.ftplib#ftplib.FTP.storlines"
}
] |
28,742,436 | def f_28742436():
return | np.maximum([2, 3, 4], [1, 5, 2]) |
import numpy as np
def check(candidate): | [
"\n assert all(candidate() == np.array([2, 5, 4]))\n"
] | f_28742436 | create array containing the maximum value of respective elements of array `[2, 3, 4]` and array `[1, 5, 2]` | [
"numpy"
] | [
{
"function": "numpy.maximum",
"text": "numpy.maximum numpy.maximum(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'maximum'>\n \nElement-wise maximum of array elements. Compare two arrays and returns a new array containing the element-wise maxima. If one of the elements being compared is a NaN, then that element is returned. If both elements are NaNs then the first is returned. The latter distinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts being a NaN. The net effect is that NaNs are propagated. Parameters ",
"title": "numpy.reference.generated.numpy.maximum"
}
] |
|
34,280,147 | def f_34280147(l):
return | l[3:] + l[:3] |
def check(candidate): | [
"\n assert candidate(\"my-string\") == \"stringmy-\"\n",
"\n assert candidate(\"my \") == \"my \"\n",
"\n assert candidate(\"n;ho0-4w606[q\") == \"o0-4w606[qn;h\"\n"
] | f_34280147 | print a list `l` and move first 3 elements to the end of the list | [] | [] |
|
4,172,131 | def f_4172131():
return | [int(1000 * random.random()) for i in range(10000)] |
import random
def check(candidate): | [
"\n result = candidate()\n assert isinstance(result, list)\n assert all([isinstance(item, int) for item in result])\n"
] | f_4172131 | create a random list of integers | [
"random"
] | [
{
"function": "random.random",
"text": "random.random() \nReturn the next random floating point number in the range [0.0, 1.0).",
"title": "python.library.random#random.random"
}
] |
|
6,677,332 | def f_6677332():
return | datetime.datetime.now().strftime('%H:%M:%S.%f') |
import datetime
def check(candidate): | [
"\n time_now = datetime.datetime.now().strftime('%H:%M:%S.%f')\n assert candidate().split('.')[0] == time_now.split('.')[0]\n"
] | f_6677332 | Using %f with strftime() in Python to get microseconds | [
"datetime"
] | [
{
"function": "datetime.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"
},
{
"function": "datetime.strftime",
"text": "datetime.strftime(format) \nReturn a string representing the date and time, controlled by an explicit format string. For a complete list of formatting directives, see strftime() and strptime() Behavior.",
"title": "python.library.datetime#datetime.datetime.strftime"
}
] |
|
15,325,182 | def f_15325182(df):
return | df.b.str.contains('^f') |
import pandas as pd
def check(candidate): | [
"\n df = pd.DataFrame([[1, 'fat'], [2, 'hip'], [3, 'foo']], columns = ['a', 'b'])\n expected = [True, False, True]\n actual = candidate(df)\n for i in range (0, len(expected)):\n assert expected[i] == actual[i]\n"
] | f_15325182 | filter rows in pandas starting with alphabet 'f' using regular expression. | [
"pandas"
] | [
{
"function": "<ast.name object at 0x7f75ea4c9fc0>.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"
}
] |
|
583,557 | def f_583557(tab):
return | '\n'.join('\t'.join(str(col) for col in row) for row in tab) |
def check(candidate): | [
"\n assert candidate([[1,2,3],[4,5,6]]) == \"1\\t2\\t3\\n4\\t5\\t6\"\n",
"\n assert candidate([[1, 'x' ,3],[4.4,5,\"six\"]]) == \"1\\tx\\t3\\n4.4\\t5\\tsix\"\n",
"\n assert candidate([]) == \"\"\n",
"\n assert candidate([[],[],[]]) == \"\\n\\n\"\n"
] | f_583557 | print a 2 dimensional list `tab` as a table with delimiters | [] | [] |
|
38,535,931 | def f_38535931(df, tuples):
return | df.set_index(list('BC')).drop(tuples, errors='ignore').reset_index() |
import pandas as pd
def check(candidate): | [
"\n df = pd.DataFrame([[3, 4], [4, 5], [-1, -2]], columns = ['B', 'C'])\n tuples = [(3, 4), (-1, -2)]\n expected = pd.DataFrame([[4, 5]], columns = ['B', 'C'])\n actual = candidate(df, tuples)\n assert pd.DataFrame.equals(actual, expected)\n"
] | f_38535931 | pandas: delete rows in dataframe `df` based on multiple columns values | [
"pandas"
] | [
{
"function": "pandas.dataframe.set_index",
"text": "pandas.DataFrame.set_index DataFrame.set_index(keys, drop=True, append=False, inplace=False, verify_integrity=False)[source]\n \nSet the DataFrame index using existing columns. Set the DataFrame index (row labels) using one or more existing columns or arrays (of the correct length). The index can replace the existing index or expand on it. Parameters ",
"title": "pandas.reference.api.pandas.dataframe.set_index"
},
{
"function": "pandas.dataframe.drop",
"text": "pandas.DataFrame.drop DataFrame.drop(labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors='raise')[source]\n \nDrop specified labels from rows or columns. Remove rows or columns by specifying label names and corresponding axis, or by specifying directly index or column names. When using a multi-index, labels on different levels can be removed by specifying the level. See the user guide <advanced.shown_levels> for more information about the now unused levels. Parameters ",
"title": "pandas.reference.api.pandas.dataframe.drop"
},
{
"function": "pandas.dataframe.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"
}
] |
|
13,945,749 | def f_13945749(goals, penalties):
return | """({:d} goals, ${:d})""".format(goals, penalties) |
def check(candidate): | [
"\n assert candidate(0, 0) == \"(0 goals, $0)\"\n",
"\n assert candidate(123, 2) == \"(123 goals, $2)\"\n"
] | f_13945749 | format the variables `goals` and `penalties` using string formatting | [] | [] |
|
13,945,749 | def f_13945749(goals, penalties):
return | """({} goals, ${})""".format(goals, penalties) |
def check(candidate): | [
"\n assert candidate(0, 0) == \"(0 goals, $0)\"\n",
"\n assert candidate(123, \"???\") == \"(123 goals, $???)\"\n",
"\n assert candidate(\"x\", 0.0) == \"(x goals, $0.0)\"\n"
] | f_13945749 | format string "({} goals, ${})" with variables `goals` and `penalties` | [] | [] |
|
18,524,642 | def f_18524642(L):
return | [int(''.join(str(d) for d in x)) for x in L] |
def check(candidate): | [
"\n assert candidate([[1,2], [2,3,4], [1,0,0]]) == [12,234,100]\n",
"\n assert candidate([[1], [2], [3]]) == [1,2,3]\n"
] | f_18524642 | convert list of lists `L` to list of integers | [] | [] |
|
18,524,642 | def f_18524642(L):
|
return L | L = [int(''.join([str(y) for y in x])) for x in L] |
def check(candidate): | [
"\n assert candidate([[1,2], [2,3,4], [1,0,0]]) == [12,234,100]\n",
"\n assert candidate([[1], [2], [3]]) == [1,2,3]\n",
"\n assert candidate([[1, 0], [0, 2], [3], [0, 0, 0, 0]]) == [10,2,3, 0]\n"
] | f_18524642 | convert a list of lists `L` to list of integers | [] | [] |
7,138,686 | def f_7138686(lines, myfile):
|
return | myfile.write('\n'.join(lines)) |
def check(candidate): | [
"\n with open('tmp.txt', 'w') as myfile:\n candidate([\"first\", \"second\", \"third\"], myfile)\n with open('tmp.txt', 'r') as fr: \n lines = fr.readlines()\n assert lines == [\"first\\n\", \"second\\n\", \"third\"]\n"
] | f_7138686 | write the elements of list `lines` concatenated by special character '\n' to file `myfile` | [] | [] |
17,238,587 | def f_17238587(text):
|
return text | text = re.sub('\\b(\\w+)( \\1\\b)+', '\\1', text) |
import re
def check(candidate): | [
"\n assert candidate(\"text\") == \"text\"\n",
"\n assert candidate(\"text text\") == \"text\"\n",
"\n assert candidate(\"texttext\") == \"texttext\"\n",
"\n assert candidate(\"text and text\") == \"text and text\"\n"
] | f_17238587 | Remove duplicate words from a string `text` 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"
}
] |
26,053,849 | def f_26053849(df):
return | df.astype(bool).sum(axis=1) |
import pandas as pd
def check(candidate): | [
"\n df1 = pd.DataFrame([[0,0,0], [0,1,0], [1,1,1]])\n assert candidate(df1).to_list() == [0, 1, 3]\n",
"\n df2 = pd.DataFrame([[0,0,0], [0,2,0], [1,10,8.9]])\n assert candidate(df1).to_list() == [0, 1, 3]\n",
"\n df2 = pd.DataFrame([[0,0.0,0], [0,2.0,0], [1,10,8.9]])\n assert candidate(df1).to_list() == [0, 1, 3]\n",
"\n df = df = pd.DataFrame([[4, 0, 0], [1, 0, 1]])\n expected = [1, 2]\n actual = candidate(df)\n for i in range(0, len(expected)):\n assert expected[i] == actual[i]\n"
] | f_26053849 | count non zero values in each column in pandas data frame `df` | [
"pandas"
] | [
{
"function": "pandas.dataframe.astype",
"text": "pandas.DataFrame.astype DataFrame.astype(dtype, copy=True, errors='raise')[source]\n \nCast a pandas object to a specified dtype dtype. Parameters ",
"title": "pandas.reference.api.pandas.dataframe.astype"
},
{
"function": "pandas.dataframe.sum",
"text": "pandas.DataFrame.sum DataFrame.sum(axis=None, skipna=True, level=None, numeric_only=None, min_count=0, **kwargs)[source]\n \nReturn the sum of the values over the requested axis. This is equivalent to the method numpy.sum. Parameters ",
"title": "pandas.reference.api.pandas.dataframe.sum"
}
] |
|
15,534,223 | def f_15534223():
return | re.search('(?<!Distillr)\\\\AcroTray\\.exe', 'C:\\SomeDir\\AcroTray.exe') |
import re
def check(candidate): | [
"\n result = candidate()\n assert result.span() == (10, 23)\n assert result.string == \"C:\\SomeDir\\AcroTray.exe\"\n"
] | f_15534223 | search for string that matches regular expression pattern '(?<!Distillr)\\\\AcroTray\\.exe' in string 'C:\\SomeDir\\AcroTray.exe' | [
"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"
}
] |
|
5,453,026 | def f_5453026():
return | """QH QD JC KD JS""".split() |
def check(candidate): | [
"\n assert candidate() == [\"QH\", \"QD\", \"JC\", \"KD\", \"JS\"]\n"
] | f_5453026 | split string 'QH QD JC KD JS' into a list on white spaces | [] | [] |
|
18,168,684 | def f_18168684(line):
return | re.search('>.*<', line).group(0) |
import re
def check(candidate): | [
"\n assert candidate(\"hahhdsf>0.0<;sgnd\") == \">0.0<\"\n",
"\n assert candidate(\"hahhdsf>2.34<;xbnfm\") == \">2.34<\"\n"
] | f_18168684 | search for occurrences of regex pattern '>.*<' in xml string `line` | [
"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"
}
] |
|
4,914,277 | def f_4914277(filename):
return | open(filename, 'w').close() |
def check(candidate): | [
"\n filename = 'tmp.txt'\n with open(filename, 'w') as fw: fw.write(\"hello world!\")\n with open(filename, 'r') as fr: \n lines = fr.readlines()\n assert len(lines) == 1 and lines[0] == \"hello world!\"\n candidate(filename)\n with open(filename, 'r') as fr: \n lines = fr.readlines()\n assert len(lines) == 0\n"
] | f_4914277 | erase all the contents of a file `filename` | [] | [] |
|
19,068,269 | def f_19068269(string_date):
return | datetime.datetime.strptime(string_date, '%Y-%m-%d %H:%M:%S.%f') |
import datetime
def check(candidate): | [
"\n assert candidate('2022-10-22 11:59:59.20') == datetime.datetime(2022, 10, 22, 11, 59, 59, 200000)\n",
"\n assert candidate('2000-01-01 11:59:59.20') == datetime.datetime(2000, 1, 1, 11, 59, 59, 200000)\n",
"\n assert candidate('1990-09-09 09:59:59.24') == datetime.datetime(1990, 9, 9, 9, 59, 59, 240000)\n",
"\n d = candidate('2022-12-14 07:06:00.25')\n assert d == datetime.datetime(2022, 12, 14, 7, 6, 0, 250000)\n"
] | f_19068269 | convert a string `string_date` into datetime using the format '%Y-%m-%d %H:%M:%S.%f' | [
"datetime"
] | [
{
"function": "datetime.strptime",
"text": "classmethod datetime.strptime(date_string, format) \nReturn a datetime corresponding to date_string, parsed according to format. This is equivalent to: datetime(*(time.strptime(date_string, format)[0:6]))\n ValueError is raised if the date_string and format can’t be parsed by time.strptime() or if it returns a value which isn’t a time tuple. For a complete list of formatting directives, see strftime() and strptime() Behavior.",
"title": "python.library.datetime#datetime.datetime.strptime"
}
] |
|
20,683,167 | def f_20683167(thelist):
return | [index for index, item in enumerate(thelist) if item[0] == '332'] |
def check(candidate): | [
"\n assert candidate([[0,1,2], ['a','bb','ccc'], ['332',33,2], [33,22,332]]) == [2]\n",
"\n assert candidate([[0,1,2], ['332'], ['332'], ['332']]) == [1,2,3]\n",
"\n assert candidate([[0,1,2], [332], [332], [332]]) == []\n"
] | f_20683167 | find the index of a list with the first element equal to '332' within the list of lists `thelist` | [] | [] |
|
30,693,804 | def f_30693804(text):
return | re.sub('[^\\sa-zA-Z0-9]', '', text).lower().strip() |
import re
def check(candidate): | [
"\n assert candidate('ABjfK329r0&&*#5t') == 'abjfk329r05t'\n",
"\n assert candidate('jseguwphegoi339yup h') == 'jseguwphegoi339yup h'\n",
"\n assert candidate(' ') == ''\n"
] | f_30693804 | lower a string `text` and remove non-alphanumeric characters aside from space | [
"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"
}
] |
|
30,693,804 | def f_30693804(text):
return | re.sub('(?!\\s)[\\W_]', '', text).lower().strip() |
import re
def check(candidate): | [
"\n assert candidate('ABjfK329r0&&*#5t') == 'abjfk329r05t'\n",
"\n assert candidate('jseguwphegoi339yup h') == 'jseguwphegoi339yup h'\n",
"\n assert candidate(' ') == ''\n"
] | f_30693804 | remove all non-alphanumeric characters except space from a string `text` and lower it | [
"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"
}
] |
|
17,138,464 | def f_17138464(x, y):
return | plt.plot(x, y, label='H\u2082O') |
import numpy as np
import matplotlib.pyplot as plt
def check(candidate): | [
"\n pic = candidate(np.array([1,2,3]),np.array([4,5,6]))[0]\n assert pic.get_label() == 'H₂O'\n x, y = pic.get_data()\n assert all(x == np.array([1,2,3]))\n assert all(y == np.array([4,5,6]))\n",
"\n pic = candidate(np.array([6, 7, 899]),np.array([0, 1, 245]))[0]\n assert pic.get_label() == 'H₂O'\n x, y = pic.get_data()\n assert all(x == np.array([6, 7, 899]))\n assert all(y == np.array([0, 1, 245]))\n"
] | f_17138464 | subscript text 'H20' with '2' as subscripted in matplotlib labels for arrays 'x' and 'y'. | [
"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"
}
] |
|
17,138,464 | def f_17138464(x, y):
return | plt.plot(x, y, label='$H_2O$') |
import numpy as np
import matplotlib.pyplot as plt
def check(candidate): | [
"\n pic = candidate(np.array([1,2,3]),np.array([4,5,6]))[0]\n assert pic.get_label() == '$H_2O$'\n x, y = pic.get_data()\n assert all(x == np.array([1,2,3]))\n assert all(y == np.array([4,5,6]))\n",
"\n pic = candidate(np.array([6, 7, 899]),np.array([0, 1, 245]))[0]\n assert pic.get_label() == '$H_2O$'\n x, y = pic.get_data()\n assert all(x == np.array([6, 7, 899]))\n assert all(y == np.array([0, 1, 245]))\n"
] | f_17138464 | subscript text 'H20' with '2' as subscripted in matplotlib labels for arrays 'x' and 'y'. | [
"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"
}
] |
|
9,138,112 | def f_9138112(mylist):
return | [x for x in mylist if len(x) == 3] |
def check(candidate): | [
"\n assert candidate([[1,2,3], 'abc', [345,53], 'avsvasf']) == [[1,2,3], 'abc']\n",
"\n assert candidate([[435,654.4,45,2],[34,34,757,65,32423]]) == []\n"
] | f_9138112 | loop over a list `mylist` if sublists length equals 3 | [] | [] |
|
1,807,026 | def f_1807026():
|
return lst | lst = [Object() for _ in range(100)] |
class Object():
def __init__(self):
self.name = "object"
def check(candidate): | [
"\n lst = candidate()\n assert all([x.name == \"object\" for x in lst])\n"
] | f_1807026 | initialize a list `lst` of 100 objects Object() | [] | [] |
13,793,321 | def f_13793321(df1, df2):
return | df1.merge(df2, on='Date_Time') |
import pandas as pd
def check(candidate): | [
"\n df1 = pd.DataFrame([[1, 2, 3]], columns=[\"Date\", \"Time\", \"Date_Time\"])\n df2 = pd.DataFrame([[1, 3],[4, 9]], columns=[\"Name\", \"Date_Time\"])\n assert candidate(df1, df2).to_dict() == {'Date': {0: 1}, 'Time': {0: 2}, 'Date_Time': {0: 3}, 'Name': {0: 1}}\n"
] | f_13793321 | joining data from dataframe `df1` with data from dataframe `df2` based on matching values of column 'Date_Time' in both dataframes | [
"pandas"
] | [
{
"function": "df1.merge",
"text": "pandas.DataFrame.merge DataFrame.merge(right, how='inner', on=None, left_on=None, right_on=None, left_index=False, right_index=False, sort=False, suffixes=('_x', '_y'), copy=True, indicator=False, validate=None)[source]\n \nMerge DataFrame or named Series objects with a database-style join. A named Series object is treated as a DataFrame with a single named column. The join is done on columns or indexes. If joining columns on columns, the DataFrame indexes will be ignored. Otherwise if joining indexes on indexes or indexes on a column or columns, the index will be passed on. When performing a cross merge, no column specifications to merge on are allowed. Warning If both key columns contain rows where the key is a null value, those rows will be matched against each other. This is different from usual SQL join behaviour and can lead to unexpected results. Parameters ",
"title": "pandas.reference.api.pandas.dataframe.merge"
}
] |
|
3,367,288 | def f_3367288(str1):
return | 'first string is: %s, second one is: %s' % (str1, 'geo.tif') |
def check(candidate): | [
"\n assert candidate(\"s001\") == \"first string is: s001, second one is: geo.tif\"\n",
"\n assert candidate(\"\") == \"first string is: , second one is: geo.tif\"\n",
"\n assert candidate(\" \") == \"first string is: , second one is: geo.tif\"\n"
] | f_3367288 | use `%s` operator to print variable values `str1` inside a string | [] | [] |
|
3,475,251 | def f_3475251():
return | [x.strip() for x in '2.MATCHES $$TEXT$$ STRING'.split('$$TEXT$$')] |
def check(candidate): | [
"\n assert candidate() == ['2.MATCHES', 'STRING']\n"
] | f_3475251 | Split a string '2.MATCHES $$TEXT$$ STRING' by a delimiter '$$TEXT$$' | [] | [] |
|
273,192 | def f_273192(directory):
|
return | if (not os.path.exists(directory)):
os.makedirs(directory) |
import os
def check(candidate): | [
"\n candidate(\"hello\")\n assert os.path.exists(\"hello\")\n",
"\n candidate(\"_some_dir\")\n assert os.path.exists(\"_some_dir\")\n"
] | f_273192 | check if directory `directory ` exists and create it if necessary | [
"os"
] | [
{
"function": "os.exists",
"text": "os.path.exists(path) \nReturn True if path refers to an existing path or an open file descriptor. Returns False for broken symbolic links. On some platforms, this function may return False if permission is not granted to execute os.stat() on the requested file, even if the path physically exists. Changed in version 3.3: path can now be an integer: True is returned if it is an open file descriptor, False otherwise. Changed in version 3.6: Accepts a path-like object.",
"title": "python.library.os.path#os.path.exists"
},
{
"function": "os.makedirs",
"text": "os.makedirs(name, mode=0o777, exist_ok=False) \nRecursive directory creation function. Like mkdir(), but makes all intermediate-level directories needed to contain the leaf directory. The mode parameter is passed to mkdir() for creating the leaf directory; see the mkdir() description for how it is interpreted. To set the file permission bits of any newly-created parent directories you can set the umask before invoking makedirs(). The file permission bits of existing parent directories are not changed. If exist_ok is False (the default), an FileExistsError is raised if the target directory already exists. Note makedirs() will become confused if the path elements to create include pardir (eg. “..” on UNIX systems). This function handles UNC paths correctly. Raises an auditing event os.mkdir with arguments path, mode, dir_fd. New in version 3.2: The exist_ok parameter. Changed in version 3.4.1: Before Python 3.4.1, if exist_ok was True and the directory existed, makedirs() would still raise an error if mode did not match the mode of the existing directory. Since this behavior was impossible to implement safely, it was removed in Python 3.4.1. See bpo-21082. Changed in version 3.6: Accepts a path-like object. Changed in version 3.7: The mode argument no longer affects the file permission bits of newly-created intermediate-level directories.",
"title": "python.library.os#os.makedirs"
}
] |
273,192 | def f_273192(path):
|
return | try:
os.makedirs(path)
except OSError:
if (not os.path.isdir(path)):
raise |
import os
def check(candidate): | [
"\n candidate(\"hello\")\n assert os.path.exists(\"hello\")\n",
"\n candidate(\"_some_dir\")\n assert os.path.exists(\"_some_dir\")\n"
] | f_273192 | check if a directory `path` exists and create it if necessary | [
"os"
] | [
{
"function": "os.isdir",
"text": "os.path.isdir(path) \nReturn True if path is an existing directory. This follows symbolic links, so both islink() and isdir() can be true for the same path. Changed in version 3.6: Accepts a path-like object.",
"title": "python.library.os.path#os.path.isdir"
},
{
"function": "os.makedirs",
"text": "os.makedirs(name, mode=0o777, exist_ok=False) \nRecursive directory creation function. Like mkdir(), but makes all intermediate-level directories needed to contain the leaf directory. The mode parameter is passed to mkdir() for creating the leaf directory; see the mkdir() description for how it is interpreted. To set the file permission bits of any newly-created parent directories you can set the umask before invoking makedirs(). The file permission bits of existing parent directories are not changed. If exist_ok is False (the default), an FileExistsError is raised if the target directory already exists. Note makedirs() will become confused if the path elements to create include pardir (eg. “..” on UNIX systems). This function handles UNC paths correctly. Raises an auditing event os.mkdir with arguments path, mode, dir_fd. New in version 3.2: The exist_ok parameter. Changed in version 3.4.1: Before Python 3.4.1, if exist_ok was True and the directory existed, makedirs() would still raise an error if mode did not match the mode of the existing directory. Since this behavior was impossible to implement safely, it was removed in Python 3.4.1. See bpo-21082. Changed in version 3.6: Accepts a path-like object. Changed in version 3.7: The mode argument no longer affects the file permission bits of newly-created intermediate-level directories.",
"title": "python.library.os#os.makedirs"
}
] |
273,192 | def f_273192(path):
|
return | try:
os.makedirs(path)
except OSError as exception:
if (exception.errno != errno.EEXIST):
raise |
import os
def check(candidate): | [
"\n candidate(\"hello\")\n assert os.path.exists(\"hello\")\n",
"\n candidate(\"_some_dir\")\n assert os.path.exists(\"_some_dir\")\n"
] | f_273192 | check if a directory `path` exists and create it if necessary | [
"os"
] | [
{
"function": "os.makedirs",
"text": "os.makedirs(name, mode=0o777, exist_ok=False) \nRecursive directory creation function. Like mkdir(), but makes all intermediate-level directories needed to contain the leaf directory. The mode parameter is passed to mkdir() for creating the leaf directory; see the mkdir() description for how it is interpreted. To set the file permission bits of any newly-created parent directories you can set the umask before invoking makedirs(). The file permission bits of existing parent directories are not changed. If exist_ok is False (the default), an FileExistsError is raised if the target directory already exists. Note makedirs() will become confused if the path elements to create include pardir (eg. “..” on UNIX systems). This function handles UNC paths correctly. Raises an auditing event os.mkdir with arguments path, mode, dir_fd. New in version 3.2: The exist_ok parameter. Changed in version 3.4.1: Before Python 3.4.1, if exist_ok was True and the directory existed, makedirs() would still raise an error if mode did not match the mode of the existing directory. Since this behavior was impossible to implement safely, it was removed in Python 3.4.1. See bpo-21082. Changed in version 3.6: Accepts a path-like object. Changed in version 3.7: The mode argument no longer affects the file permission bits of newly-created intermediate-level directories.",
"title": "python.library.os#os.makedirs"
}
] |
18,785,032 | def f_18785032(text):
return | re.sub('\\bH3\\b', 'H1', text) |
import re
def check(candidate): | [
"\n assert candidate(\"hello world and H3\") == \"hello world and H1\"\n",
"\n assert candidate(\"hello world and H1\") == \"hello world and H1\"\n",
"\n assert candidate(\"hello world!\") == \"hello world!\"\n"
] | f_18785032 | Replace a separate word 'H3' by 'H1' in a 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"
}
] |
|
1,450,897 | def f_1450897():
return | re.sub('\\D', '', 'aas30dsa20') |
import re
def check(candidate): | [
"\n assert candidate() == \"3020\"\n"
] | f_1450897 | substitute ASCII letters in string 'aas30dsa20' with empty string '' | [
"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,450,897 | def f_1450897():
return | """""".join([x for x in 'aas30dsa20' if x.isdigit()]) |
def check(candidate): | [
"\n assert candidate() == \"3020\"\n"
] | f_1450897 | get digits only from a string `aas30dsa20` using lambda function | [] | [] |
|
14,435,268 | def f_14435268(soup):
return | soup.find('name').string |
from bs4 import BeautifulSoup
def check(candidate): | [
"\n content = \"<contact><name>LastName</name><lastName>FirstName</lastName><phone>+90 333 12345</phone></contact>\"\n soup = BeautifulSoup(content)\n assert candidate(soup) == \"LastName\"\n",
"\n content = \"<name>hello world!</name>\"\n soup = BeautifulSoup(content)\n assert candidate(soup) == \"hello world!\"\n"
] | f_14435268 | access a tag called "name" in beautifulsoup `soup` | [
"bs4"
] | [] |
|
20,180,210 | def f_20180210(A, B):
return | np.concatenate((A, B)) |
import numpy as np
def check(candidate): | [
"\n A = np.array([1,2])\n B = np.array([3,4])\n assert np.allclose(candidate(A, B), np.array([1,2,3,4]))\n",
"\n A = np.array([[1,2]])\n B = np.array([[3,4]])\n assert np.allclose(candidate(A, B), np.array([[1,2],[3,4]]))\n",
"\n A = np.array([[1],[2]])\n B = np.array([[3],[4]])\n assert np.allclose(candidate(A, B), np.array([[1],[2],[3],[4]]))\n",
"\n a = np.array([[1, 3, 4], [4, 5, 6], [6, 0, -1]])\n b = np.array([[5, 6, 1], [0, 2, -1], [9, 4, 1]])\n expected = np.array([[ 1, 3, 4], [ 4, 5, 6],\n [ 6, 0, -1], [ 5, 6, 1], [ 0, 2, -1], [ 9, 4, 1]])\n assert np.array_equal(candidate(a, b), expected)\n"
] | f_20180210 | Create new matrix object by concatenating data from matrix A and matrix B | [
"numpy"
] | [
{
"function": "numpy.concatenate",
"text": "numpy.concatenate numpy.concatenate((a1, a2, ...), axis=0, out=None, dtype=None, casting=\"same_kind\")\n \nJoin a sequence of arrays along an existing axis. Parameters ",
"title": "numpy.reference.generated.numpy.concatenate"
}
] |
|
20,180,210 | def f_20180210(A, B):
return | np.vstack((A, B)) |
import numpy as np
def check(candidate): | [
"\n A = np.array([1,2])\n B = np.array([3,4])\n assert np.allclose(candidate(A, B), np.array([[1,2],[3,4]]))\n",
"\n A = np.array([[1,2]])\n B = np.array([[3,4]])\n assert np.allclose(candidate(A, B), np.array([[1,2],[3,4]]))\n",
"\n A = np.array([[1],[2]])\n B = np.array([[3],[4]])\n assert np.allclose(candidate(A, B), np.array([[1],[2],[3],[4]]))\n",
"\n a = np.array([[1, 3, 4], [4, 5, 6], [6, 0, -1]])\n b = np.array([[5, 6, 1], [0, 2, -1], [9, 4, 1]])\n expected = np.array([[ 1, 3, 4], [ 4, 5, 6],\n [ 6, 0, -1], [ 5, 6, 1], [ 0, 2, -1], [ 9, 4, 1]])\n assert np.array_equal(candidate(a, b), expected)\n"
] | f_20180210 | concat two matrices `A` and `B` in numpy | [
"numpy"
] | [
{
"function": "numpy.vstack",
"text": "numpy.vstack numpy.vstack(tup)[source]\n \nStack arrays in sequence vertically (row wise). This is equivalent to concatenation along the first axis after 1-D arrays of shape (N,) have been reshaped to (1,N). Rebuilds arrays divided by vsplit. This function makes most sense for arrays with up to 3 dimensions. For instance, for pixel-data with a height (first axis), width (second axis), and r/g/b channels (third axis). The functions concatenate, stack and block provide more general stacking and concatenation operations. Parameters ",
"title": "numpy.reference.generated.numpy.vstack"
}
] |
ODEX dataset annotated with the ground-truth library documentation, to enable evaluations for retrieval and retrieval-augmented code generation.
Please refer to [code-rag-bench] for more details.