task_id
int64
19.3k
41.9M
prompt
stringlengths
17
68
suffix
stringlengths
0
22
canonical_solution
stringlengths
6
153
test_start
stringlengths
22
198
test
sequence
entry_point
stringlengths
7
10
intent
stringlengths
19
200
library
sequence
638,048
def f_638048(list_of_pairs): return
sum([pair[0] for pair in list_of_pairs])
def check(candidate):
[ "\n assert candidate([(5, 9), (-1, -2), (4, 2)]) == 8\n" ]
f_638048
sum the first value in each tuple in a list of tuples `list_of_pairs` in python
[]
14,950,260
def f_14950260(): return
ast.literal_eval("{'code1':1,'code2':1}")
import ast def check(candidate):
[ "\n d = candidate()\n exp_result = {'code1' : 1, 'code2': 1}\n for key in d:\n if key not in exp_result:\n assert False\n else:\n assert d[key] == exp_result[key]\n" ]
f_14950260
convert unicode string u"{'code1':1,'code2':1}" into dictionary
[ "ast" ]
11,416,772
def f_11416772(mystring): return
[word for word in mystring.split() if word.startswith('$')]
def check(candidate):
[ "\n str = \"$abc def $efg $hij klm $\"\n exp_result = ['$abc', '$efg', '$hij', '$']\n assert sorted(candidate(str)) == sorted(exp_result)\n" ]
f_11416772
find all words in a string `mystring` that start with the `$` sign
[]
11,331,982
def f_11331982(text):
return text
text = re.sub('^https?:\\/\\/.*[\\r\\n]*', '', text, flags=re.MULTILINE)
import re def check(candidate):
[ "\n assert candidate(\"https://www.wikipedia.org/ click at\") == \"\"\n" ]
f_11331982
remove any url within string `text`
[ "re" ]
34,945,274
def f_34945274(A): return
np.where(np.in1d(A, [1, 3, 4]).reshape(A.shape), A, 0)
import numpy as np def check(candidate):
[ "\n A = np.array([[6, 8, 1, 3, 4], [-1, 0, 3, 5, 1]])\n B = np.array([[0, 0, 1, 3, 4], [0, 0, 3, 0, 1]])\n assert np.array_equal(candidate(A), B)\n" ]
f_34945274
replace all elements in array `A` that are not present in array `[1, 3, 4]` with zeros
[ "numpy" ]
15,819,980
def f_15819980(a): return
np.mean(a, axis=1)
import numpy as np def check(candidate):
[ "\n A = np.array([[6, 8, 1, 3, 4], [-1, 0, 3, 5, 1]])\n B = np.array([4.4, 1.6])\n assert np.array_equal(candidate(A), B)\n" ]
f_15819980
calculate mean across dimension in a 2d array `a`
[ "numpy" ]
19,894,365
def f_19894365(): return
subprocess.call(['/usr/bin/Rscript', '--vanilla', '/pathto/MyrScript.r'])
from unittest.mock import Mock import subprocess def check(candidate):
[ "\n subprocess.call = Mock(return_value = 0)\n assert candidate() == 0\n" ]
f_19894365
running r script '/pathto/MyrScript.r' from python
[ "subprocess" ]
19,894,365
def f_19894365(): return
subprocess.call('/usr/bin/Rscript --vanilla /pathto/MyrScript.r', shell=True)
from unittest.mock import Mock import subprocess def check(candidate):
[ "\n subprocess.call = Mock(return_value = 0)\n assert candidate() == 0\n" ]
f_19894365
run r script '/usr/bin/Rscript --vanilla /pathto/MyrScript.r'
[ "subprocess" ]
33,058,590
def f_33058590(df): return
df.fillna(df.mean(axis=0))
import pandas as pd import numpy as np def check(candidate):
[ "\n df = pd.DataFrame([[1,2,3],[4,5,6],[7.0,np.nan,9.0]], columns=[\"c1\",\"c2\",\"c3\"]) \n res = pd.DataFrame([[1,2,3],[4,5,6],[7.0,3.5,9.0]], columns=[\"c1\",\"c2\",\"c3\"])\n assert candidate(df).equals(res)\n" ]
f_33058590
replacing nan in the dataframe `df` with row average
[ "numpy", "pandas" ]
12,400,256
def f_12400256(): return
time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1347517370))
import time def check(candidate):
[ "\n assert candidate() == \"2012-09-13 06:22:50\"\n" ]
f_12400256
Convert unix timestamp '1347517370' to formatted string '%Y-%m-%d %H:%M:%S'
[ "time" ]
23,359,886
def f_23359886(a): return
a[np.where((a[:, (0)] == 0) * (a[:, (1)] == 1))]
import numpy as np def check(candidate):
[ "\n a = np.array([[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8], [ 9, 10, 11], [12, 13, 14]])\n res = np.array([[0, 1, 2]])\n assert np.array_equal(candidate(a), res)\n" ]
f_23359886
selecting rows in Numpy ndarray 'a', where the value in the first column is 0 and value in the second column is 1
[ "numpy" ]
4,383,082
def f_4383082(words): return
re.split(' +', words)
import regex as re def check(candidate):
[ "\n s = \"hello world sample text\"\n res = [\"hello\", \"world\", \"sample\", \"text\"]\n assert candidate(s) == res\n" ]
f_4383082
separate words delimited by one or more spaces into a list
[ "regex" ]
14,637,696
def f_14637696(words): return
len(max(words, key=len))
def check(candidate):
[ "\n assert candidate([\"hello\", \"world\", \"sample\", \"text\", \"superballer\"]) == 11\n" ]
f_14637696
length of longest element in list `words`
[]
3,933,478
def f_3933478(result): return
result[0]['from_user']
def check(candidate):
[ "\n Contents = [{\"hi\": 7, \"bye\": 4, \"from_user\": 0}, {1: 2, 3: 4, 5: 6}]\n assert candidate(Contents) == 0\n" ]
f_3933478
get the value associated with unicode key 'from_user' of first dictionary in list `result`
[]
39,112,645
def f_39112645(): return
[line.split() for line in open('File.txt')]
def check(candidate):
[ "\n with open('File.txt','w') as fw:\n fw.write(\"hi hello cat dog\")\n assert candidate() == [['hi', 'hello', 'cat', 'dog']]\n" ]
f_39112645
Retrieve each line from a file 'File.txt' as a list
[]
1,031,851
def f_1031851(a): return
dict((v, k) for k, v in a.items())
def check(candidate):
[ "\n a = {\"one\": 1, \"two\": 2}\n assert candidate(a) == {1: \"one\", 2: \"two\"}\n" ]
f_1031851
swap keys with values in a dictionary `a`
[]
8,577,137
def f_8577137(): return
open('path/to/FILE_NAME.ext', 'w')
import os def check(candidate):
[ "\n path1 = os.path.join(\"\", \"path\")\n os.mkdir(path1)\n path2 = os.path.join(\"path\", \"to\")\n os.mkdir(path2)\n candidate()\n assert os.path.exists('path/to/FILE_NAME.ext')\n" ]
f_8577137
Open a file `path/to/FILE_NAME.ext` in write mode
[ "os" ]
17,926,273
def f_17926273(df): return
df.groupby(['col1', 'col2'])['col3'].nunique().reset_index()
import pandas as pd def check(candidate):
[ "\n data = [[1, 1, 1], [1, 1, 1], [1, 1, 2], [1, 2, 3], [1, 2, 3], [1, 2, 3], \n [2, 1, 1], [2, 1, 2], [2, 1, 3], [2, 2, 3], [2, 2, 3], [2, 2, 3]]\n expected = [[1, 1, 2], [1, 2, 1], [2, 1, 3], [2, 2, 1]]\n df = pd.DataFrame(data, columns = ['col1', 'col2', 'col3'])\n expected_df = pd.DataFrame(expected, columns = ['col1', 'col2', 'col3'])\n df1 = candidate(df)\n assert pd.DataFrame.equals(expected_df, df1)\n" ]
f_17926273
count distinct values in a column 'col3' of a pandas dataframe `df` group by objects in 'col1' and 'col2'
[ "pandas" ]
3,735,814
def f_3735814(dict1): return
any(key.startswith('EMP$$') for key in dict1)
def check(candidate):
[ "\n assert candidate({'EMP$$': 1, 'EMP$$112': 4}) == True\n", "\n assert candidate({'EMP$$': 1, 'EM$$112': 4}) == True\n", "\n assert candidate({'EMP$33': 0}) == False\n" ]
f_3735814
Check if any key in the dictionary `dict1` starts with the string `EMP$$`
[]
3,735,814
def f_3735814(dict1): return
[value for key, value in list(dict1.items()) if key.startswith('EMP$$')]
def check(candidate):
[ "\n assert sorted(candidate({'EMP$$': 1, 'EMP$$112': 4})) == [1, 4]\n", "\n assert sorted(candidate({'EMP$$': 1, 'EM$$112': 4})) == [1]\n", "\n assert sorted(candidate({'EMP$33': 0})) == []\n" ]
f_3735814
create list of values from dictionary `dict1` that have a key that starts with 'EMP$$'
[]
26,097,916
def f_26097916(sf):
return df
df = pd.DataFrame({'email': sf.index, 'list': sf.values})
import pandas as pd def check(candidate):
[ "\n dict = {'email1': [1.0, 5.0, 7.0], 'email2': [4.2, 3.6, -0.9]}\n sf = pd.Series(dict)\n k = [['email1', [1.0, 5.0, 7.0]], ['email2', [4.2, 3.6, -0.9]]]\n df1 = pd.DataFrame(k, columns=['email', 'list'])\n df2 = candidate(sf)\n assert pd.DataFrame.equals(df1, df2)\n" ]
f_26097916
convert a pandas series `sf` into a pandas dataframe `df` with columns `email` and `list`
[ "pandas" ]
4,048,964
def f_4048964(list): return
'\t'.join(map(str, list))
def check(candidate):
[ "\n assert candidate(['hello', 'world', '!']) == 'hello\\tworld\\t!'\n", "\n assert candidate([]) == \"\"\n", "\n assert candidate([\"mconala\"]) == \"mconala\"\n", "\n assert candidate([\"MCoNaLa\"]) == \"MCoNaLa\"\n" ]
f_4048964
concatenate elements of list `list` by tabs ` `
[]
3,182,716
def f_3182716(): return
'\xd0\xbf\xd1\x80\xd0\xb8'.encode('raw_unicode_escape')
def check(candidate):
[ "\n assert candidate() == b'\\xd0\\xbf\\xd1\\x80\\xd0\\xb8'\n" ]
f_3182716
print unicode string '\xd0\xbf\xd1\x80\xd0\xb8' with utf-8
[]
3,182,716
def f_3182716(): return
'Sopet\xc3\xb3n'.encode('latin-1').decode('utf-8')
def check(candidate):
[ "\n assert candidate() == \"Sopetón\"\n" ]
f_3182716
Encode a latin character in string `Sopet\xc3\xb3n` properly
[]
35,622,945
def f_35622945(s): return
re.findall('n(?<=[^n]n)n+(?=[^n])(?i)', s)
import re def check(candidate):
[ "\n assert candidate(\"ncnnnne\") == ['nnnn']\n", "\n assert candidate(\"nn\") == []\n", "\n assert candidate(\"ask\") == []\n" ]
f_35622945
regex, find "n"s only in the middle of string `s`
[ "re" ]
5,306,756
def f_5306756(): return
'{0:.0f}%'.format(1.0 / 3 * 100)
def check(candidate):
[ "\n assert(candidate() == \"33%\")\n" ]
f_5306756
display the float `1/3*100` as a percentage
[]
2,878,084
def f_2878084(mylist):
return mylist
mylist.sort(key=lambda x: x['title'])
def check(candidate):
[ "\n input = [\n {'title':'New York Times', 'title_url':'New_York_Times','id':4}, \n {'title':'USA Today','title_url':'USA_Today','id':6}, \n {'title':'Apple News','title_url':'Apple_News','id':2}\n ]\n res = [\n {'title': 'Apple News', 'title_url': 'Apple_News', 'id': 2}, \n {'title': 'New York Times', 'title_url': 'New_York_Times', 'id': 4},\n {'title': 'USA Today', 'title_url': 'USA_Today', 'id': 6}\n ]\n assert candidate(input) == res\n" ]
f_2878084
sort a list of dictionary `mylist` by the key `title`
[]
2,878,084
def f_2878084(l):
return l
l.sort(key=lambda x: x['title'])
def check(candidate):
[ "\n input = [\n {'title':'New York Times', 'title_url':'New_York_Times','id':4}, \n {'title':'USA Today','title_url':'USA_Today','id':6}, \n {'title':'Apple News','title_url':'Apple_News','id':2}\n ]\n res = [\n {'title': 'Apple News', 'title_url': 'Apple_News', 'id': 2}, \n {'title': 'New York Times', 'title_url': 'New_York_Times', 'id': 4},\n {'title': 'USA Today', 'title_url': 'USA_Today', 'id': 6}\n ]\n assert candidate(input) == res\n" ]
f_2878084
sort a list `l` of dicts by dict value 'title'
[]
2,878,084
def f_2878084(l):
return l
l.sort(key=lambda x: (x['title'], x['title_url'], x['id']))
def check(candidate):
[ "\n input = [\n {'title':'New York Times', 'title_url':'New_York_Times','id':4}, \n {'title':'USA Today','title_url':'USA_Today','id':6}, \n {'title':'Apple News','title_url':'Apple_News','id':2}\n ]\n res = [\n {'title': 'Apple News', 'title_url': 'Apple_News', 'id': 2}, \n {'title': 'New York Times', 'title_url': 'New_York_Times', 'id': 4},\n {'title': 'USA Today', 'title_url': 'USA_Today', 'id': 6}\n ]\n assert candidate(input) == res\n" ]
f_2878084
sort a list of dictionaries by the value of keys 'title', 'title_url', 'id' in ascending order.
[]
9,323,159
def f_9323159(l1, l2): return
heapq.nlargest(10, range(len(l1)), key=lambda i: abs(l1[i] - l2[i]))
import heapq def check(candidate):
[ "\n l1 = [99, 86, 90, 70, 86, 95, 56, 98, 80, 81]\n l2 = [21, 11, 21, 1, 26, 40, 4, 50, 34, 37]\n res = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n assert candidate(l1, l2) == res\n" ]
f_9323159
find 10 largest differences between each respective elements of list `l1` and list `l2`
[ "heapq" ]
29,877,663
def f_29877663(soup): return
soup.find_all('span', {'class': 'starGryB sp'})
import bs4 def check(candidate):
[ "\n html = '''<span class=\"starBig sp\">4.1</span>\n <span class=\"starGryB sp\">2.9</span>\n <span class=\"sp starGryB\">2.9</span>\n <span class=\"sp starBig\">22</span>'''\n soup = bs4.BeautifulSoup(html, features=\"html5lib\")\n res = '''[<span class=\"starGryB sp\">2.9</span>]'''\n assert(str(candidate(soup)) == res)\n" ]
f_29877663
BeautifulSoup find all 'span' elements in HTML string `soup` with class of 'starGryB sp'
[ "bs4" ]
24,189,150
def f_24189150(df, engine):
return
df.to_sql('test', engine)
import pandas as pd from sqlalchemy import create_engine def check(candidate):
[ "\n engine = create_engine('sqlite://', echo=False)\n df = pd.DataFrame({'name' : ['User 1', 'User 2', 'User 3']})\n candidate(df, engine)\n result = pd.read_sql('SELECT name FROM test', engine)\n assert result.equals(df)\n" ]
f_24189150
write records in dataframe `df` to table 'test' in schema 'a_schema' with `engine`
[ "pandas", "sqlalchemy" ]
30,766,151
def f_30766151(s): return
re.sub('[^(){}[\]]', '', s)
import re def check(candidate):
[ "\n assert candidate(\"(a(vdwvndw){}]\") == \"((){}]\"\n", "\n assert candidate(\"12345\") == \"\"\n" ]
f_30766151
Extract brackets from string `s`
[ "re" ]
1,143,379
def f_1143379(L): return
list(dict((x[0], x) for x in L).values())
def check(candidate):
[ "\n L = [['14', '65', 76], ['2', '5', 6], ['7', '12', 33], ['14', '22', 46]]\n res = [['14', '22', 46], ['2', '5', 6], ['7', '12', 33]]\n assert(candidate(L) == res)\n", "\n assert candidate([\"a\", \"aa\", \"abc\", \"bac\"]) == [\"abc\", \"bac\"]\n" ]
f_1143379
remove duplicate elements from list 'L'
[]
12,330,522
def f_12330522(file): return
[line.rstrip('\n') for line in file]
def check(candidate):
[ "\n res = ['1', '2', '3']\n f = open(\"myfile.txt\", \"a\")\n f.write(\"1\\n2\\n3\")\n f.close()\n f = open(\"myfile.txt\", \"r\")\n assert candidate(f) == res\n" ]
f_12330522
read a file `file` without newlines
[]
364,621
def f_364621(testlist): return
[i for (i, x) in enumerate(testlist) if (x == 1)]
def check(candidate):
[ "\n testlist = [1,2,3,5,3,1,2,1,6]\n assert candidate(testlist) == [0, 5, 7]\n", "\n testlist = [0, -1]\n assert candidate(testlist) == []\n" ]
f_364621
get the position of item 1 in `testlist`
[]
364,621
def f_364621(testlist): return
[i for (i, x) in enumerate(testlist) if (x == 1)]
def check(candidate):
[ "\n testlist = [1,2,3,5,3,1,2,1,6]\n assert candidate(testlist) == [0, 5, 7]\n", "\n testlist = [0, -1]\n assert candidate(testlist) == []\n" ]
f_364621
get the position of item 1 in `testlist`
[]
364,621
def f_364621(testlist, element): return
testlist.index(element)
def check(candidate):
[ "\n testlist = [1,2,3,5,3,1,2,1,6]\n assert candidate(testlist, 1) == 0\n", "\n testlist = [1,2,3,5,3,1,2,1,6]\n try:\n candidate(testlist, 14)\n except:\n assert True\n" ]
f_364621
get the position of item `element` in list `testlist`
[]
13,145,368
def f_13145368(lis): return
max(lis, key=lambda item: item[1])[0]
def check(candidate):
[ "\n lis = [(101, 153), (255, 827), (361, 961)]\n assert candidate(lis) == 361\n" ]
f_13145368
find the first element of the tuple with the maximum second element in a list of tuples `lis`
[]
13,145,368
def f_13145368(lis): return
max(lis, key=itemgetter(1))[0]
from operator import itemgetter def check(candidate):
[ "\n lis = [(101, 153), (255, 827), (361, 961)]\n assert candidate(lis) == 361\n" ]
f_13145368
get the item at index 0 from the tuple that has maximum value at index 1 in list `lis`
[ "operator" ]
2,689,189
def f_2689189():
return
time.sleep(1)
import time def check(candidate):
[ "\n t1 = time.time()\n candidate()\n t2 = time.time()\n assert t2 - t1 > 1\n" ]
f_2689189
Make a delay of 1 second
[ "time" ]
12,485,244
def f_12485244(L): return
""", """.join('(' + ', '.join(i) + ')' for i in L)
def check(candidate):
[ "\n L = [(\"abc\", \"def\"), (\"hij\", \"klm\")]\n assert candidate(L) == '(abc, def), (hij, klm)'\n" ]
f_12485244
convert list of tuples `L` to a string
[]
755,857
def f_755857():
return b
b = models.CharField(max_length=7, default='0000000', editable=False)
from django.db import models def check(candidate):
[ "\n assert candidate().get_default() == '0000000'\n" ]
f_755857
Django set default value of field `b` equal to '0000000'
[ "django" ]
16,193,578
def f_16193578(list5): return
sorted(list5, key = lambda x: (degrees(x), x))
from math import degrees def check(candidate):
[ "\n list5 = [4, 1, 2, 3, 9, 5]\n assert candidate(list5) == [1, 2, 3, 4, 5, 9]\n" ]
f_16193578
Sort lis `list5` in ascending order based on the degrees value of its elements
[ "math" ]
16,041,405
def f_16041405(l): return
(n for n in l)
def check(candidate):
[ "\n generator = candidate([1,2,3,5])\n assert str(type(generator)) == \"<class 'generator'>\"\n assert [x for x in generator] == [1, 2, 3, 5]\n" ]
f_16041405
convert a list `l` into a generator object
[]
18,837,607
def f_18837607(oldlist, removelist): return
[v for i, v in enumerate(oldlist) if i not in removelist]
def check(candidate):
[ "\n assert candidate([\"asdf\",\"ghjk\",\"qwer\",\"tyui\"], [1,3]) == ['asdf', 'qwer']\n", "\n assert candidate([1,2,3,4,5], [0,4]) == [2,3,4]\n" ]
f_18837607
remove elements from list `oldlist` that have an index number mentioned in list `removelist`
[]
4,710,067
def f_4710067(): return
open('yourfile.txt', 'w')
def check(candidate):
[ "\n fw = candidate()\n assert fw.name == \"yourfile.txt\"\n assert fw.mode == 'w'\n" ]
f_4710067
Open a file `yourfile.txt` in write mode
[]
7,373,219
def f_7373219(obj, attr): return
getattr(obj, attr)
def check(candidate):
[ "\n class Student:\n student_id = \"\"\n student_name = \"\"\n\n def __init__(self, student_id=101, student_name=\"Adam\"):\n self.student_id = student_id\n self.student_name = student_name\n\n student = Student()\n\n assert(candidate(student, 'student_name') == \"Adam\")\n assert(candidate(student, 'student_id') == 101)\n", "\n class Student:\n student_id = \"\"\n student_name = \"\"\n\n def __init__(self, student_id=101, student_name=\"Adam\"):\n self.student_id = student_id\n self.student_name = student_name\n\n student = Student()\n\n try:\n value = candidate(student, 'student_none')\n except: \n assert True\n" ]
f_7373219
get attribute 'attr' from object `obj`
[]
8,171,751
def f_8171751(): return
reduce(lambda a, b: a + b, (('aa',), ('bb',), ('cc',)))
from functools import reduce def check(candidate):
[ "\n assert candidate() == ('aa', 'bb', 'cc')\n" ]
f_8171751
convert tuple of tuples `(('aa',), ('bb',), ('cc',))` to tuple
[ "functools" ]
8,171,751
def f_8171751(): return
list(map(lambda a: a[0], (('aa',), ('bb',), ('cc',))))
def check(candidate):
[ "\n assert candidate() == ['aa', 'bb', 'cc']\n" ]
f_8171751
convert tuple of tuples `(('aa',), ('bb',), ('cc',))` to list in one line
[]
28,986,489
def f_28986489(df):
return df
df['range'].replace(',', '-', inplace=True)
import pandas as pd def check(candidate):
[ "\n df = pd.DataFrame({'range' : [\",\", \"(50,290)\", \",,,\"]})\n res = pd.DataFrame({'range' : [\"-\", \"(50,290)\", \",,,\"]})\n assert candidate(df).equals(res)\n" ]
f_28986489
replace a characters in a column of a dataframe `df`
[ "pandas" ]
19,339
def f_19339(): return
zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)])
def check(candidate):
[ "\n assert [a for a in candidate()] == [('a', 'b', 'c', 'd'), (1, 2, 3, 4)]\n" ]
f_19339
unzip the list `[('a', 1), ('b', 2), ('c', 3), ('d', 4)]`
[]
19,339
def f_19339(original): return
([a for (a, b) in original], [b for (a, b) in original])
def check(candidate):
[ "\n original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]\n assert candidate(original) == (['a', 'b', 'c', 'd'], [1, 2, 3, 4])\n", "\n original2 = [([], 1), ([], 2), (5, 3), (6, 4)]\n assert candidate(original2) == ([[], [], 5, 6], [1, 2, 3, 4])\n" ]
f_19339
unzip list `original`
[]
19,339
def f_19339(original): return
((a for (a, b) in original), (b for (a, b) in original))
def check(candidate):
[ "\n original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]\n result = candidate(original)\n assert [a for gen in result for a in gen] == ['a','b','c','d',1,2,3,4]\n", "\n original2 = [([], 1), ([], 2), (5, 3), (6, 4)]\n result2 = candidate(original2)\n assert [a for gen in result2 for a in gen] == [[], [], 5, 6, 1, 2, 3, 4]\n" ]
f_19339
unzip list `original` and return a generator
[]
19,339
def f_19339(): return
zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e',)])
def check(candidate):
[ "\n assert list(candidate()) == [('a', 'b', 'c', 'd', 'e')]\n" ]
f_19339
unzip list `[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', )]`
[]
19,339
def f_19339(): return
list(zip_longest(('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e',)))
from itertools import zip_longest def check(candidate):
[ "\n assert(candidate() == [('a', 'b', 'c', 'd', 'e'), (1, 2, 3, 4, None)])\n" ]
f_19339
unzip list `[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', )]` and fill empty results with None
[ "itertools" ]
1,960,516
def f_1960516(): return
json.dumps('3.9')
import json def check(candidate):
[ "\n data = candidate()\n assert json.loads(data) == '3.9'\n" ]
f_1960516
encode `Decimal('3.9')` to a JSON string
[ "json" ]
1,024,847
def f_1024847(d):
return d
d['mynewkey'] = 'mynewvalue'
def check(candidate):
[ "\n assert candidate({'key': 'value'}) == {'key': 'value', 'mynewkey': 'mynewvalue'}\n" ]
f_1024847
Add key "mynewkey" to dictionary `d` with value "mynewvalue"
[]
1,024,847
def f_1024847(data):
return data
data.update({'a': 1, })
def check(candidate):
[ "\n assert candidate({'key': 'value'}) == {'key': 'value', 'a': 1}\n", "\n assert candidate({'key': 'value', 'a' : 2}) == {'key': 'value', 'a': 1}\n" ]
f_1024847
Add key 'a' to dictionary `data` with value 1
[]
1,024,847
def f_1024847(data):
return data
data.update(dict(a=1))
def check(candidate):
[ "\n assert candidate({'key': 'value'}) == {'key': 'value', 'a': 1}\n", "\n assert candidate({'key': 'value', 'a' : 2}) == {'key': 'value', 'a': 1}\n" ]
f_1024847
Add key 'a' to dictionary `data` with value 1
[]
1,024,847
def f_1024847(data):
return data
data.update(a=1)
def check(candidate):
[ "\n assert candidate({'key': 'value'}) == {'key': 'value', 'a': 1}\n", "\n assert candidate({'key': 'value', 'a' : 2}) == {'key': 'value', 'a': 1}\n" ]
f_1024847
Add key 'a' to dictionary `data` with value 1
[]
35,837,346
def f_35837346(matrix): return
max([max(i) for i in matrix])
def check(candidate):
[ "\n assert candidate([[1,2,3],[4,5,6],[7,8,9]]) == 9\n", "\n assert candidate([[1.3,2.8],[4.2,10],[7.9,8.1,5]]) == 10\n" ]
f_35837346
find maximal value in matrix `matrix`
[]
20,457,038
def f_20457038(answer):
return answer
answer = str(round(answer, 2))
def check(candidate):
[ "\n assert candidate(2.34351) == \"2.34\"\n", "\n assert candidate(99.375) == \"99.38\"\n", "\n assert candidate(4.1) == \"4.1\"\n", "\n assert candidate(3) == \"3\"\n" ]
f_20457038
Round number `answer` to 2 precision after the decimal point
[]
2,890,896
def f_2890896(s):
return ip
ip = re.findall('[0-9]+(?:\\.[0-9]+){3}', s)
import re def check(candidate):
[ "\n assert candidate(\"<html><head><title>Current IP Check</title></head><body>Current IP Address: 165.91.15.131</body></html>\") == [\"165.91.15.131\"]\n", "\n assert candidate(\"<html><head><title>Current IP Check</title></head><body>Current IP Address: 165.91.15.131 and this is not a IP Address: 165.91.15</body></html>\") == [\"165.91.15.131\"]\n", "\n assert candidate(\"<html><head><title>Current IP Check</title></head><body>Current IP Address: 192.168.1.1 & this is another IP address: 192.168.1.2</body></html>\") == [\"192.168.1.1\", \"192.168.1.2\"]\n" ]
f_2890896
extract ip address `ip` from an html string `s`
[ "re" ]
29,836,836
def f_29836836(df): return
df.groupby('A').filter(lambda x: len(x) > 1)
import pandas as pd def check(candidate):
[ "\n assert candidate(pd.DataFrame([[1, 2], [1, 4], [5, 6]], columns=['A', 'B'])).equals(pd.DataFrame([[1, 2], [1, 4]], columns=['A', 'B'])) is True\n", "\n assert candidate(pd.DataFrame([[1, 2], [1, 4], [1, 6]], columns=['A', 'B'])).equals(pd.DataFrame([[1, 2], [1, 4], [1, 6]], columns=['A', 'B'])) is True\n" ]
f_29836836
filter dataframe `df` by values in column `A` that appear more than once
[ "pandas" ]
2,545,397
def f_2545397(myfile): return
[x for x in myfile if x != '']
def check(candidate):
[ "\n with open('./tmp.txt', 'w') as fw: \n for s in [\"hello\", \"world\", \"!!!\"]:\n fw.write(f\"{s}\\n\")\n\n with open('./tmp.txt', 'r') as myfile:\n lines = candidate(myfile)\n assert isinstance(lines, list)\n assert len(lines) == 3\n assert lines[0].strip() == \"hello\"\n" ]
f_2545397
append each line in file `myfile` into a list
[]
2,545,397
def f_2545397():
return lst
lst = list(map(int, open('filename.txt').readlines()))
import pandas as pd def check(candidate):
[ "\n with open('./filename.txt', 'w') as fw: \n for s in [\"1\", \"2\", \"100\"]:\n fw.write(f\"{s}\\n\")\n\n assert candidate() == [1, 2, 100]\n" ]
f_2545397
Get a list of integers `lst` from a file `filename.txt`
[ "pandas" ]
35,420,052
def f_35420052(plt, mappable, ax3):
return plt
plt.colorbar(mappable=mappable, cax=ax3)
import numpy as np import matplotlib.pyplot as plt from obspy.core.trace import Trace from obspy.imaging.spectrogram import spectrogram def check(candidate):
[ "\n spl1 = Trace(data=np.arange(0, 10))\n fig = plt.figure()\n ax1 = fig.add_axes([0.1, 0.75, 0.7, 0.2]) #[left bottom width height]\n ax2 = fig.add_axes([0.1, 0.1, 0.7, 0.60], sharex=ax1)\n ax3 = fig.add_axes([0.83, 0.1, 0.03, 0.6])\n\n #make time vector\n t = np.arange(spl1.stats.npts) / spl1.stats.sampling_rate\n\n #plot waveform (top subfigure) \n ax1.plot(t, spl1.data, 'k')\n\n #plot spectrogram (bottom subfigure)\n spl2 = spl1\n fig = spl2.spectrogram(show=False, axes=ax2, wlen=10)\n mappable = ax2.images[0]\n candidate(plt, mappable, ax3)\n \n im=ax2.images\n assert im[-1].colorbar is not None\n" ]
f_35420052
add color bar with image `mappable` to plot `plt`
[ "matplotlib", "numpy", "obspy" ]
29,903,025
def f_29903025(df): return
Counter(' '.join(df['text']).split()).most_common(100)
import pandas as pd from collections import Counter def check(candidate):
[ "\n df = pd.DataFrame({\"text\": [\n 'Python is a high-level, general-purpose programming language.', \n 'Its design philosophy emphasizes code readability with the use of significant indentation. Python is dynamically-typed and garbage-collected.'\n ]})\n assert candidate(df) == [('Python', 2),('is', 2),('a', 1),('high-level,', 1),('general-purpose', 1),\n ('programming', 1),('language.', 1),('Its', 1),('design', 1),('philosophy', 1),('emphasizes', 1),\n ('code', 1),('readability', 1),('with', 1), ('the', 1),('use', 1),('of', 1),('significant', 1),\n ('indentation.', 1),('dynamically-typed', 1),('and', 1),('garbage-collected.', 1)]\n" ]
f_29903025
count most frequent 100 words in column 'text' of dataframe `df`
[ "collections", "pandas" ]
7,378,180
def f_7378180(): return
list(itertools.combinations((1, 2, 3), 2))
import itertools def check(candidate):
[ "\n assert candidate() == [(1, 2), (1, 3), (2, 3)]\n" ]
f_7378180
generate all 2-element subsets of tuple `(1, 2, 3)`
[ "itertools" ]
4,530,069
def f_4530069(): return
datetime.now(pytz.utc)
import pytz import time from datetime import datetime, timezone def check(candidate):
[ "\n assert (candidate() - datetime(1970, 1, 1).replace(tzinfo=timezone.utc)).total_seconds() - time.time() <= 1\n" ]
f_4530069
get a value of datetime.today() in the UTC time zone
[ "datetime", "pytz", "time" ]
4,842,956
def f_4842956(list1):
return list2
list2 = [x for x in list1 if x != []]
def check(candidate):
[ "\n assert candidate([[\"a\"], [], [\"b\"]]) == [[\"a\"], [\"b\"]]\n", "\n assert candidate([[], [1,2,3], [], [\"b\"]]) == [[1,2,3], [\"b\"]]\n" ]
f_4842956
Get a new list `list2`by removing empty list from a list of lists `list1`
[]
4,842,956
def f_4842956(list1):
return list2
list2 = [x for x in list1 if x]
def check(candidate):
[ "\n assert candidate([[\"a\"], [], [\"b\"]]) == [[\"a\"], [\"b\"]]\n", "\n assert candidate([[], [1,2,3], [], [\"b\"]]) == [[1,2,3], [\"b\"]]\n" ]
f_4842956
Create `list2` to contain the lists from list `list1` excluding the empty lists from `list1`
[]
9,262,278
def f_9262278(data): return
HttpResponse(data, content_type='application/json')
import os import json from django.http import HttpResponse from django.conf import settings if not settings.configured: settings.configure(DEBUG=True) def check(candidate):
[ "\n if settings.DEBUG:\n assert candidate(json.dumps({\"Sample-Key\": \"Sample-Value\"})).content == b'{\"Sample-Key\": \"Sample-Value\"}'\n", "\n if settings.DEBUG:\n assert candidate(json.dumps({\"Sample-Key\": \"Sample-Value\"}))['content-type'] == 'application/json'\n" ]
f_9262278
Django response with JSON `data`
[ "django", "json", "os" ]
17,284,947
def f_17284947(example_str): return
re.findall('(.*?)\\[.*?\\]', example_str)
import re def check(candidate):
[ "\n list_elems = candidate(\"Josie Smith [3996 COLLEGE AVENUE, SOMETOWN, MD 21003]Mugsy Dog Smith [2560 OAK ST, GLENMEADE, WI 14098]\")\n assert \"\".join(list_elems).strip() == 'Josie Smith Mugsy Dog Smith'\n" ]
f_17284947
get all text that is not enclosed within square brackets in string `example_str`
[ "re" ]
17,284,947
def f_17284947(example_str): return
re.findall('(.*?)(?:\\[.*?\\]|$)', example_str)
import re def check(candidate):
[ "\n list_elems = candidate(\"Josie Smith [3996 COLLEGE AVENUE, SOMETOWN, MD 21003]Mugsy Dog Smith [2560 OAK ST, GLENMEADE, WI 14098]\")\n assert \"\".join(list_elems).strip() == 'Josie Smith Mugsy Dog Smith'\n" ]
f_17284947
Use a regex to get all text in a string `example_str` that is not surrounded by square brackets
[ "re" ]
14,182,339
def f_14182339(): return
re.findall('\\(.+?\\)|\\w', '(zyx)bc')
import re def check(candidate):
[ "\n assert candidate() == ['(zyx)', 'b', 'c']\n" ]
f_14182339
get whatever is between parentheses as a single match, and any char outside as an individual match in string '(zyx)bc'
[ "re" ]
14,182,339
def f_14182339(): return
re.findall('\\((.*?)\\)|(\\w)', '(zyx)bc')
import re def check(candidate):
[ "\n assert candidate() == [('zyx', ''), ('', 'b'), ('', 'c')]\n" ]
f_14182339
match regex '\\((.*?)\\)|(\\w)' with string '(zyx)bc'
[ "re" ]
14,182,339
def f_14182339(): return
re.findall('\\(.*?\\)|\\w', '(zyx)bc')
import re def check(candidate):
[ "\n assert candidate() == ['(zyx)', 'b', 'c']\n" ]
f_14182339
match multiple regex patterns with the alternation operator `|` in a string `(zyx)bc`
[ "re" ]
7,126,916
def f_7126916(elements):
return elements
elements = ['%{0}%'.format(element) for element in elements]
def check(candidate):
[ "\n elements = ['abc', 'def', 'ijk', 'mno']\n assert candidate(elements) == ['%abc%', '%def%', '%ijk%', '%mno%']\n", "\n elements = [1, 2, 3, 4, 500]\n assert candidate(elements) == ['%1%', '%2%', '%3%', '%4%', '%500%']\n" ]
f_7126916
formate each string cin list `elements` into pattern '%{0}%'
[]
3,595,685
def f_3595685(): return
subprocess.Popen(['background-process', 'arguments'])
import subprocess from unittest.mock import Mock def check(candidate):
[ "\n subprocess.Popen = Mock(return_value = 0)\n assert candidate() == 0\n" ]
f_3595685
Open a background process 'background-process' with arguments 'arguments'
[ "subprocess" ]
18,453,566
def f_18453566(mydict, mykeys): return
[mydict[x] for x in mykeys]
def check(candidate):
[ "\n mydict = {'one': 1, 'two': 2, 'three': 3}\n mykeys = ['three', 'one']\n assert candidate(mydict, mykeys) == [3, 1]\n", "\n mydict = {'one': 1.0, 'two': 2.0, 'three': 3.0}\n mykeys = ['one']\n assert candidate(mydict, mykeys) == [1.0]\n" ]
f_18453566
get list of values from dictionary 'mydict' w.r.t. list of keys 'mykeys'
[]
12,692,135
def f_12692135(): return
dict([('Name', 'Joe'), ('Age', 22)])
def check(candidate):
[ "\n assert candidate() == {'Name': 'Joe', 'Age': 22}\n" ]
f_12692135
convert list `[('Name', 'Joe'), ('Age', 22)]` into a dictionary
[]
14,401,047
def f_14401047(data): return
data.mean(axis=1).reshape(data.shape[0], -1)
import numpy as np def check(candidate):
[ "\n data = np.array([[1, 2, 3, 4, 4, 3, 7, 1], [6, 2, 3, 4, 3, 4, 4, 1]])\n expected_res = np.array([[3.125], [3.375]])\n assert np.array_equal(candidate(data), expected_res)\n" ]
f_14401047
average each two columns of array `data`
[ "numpy" ]
18,886,596
def f_18886596(s): return
s.replace('"', '\"')
def check(candidate):
[ "\n s = 'This sentence has some \"quotes\" in it'\n assert candidate(s) == 'This sentence has some \\\"quotes\\\" in it'\n" ]
f_18886596
double backslash escape all double quotes in string `s`
[]
5,932,059
def f_5932059(s): return
re.split('(\\W+)', s)
import re def check(candidate):
[ "\n s = \"this is a\\nsentence\"\n assert candidate(s) == ['this', ' ', 'is', ' ', 'a', '\\n', 'sentence']\n" ]
f_5932059
split a string `s` into a list of words and whitespace
[ "re" ]
9,938,130
def f_9938130(df): return
df.plot(kind='barh', stacked=True)
import pandas as pd def check(candidate):
[ "\n data = [[1, 3], [2, 5], [4, 8]]\n df = pd.DataFrame(data, columns = ['a', 'b'])\n assert str(candidate(df)).split('(')[0] == 'AxesSubplot'\n" ]
f_9938130
plotting stacked barplots on a panda data frame `df`
[ "pandas" ]
35,945,473
def f_35945473(myDictionary): return
{i[1]: i[0] for i in list(myDictionary.items())}
def check(candidate):
[ "\n assert candidate({'a' : 'b', 'c' : 'd'}) == {'b': 'a', 'd': 'c'}\n" ]
f_35945473
reverse the keys and values in a dictionary `myDictionary`
[]
30,729,735
def f_30729735(myList): return
[i for i, j in enumerate(myList) if 'how' in j.lower() or 'what' in j.lower()]
def check(candidate):
[ "\n assert candidate(['abc', 'how', 'what', 'def']) == [1, 2]\n" ]
f_30729735
finding the index of elements containing substring 'how' and 'what' in a list of strings 'myList'.
[]
1,303,243
def f_1303243(obj): return
isinstance(obj, str)
def check(candidate):
[ "\n assert candidate('python3') == True\n", "\n assert candidate(1.23) == False\n" ]
f_1303243
check if object `obj` is a string
[]
1,303,243
def f_1303243(o): return
isinstance(o, str)
def check(candidate):
[ "\n assert candidate(\"hello\") == True\n", "\n assert candidate(123) == False\n", "\n assert candidate([]) == False\n", "\n assert candidate({\"aa\", \"v\"}) == False\n", "\n assert candidate(\"123\") == True\n" ]
f_1303243
check if object `o` is a string
[]
1,303,243
def f_1303243(o): return
(type(o) is str)
def check(candidate):
[ "\n assert candidate(\"hello\") == True\n", "\n assert candidate(123) == False\n", "\n assert candidate([]) == False\n", "\n assert candidate({\"aa\", \"v\"}) == False\n", "\n assert candidate(\"123\") == True\n" ]
f_1303243
check if object `o` is a string
[]
1,303,243
def f_1303243(obj_to_test): return
isinstance(obj_to_test, str)
def check(candidate):
[ "\n assert candidate(\"hello\") == True\n", "\n assert candidate(123) == False\n", "\n assert candidate([]) == False\n", "\n assert candidate({\"aa\", \"v\"}) == False\n", "\n assert candidate(\"123\") == True\n" ]
f_1303243
check if `obj_to_test` is a string
[]
8,177,079
def f_8177079(list1, list2):
return
list2.extend(list1)
def check(candidate):
[ "\n a, b = [1, 2, 3], [4, 5, 6]\n candidate(a, b)\n assert b == [4, 5, 6, 1, 2, 3]\n", "\n a, c = [1, 2, 3], [7, 8, 9]\n candidate(a, c)\n assert c == [7, 8, 9, 1, 2, 3] \n", "\n b = [4, 5, 6, 1, 2, 3]\n c = [7, 8, 9, 1, 2, 3] \n candidate(b, c)\n assert c == [7, 8, 9, 1, 2, 3, 4, 5, 6, 1, 2, 3]\n" ]
f_8177079
append list `list1` to `list2`
[]
8,177,079
def f_8177079(mylog, list1):
return
list1.extend(mylog)
def check(candidate):
[ "\n a, b = [1, 2, 3], [4, 5, 6]\n candidate(a, b)\n assert b == [4, 5, 6, 1, 2, 3]\n", "\n a, c = [1, 2, 3], [7, 8, 9]\n candidate(a, c)\n assert c == [7, 8, 9, 1, 2, 3] \n", "\n b = [4, 5, 6, 1, 2, 3]\n c = [7, 8, 9, 1, 2, 3] \n candidate(b, c)\n assert c == [7, 8, 9, 1, 2, 3, 4, 5, 6, 1, 2, 3]\n" ]
f_8177079
append list `mylog` to `list1`
[]
8,177,079
def f_8177079(a, c):
return
c.extend(a)
def check(candidate):
[ "\n a, b = [1, 2, 3], [4, 5, 6]\n candidate(a, b)\n assert b == [4, 5, 6, 1, 2, 3]\n", "\n a, c = [1, 2, 3], [7, 8, 9]\n candidate(a, c)\n assert c == [7, 8, 9, 1, 2, 3] \n", "\n b = [4, 5, 6, 1, 2, 3]\n c = [7, 8, 9, 1, 2, 3] \n candidate(b, c)\n assert c == [7, 8, 9, 1, 2, 3, 4, 5, 6, 1, 2, 3]\n" ]
f_8177079
append list `a` to `c`
[]
8,177,079
def f_8177079(mylog, list1):
return
for line in mylog: list1.append(line)
def check(candidate):
[ "\n a, b = [1, 2, 3], [4, 5, 6]\n candidate(a, b)\n assert b == [4, 5, 6, 1, 2, 3]\n", "\n a, c = [1, 2, 3], [7, 8, 9]\n candidate(a, c)\n assert c == [7, 8, 9, 1, 2, 3] \n", "\n b = [4, 5, 6, 1, 2, 3]\n c = [7, 8, 9, 1, 2, 3] \n candidate(b, c)\n assert c == [7, 8, 9, 1, 2, 3, 4, 5, 6, 1, 2, 3]\n" ]
f_8177079
append items in list `mylog` to `list1`
[]
4,126,227
def f_4126227(a, b):
return
b.append((a[0][0], a[0][2]))
def check(candidate):
[ "\n a = [(1,2,3),(4,5,6)]\n b = [(0,0)]\n candidate(a, b)\n assert(b == [(0, 0), (1, 3)])\n" ]
f_4126227
append a tuple of elements from list `a` with indexes '[0][0] [0][2]' to list `b`
[]
34,902,378
def f_34902378(app):
return
app.config['SECRET_KEY'] = 'Your_secret_string'
from flask import Flask def check(candidate):
[ "\n app = Flask(\"test\")\n candidate(app)\n assert app.config['SECRET_KEY'] == 'Your_secret_string'\n" ]
f_34902378
Initialize `SECRET_KEY` in flask config with `Your_secret_string `
[ "flask" ]
22,799,300
def f_22799300(out): return
pd.DataFrame(out.tolist(), columns=['out-1', 'out-2'], index=out.index)
import numpy as np import pandas as pd from scipy import stats def check(candidate):
[ "\n df = pd.DataFrame(dict(x=np.random.randn(100), y=np.repeat(list(\"abcd\"), 25)))\n out = df.groupby(\"y\").x.apply(stats.ttest_1samp, 0)\n test = pd.DataFrame(out.tolist())\n test.columns = ['out-1', 'out-2']\n test.index = out.index\n res = candidate(out)\n assert(test.equals(res))\n" ]
f_22799300
unpack a series of tuples in pandas `out` into a DataFrame with column names 'out-1' and 'out-2'
[ "numpy", "pandas", "scipy" ]