Prompt:
def f_3283984():
	return


Prompt:
def f_3844801(myList):
	return

assert candidate(['k','k','k','k','k']) == True

assert candidate([None,'%$#ga',3]) == False

check if all elements in list `myList` are identical


Prompt:
def f_4302166():
	return

assert candidate() == '              Python :            Very Good'

format number of spaces between strings `Python`, `:` and `Very Good` to be `20`


Prompt:
def f_7555335(d):
	return

assert candidate('hello world!'.encode('cp1251')) == b'hello world!'

assert candidate(''.encode('cp1251')) == b''

assert candidate('hello world!'.encode('cp1251')) != 'hello world!'

convert a string `d` from CP-1251 to UTF-8


Prompt:
def f_2544710(kwargs):
	return

{k: v for k, v in list(kwargs.items()) if v is not None}

assert candidate({i: None for i in range(10)}) == {}

assert candidate({'abc': 'abc'})['abc'] == 'abc'

assert candidate({'x': None, 'yy': 234}) == {'yy': 234}

get rid of None values in dictionary `kwargs`


Prompt:
def f_2544710(kwargs):
	return

dict((k, v) for k, v in kwargs.items() if v is not None)

assert candidate({i: None for i in range(10)}) == {}

assert candidate({'abc': 'abc'})['abc'] == 'abc'

assert candidate({'x': None, 'yy': 234}) == {'yy': 234}

get rid of None values in dictionary `kwargs`


Prompt:
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):

    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'
    subprocess.check_output = Mock(return_value = output)
    assert candidate() == output

capture final output of a chain of system commands `ps -ef | grep something | wc -l`


Prompt:
def f_6726636():
	return

concatenate a list of strings `['a', 'b', 'c']`


Prompt:
def f_18079563(s1, s2):
	return

import pandas as pd

def check(candidate):

    x1, x2 = pd.Series([1,2]), pd.Series([1,3])
    assert candidate(x1, x2).equals(pd.Series([1]))

    x1, x2 = pd.Series([1,2]), pd.Series([1,3, 10, 4, 5, 9])
    assert candidate(x1, x2).equals(pd.Series([1]))

    x1, x2 = pd.Series([1,2]), pd.Series([1,2, 10])
    assert candidate(x1, x2).equals(pd.Series([1, 2]))

find intersection data between series `s1` and series `s2`


Prompt: def f_8315209(client):

import socket
from unittest.mock import Mock
import mock

def check(candidate):

    with mock.patch('socket.socket') as mock_socket:
        mock_socket.return_value.recv.return_value = ''
        mock_socket.bind(('', 8080))
        mock_socket.listen(5)
        mock_socket.accept = Mock(return_value = mock_socket)
        mock_socket.send = Mock()
        try:
            candidate(mock_socket)
        except:
            assert False


Prompt:
def f_26153795(when):
	return

assert candidate('2013-05-07') == datetime.date(2013, 5, 7)

assert candidate('1990-01-08') == datetime.date(1990, 1, 8)

assert candidate('1990-1-08') == datetime.date(1990, 1, 8)

assert candidate('1990-1-8') == datetime.date(1990, 1, 8)

assert candidate('1990-01-8') == datetime.date(1990, 1, 8)

Format a datetime string `when` to extract date only


Prompt:
def f_172439(inputString):
	return

assert candidate('line a\nfollows by line b	...bye\n') ==         ['line a', 'follows by line b	...bye', '']

assert candidate('no new line in this sentence. ') == ['no new line in this sentence. ']

assert candidate('a	bfs hhhdf	sfdas') == ['a	bfs hhhdf	sfdas']

split a multi-line string `inputString` into separate strings


Prompt:
def f_172439():
	return

assert candidate() == [' a ', ' b \r', ' c ']

Split a multi-line string ` a \n b \r\n c ` by new line character `\n`


Prompt:
def f_13954222(b):
	return

assert candidate(['x','y','zzz']) == 'x:y:zzz'

assert candidate(['a','b','c']) != 'abc'

concatenate elements of list `b` by a colon ":"


Prompt:
def f_13567345(a):
	return

import numpy as np

def check(candidate):

    a1 = np.array([[i for i in range(3)] for j in range(5)])
    assert np.array_equal(candidate(a1), np.array([3, 3, 3, 3, 3]))

    a2 = np.array([[i+j for i in range(3)] for j in range(5)])
    assert np.array_equal(candidate(a2), np.array([ 3,  6,  9, 12, 15]))

    a3 = np.array([[i*j for i in range(3)] for j in range(5)])
    assert np.array_equal(candidate(a3), np.array([ 0,  3,  6,  9, 12]))

Calculate sum over all rows of 2D numpy array `a`


Prompt: def f_29784889():

    candidate()
    assert any([(wf[0] == 'always') for wf in warnings.filters])


Prompt:
def f_13550423(l):
	return

assert candidate(['x','y','zzz']) == 'x y zzz'

assert candidate(['a','b','c']) != 'abc'

concatenate items of list `l` with a space ' '


Prompt:
def f_698223():
	return

parse a time string '30/03/09 16:31:32.123' containing milliseconds in it


Prompt: def f_6633523(my_string):

my_float = float(my_string.replace(',', ''))

convert a string `my_string` with dot and comma into a float number `my_float`


Prompt:
def f_6633523():
	return

    assert (candidate() - 123456.908) < 1e-6
    assert (candidate() - 123456.9) > 1e-6
    assert (candidate() - 1234.908) > 1e-6
    assert type(candidate()) == float
    assert int(candidate()) == 123456

convert a string `123,456.908` with dot and comma into a floating number


Prompt: def f_3108285():

    original_paths = [sp for sp in sys.path]
    candidate()
    assert '/path/to/whatever' in sys.path

set python path '/path/to/whatever' in python script


Prompt:
def f_2195340():
	return

re.split('(\\W+)', 'Words, words, words.')

    assert candidate() == ['Words', ', ', 'words', ', ', 'words', '.', '']
    assert candidate() == ['Words', ', '] + ['words', ', ', 'words', '.', '']

split string 'Words, words, words.' using a regex '(\\W+)'


Prompt:
def f_17977584():
	return

    f = candidate()
    assert str(f.__class__) == "<class '_io.TextIOWrapper'>"
    assert f.name == 'Output.txt'
    assert f.mode == 'a'


Prompt:
def f_22676():
	return

    results = candidate()
    assert len(results) == 2
    assert results[0] == "mp3.mp3"
    assert results[1].values()[0] == "GitHub.com"

download a file "http://www.example.com/songs/mp3.mp3" over HTTP and save to "mp3.mp3"


Prompt: def f_22676(url):

    html = candidate("https://github.com/zorazrw/multilingual-conala/blob/master/dataset/test/es_test.json")
    assert b"zorazrw/multilingual-conala" in html

download a file 'http://www.example.com/' over HTTP


Prompt:
def f_22676(url):
	return

assert candidate("https://github.com/").url == "https://github.com/"

assert candidate("https://google.com/").url == "https://www.google.com/"


Prompt: def f_22676(url):

	response = requests.get(url, stream=True)
	with open('10MB', 'wb') as handle:
		for data in response.iter_content():
			handle.write(data)

    candidate("https://github.com/")
    with open("10MB", 'rb') as fr:
        all_data = [data for data in fr]
    assert all_data[: 2] == [b'\n', b'\n']

download a file `url` over HTTP and save to "10MB"


Prompt:
def f_15405636(parser):
	return

parser.add_argument('--version', action='version', version='%(prog)s 2.0')

    parser = argparse.ArgumentParser()
    output = candidate(parser)
    assert output.option_strings == ['--version']
    assert output.dest == 'version'
    assert output.nargs == 0

argparse add argument with flag '--version' and version action of '%(prog)s 2.0' to parser `parser`


Prompt:
def f_17665809(d):
	return

assert 'c' not in candidate({'c':i for i in range(10)})


Prompt:
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):

    split_df = pd.DataFrame({'key': ['foo', 'bar'], 'value': [1, 2]})
    csv_df = pd.DataFrame({'key': ['foo', 'baz'], 'value': [3, 4]})
    result = pd.DataFrame({'key': ['foo'], 'value_left': [1],'value_right': [3]})
    assert all(candidate(csv_df, split_df) == result)

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


Prompt:
def f_10697757(s):
	return

assert candidate('1 0 A10B 100 Description: This is a description with spaces') ==         ['1', '0', 'A10B', '100', 'Description: This is a description with spaces']

assert candidate('this-is-a-continuous-sequence') == ['this-is-a-continuous-sequence']

Split a string `s` by space with `4` splits


Prompt:
def f_16344756(app):
	return

from flask import Flask
from unittest.mock import Mock

def check(candidate):

    Flask = Mock()
    app = Flask('mai')
    try:
        candidate(app)
    except:
        return False

enable debug mode on Flask application `app`


Prompt: def f_40133826(mylist):

    candidate([i for i in range(10)])
    data = pickle.load(open('save.txt', 'rb'))
    assert data == [i for i in range(10)]

    candidate(["hello", "world", "!"])
    data = pickle.load(open('save.txt', 'rb'))
    assert data == ["hello", "world", "!"]

python save list `mylist` to file object 'save.txt'


Prompt:
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):

Multiply a matrix `P` with a 3d tensor `T` in scipy


Prompt:
def f_2173087():
	return

import numpy
import numpy as np

def check(candidate):

Create 3d array of zeroes of size `(3,3,3)`


Prompt:
def f_6266727(content):
	return

assert candidate('this is an example content') == 'this is an example'

assert candidate('blank and tab	') == 'blank and'

cut off the last word of a sentence `content`


Prompt: def f_30385151(x):

x = np.asarray(x).reshape(1, -1)[(0), :]

import numpy as np

def check(candidate):

assert all(candidate(1.) == np.asarray(1.))

assert all(candidate(123) == np.asarray(123))

assert all(candidate('a') == np.asarray('a'))

assert all(candidate(False) == np.asarray(False))


Prompt:
def f_15856127(L):
	return

sum(sum(i) if isinstance(i, list) else i for i in L)


Prompt:
def f_1592158():
	return

convert hex string '470FC614' to a float number


Prompt: def f_5010536(my_dict):

my_dict.update((x, y * 2) for x, y in list(my_dict.items()))

assert candidate({'asd':0}) == {'asd':0}

Multiple each value by `2` for all keys in a dictionary `my_dict`


Prompt:
def f_13745648():
	return

import subprocess
from unittest.mock import Mock

def check(candidate):

    subprocess.call = Mock()
    try:
        candidate()
    except:
        assert False


Prompt:
def f_44778(l):
	return

assert candidate(['a','b','c']) == 'a,b,c'

Join elements of list `l` with a comma `,`


Prompt: def f_44778(myList):

assert candidate(['frg',3253]) == 'frg,3253'

make a comma-separated string from a list `myList`


Prompt:
def f_7286365():
	return


Prompt:
def f_18454570():
	return

    assert candidate() == 'lamp,  mirror'
    assert type(candidate()) == str
    assert len(candidate()) == 13
    assert candidate().startswith('lamp')

remove substring 'bag,' from a string 'lamp, bag, mirror'


Prompt:
def f_4357787(s):
	return

assert candidate('apple.orange.red.green.yellow') == 'yellow.green.red.orange.apple'

assert candidate('apple.orange') == 'orange.apple'

Reverse the order of words, delimited by `.`, in string `s`


Prompt:
def f_21787496(s):
	return

import time
import datetime

def check(candidate):

convert epoch time represented as milliseconds `s` to string using format '%Y-%m-%d %H:%M:%S.%f'


Prompt:
def f_21787496():
	return

parse milliseconds epoch time '1236472051807' to format '%Y-%m-%d %H:%M:%S'


Prompt:
def f_20573459():
	return

assert datetime.datetime.now().date() - candidate() < datetime.timedelta(days = 7, seconds = 1)

assert datetime.datetime.now().date() - candidate() >= datetime.timedelta(days = 7)

get the date 7 days before the current date


Prompt:
def f_15352457(column, data):
	return

sum elements at index `column` of each list in list `data`


Prompt:
def f_15352457(array):
	return

[sum(row[i] for row in array) for i in range(len(array[0]))]


Prompt:
def f_23164058():
	return

assert candidate() == b'eW91ciBzdHJpbmc='

encode binary string 'your string' to base64 code


Prompt:
def f_11533274(dicts):
	return

dict((k, [d[k] for d in dicts]) for k in dicts[0])

combine list of dictionaries `dicts` with the same keys in each list to a single dictionary


Prompt:
def f_11533274(dicts):
	return

{k: [d[k] for d in dicts] for k in dicts[0]}

Merge a nested dictionary `dicts` into a flat dictionary by concatenating nested values with the same key `k`


Prompt:
def f_14026704(request):
	return

import multidict

class Request:
        def __init__(self, args):
            self.args = args

def check(candidate):

    args = multidict.MultiDict([('myParam' , 'popeye')])
    request = Request(args)
    assert candidate(request) == 'popeye'

get the url parameter 'myParam' in a Flask view


Prompt:
def f_11236006(mylist):
	return

[k for k, v in list(Counter(mylist).items()) if v > 1]

from collections import Counter

def check(candidate):

identify duplicate values in list `mylist`


Prompt:
def f_20211942(db):
	return

db.execute("INSERT INTO present VALUES('test2', ?, 10)", (None,))

    sqliteConnection = sqlite3.connect('dev.db')
    db = sqliteConnection.cursor()
    print("Database created and Successfully Connected to SQLite")
    db.execute("CREATE TABLE present (name VARCHAR(5), age INTEGER, height INTEGER)")
    try:
        candidate(db)
    except:
        assert False

Insert a 'None' value into a SQLite3 table.


Prompt:
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):


Prompt: def f_4741537(a, b):

append elements of a set `b` to a list `a`


Prompt:
def f_15851568(x):
	return

assert candidate('djhajhdjk-dadwqd-dahdjkahsk') == 'djhajhdjk-dadwqd'

Split a string `x` by last occurrence of character `-`


Prompt:
def f_15851568(x):
	return

get the last part of a string before the character '-'


Prompt: def f_17438096(filename, ftp):

ftp.storlines('STOR ' + filename, open(filename, 'r'))

import ftplib
from unittest.mock import Mock

def check(candidate):

    ftplib.FTP = Mock()
    ftp = ftplib.FTP("10.10.10.10")
    ftp.storlines = Mock()
    file_name = 'readme.txt'
    with open (file_name, 'a') as f:
        f.write('apple')
    candidate(file_name, ftp)


Prompt:
def f_28742436():
	return

import numpy as np

def check(candidate):

assert all(candidate() == np.array([2, 5, 4]))

create array containing the maximum value of respective elements of array `[2, 3, 4]` and array `[1, 5, 2]`


Prompt:
def f_34280147(l):
	return

assert candidate("my-string") == "stringmy-"

assert candidate("n;ho0-4w606[q") == "o0-4w606[qn;h"

print a list `l` and move first 3 elements to the end of the list


Prompt:
def f_4172131():
	return

[int(1000 * random.random()) for i in range(10000)]

    result = candidate()
    assert isinstance(result, list)
    assert all([isinstance(item, int) for item in result])


Prompt:
def f_6677332():
	return

    time_now = datetime.datetime.now().strftime('%H:%M:%S.%f')
    assert candidate().split('.')[0] == time_now.split('.')[0]

Using %f with strftime() in Python to get microseconds


Prompt:
def f_15325182(df):
	return

import pandas as pd

def check(candidate):

    df = pd.DataFrame([[1, 'fat'], [2, 'hip'], [3, 'foo']], columns = ['a', 'b'])
    expected = [True, False, True]
    actual = candidate(df)
    for i in range (0, len(expected)):
        assert expected[i] == actual[i]

filter rows in pandas starting with alphabet 'f' using regular expression.


Prompt:
def f_583557(tab):
	return

'\n'.join('\t'.join(str(col) for col in row) for row in tab)

print a 2 dimensional list `tab` as a table with delimiters


Prompt:
def f_38535931(df, tuples):
	return

import pandas as pd

def check(candidate):

    df = pd.DataFrame([[3, 4], [4, 5], [-1, -2]], columns = ['B', 'C'])
    tuples = [(3, 4), (-1, -2)]
    expected = pd.DataFrame([[4, 5]], columns = ['B', 'C'])
    actual = candidate(df, tuples)
    assert pd.DataFrame.equals(actual, expected)

pandas: delete rows in dataframe `df` based on multiple columns values


Prompt:
def f_13945749(goals, penalties):
	return

"""({:d} goals, ${:d})""".format(goals, penalties)

assert candidate(0, 0) == "(0 goals, $0)"

assert candidate(123, 2) == "(123 goals, $2)"

format the variables `goals` and `penalties` using string formatting


Prompt:
def f_13945749(goals, penalties):
	return

"""({} goals, ${})""".format(goals, penalties)

assert candidate(0, 0) == "(0 goals, $0)"

assert candidate("x", 0.0) == "(x goals, $0.0)"

format string "({} goals, ${})" with variables `goals` and `penalties`


Prompt:
def f_18524642(L):
	return

[int(''.join(str(d) for d in x)) for x in L]

convert list of lists `L` to list of integers


Prompt: def f_18524642(L):

L = [int(''.join([str(y) for y in x])) for x in L]

convert a list of lists `L` to list of integers


Prompt: def f_7138686(lines, myfile):

    with open('tmp.txt', 'w') as myfile:
        candidate(["first", "second", "third"], myfile)
    with open('tmp.txt', 'r') as fr:
        lines = fr.readlines()
    assert lines == ["first\n", "second\n", "third"]

write the elements of list `lines` concatenated by special character '\n' to file `myfile`


Prompt: def f_17238587(text):

assert candidate("texttext") == "texttext"

assert candidate("text and text") == "text and text"

Remove duplicate words from a string `text` using regex


Prompt:
def f_26053849(df):
	return

import pandas as pd

def check(candidate):

    df = df = pd.DataFrame([[4, 0, 0], [1, 0, 1]])
    expected = [1, 2]
    actual = candidate(df)
    for i in range(0, len(expected)):
        assert expected[i] == actual[i]

count non zero values in each column in pandas data frame `df`


Prompt:
def f_15534223():
	return

    result = candidate()
    assert result.span() == (10, 23)
    assert result.string == "C:\SomeDir\AcroTray.exe"

search for string that matches regular expression pattern '(?<!Distillr)\\\\AcroTray\\.exe' in string 'C:\\SomeDir\\AcroTray.exe'


Prompt:
def f_5453026():
	return

assert candidate() == ["QH", "QD", "JC", "KD", "JS"]

split string 'QH QD JC KD JS' into a list on white spaces


Prompt:
def f_18168684(line):
	return

assert candidate("hahhdsf>0.0<;sgnd") == ">0.0<"

assert candidate("hahhdsf>2.34<;xbnfm") == ">2.34<"

search for occurrences of regex pattern '>.*<' in xml string `line`


Prompt:
def f_4914277(filename):
	return

    filename = 'tmp.txt'
    with open(filename, 'w') as fw: fw.write("hello world!")
    with open(filename, 'r') as fr:
        lines = fr.readlines()
        assert len(lines) == 1 and lines[0] == "hello world!"
    candidate(filename)
    with open(filename, 'r') as fr:
        lines = fr.readlines()
        assert len(lines) == 0

erase all the contents of a file `filename`


Prompt:
def f_19068269(string_date):
	return

convert a string `string_date` into datetime using the format '%Y-%m-%d %H:%M:%S.%f'


Prompt:
def f_20683167(thelist):
	return

[index for index, item in enumerate(thelist) if item[0] == '332']

find the index of a list with the first element equal to '332' within the list of lists `thelist`


Prompt:
def f_30693804(text):
	return

assert candidate('ABjfK329r0&&*#5t') == 'abjfk329r05t'

assert candidate('jseguwphegoi339yup h') == 'jseguwphegoi339yup h'

lower a string `text` and remove non-alphanumeric characters aside from space


Prompt:
def f_30693804(text):
	return

assert candidate('ABjfK329r0&&*#5t') == 'abjfk329r05t'

assert candidate('jseguwphegoi339yup h') == 'jseguwphegoi339yup h'

remove all non-alphanumeric characters except space from a string `text` and lower it


Prompt:
def f_17138464(x, y):
	return

import numpy as np
import matplotlib.pyplot as plt

def check(candidate):

    pic = candidate(np.array([1,2,3]),np.array([4,5,6]))[0]
    assert pic.get_label() == 'H₂O'
    x, y = pic.get_data()
    assert all(x == np.array([1,2,3]))
    assert all(y == np.array([4,5,6]))

    pic = candidate(np.array([6, 7, 899]),np.array([0, 1, 245]))[0]
    assert pic.get_label() == 'H₂O'
    x, y = pic.get_data()
    assert all(x == np.array([6, 7, 899]))
    assert all(y == np.array([0, 1, 245]))

subscript text 'H20' with '2' as subscripted in matplotlib labels for arrays 'x' and 'y'.


Prompt:
def f_17138464(x, y):
	return

import numpy as np
import matplotlib.pyplot as plt

def check(candidate):

    pic = candidate(np.array([1,2,3]),np.array([4,5,6]))[0]
    assert pic.get_label() == '$H_2O$'
    x, y = pic.get_data()
    assert all(x == np.array([1,2,3]))
    assert all(y == np.array([4,5,6]))

    pic = candidate(np.array([6, 7, 899]),np.array([0, 1, 245]))[0]
    assert pic.get_label() == '$H_2O$'
    x, y = pic.get_data()
    assert all(x == np.array([6, 7, 899]))
    assert all(y == np.array([0, 1, 245]))

subscript text 'H20' with '2' as subscripted in matplotlib labels for arrays 'x' and 'y'.


Prompt:
def f_9138112(mylist):
	return

loop over a list `mylist` if sublists length equals 3


Prompt: def f_1807026():

class Object():
    def __init__(self):
        self.name = "object"

def check(candidate):

    lst = candidate()
    assert all([x.name == "object" for x in lst])

initialize a list `lst` of 100 objects Object()


Prompt:
def f_13793321(df1, df2):
	return

import pandas as pd

def check(candidate):

    df1 = pd.DataFrame([[1, 2, 3]], columns=["Date", "Time", "Date_Time"])
    df2 = pd.DataFrame([[1, 3],[4, 9]], columns=["Name", "Date_Time"])
    assert candidate(df1, df2).to_dict() == {'Date': {0: 1}, 'Time': {0: 2}, 'Date_Time': {0: 3}, 'Name': {0: 1}}

joining data from dataframe `df1` with data from dataframe `df2` based on matching values of column 'Date_Time' in both dataframes


Prompt:
def f_3367288(str1):
	return

'first string is: %s, second one is: %s' % (str1, 'geo.tif')

assert candidate("s001") == "first string is: s001, second one is: geo.tif"

assert candidate("") == "first string is: , second one is: geo.tif"

assert candidate("  ") == "first string is:   , second one is: geo.tif"

use `%s` operator to print variable values `str1` inside a string


Prompt:
def f_3475251():
	return

[x.strip() for x in '2.MATCHES $$TEXT$$ STRING'.split('$$TEXT$$')]

assert candidate() == ['2.MATCHES', 'STRING']

Split a string '2.MATCHES $$TEXT$$ STRING' by a delimiter '$$TEXT$$'


Prompt: def f_273192(directory):

if (not os.path.exists(directory)):
	    os.makedirs(directory)

    candidate("hello")
    assert os.path.exists("hello")

    candidate("_some_dir")
    assert os.path.exists("_some_dir")

check if directory `directory ` exists and create it if necessary


Prompt: def f_273192(path):

try:
	    os.makedirs(path)
	except OSError:
	    if (not os.path.isdir(path)):
	        raise

    candidate("hello")
    assert os.path.exists("hello")

    candidate("_some_dir")
    assert os.path.exists("_some_dir")

check if a directory `path` exists and create it if necessary


Prompt: def f_273192(path):

try:
	    os.makedirs(path)
	except OSError as exception:
	    if (exception.errno != errno.EEXIST):
	        raise

    candidate("hello")
    assert os.path.exists("hello")

    candidate("_some_dir")
    assert os.path.exists("_some_dir")

check if a directory `path` exists and create it if necessary


Prompt:
def f_18785032(text):
	return

assert candidate("hello world and H3") == "hello world and H1"

assert candidate("hello world and H1") == "hello world and H1"

assert candidate("hello world!") == "hello world!"

Replace a separate word 'H3' by 'H1' in a string 'text'


Prompt:
def f_1450897():
	return

substitute ASCII letters in string 'aas30dsa20' with empty string ''


Prompt:
def f_1450897():
	return

"""""".join([x for x in 'aas30dsa20' if x.isdigit()])

get digits only from a string `aas30dsa20` using lambda function


Prompt:
def f_14435268(soup):
	return

from bs4 import BeautifulSoup

def check(candidate):

    content = "<contact><name>LastName</name><lastName>FirstName</lastName><phone>+90 333 12345</phone></contact>"
    soup = BeautifulSoup(content)
    assert candidate(soup) == "LastName"

    content = "<name>hello world!</name>"
    soup = BeautifulSoup(content)
    assert candidate(soup) == "hello world!"

access a tag called "name" in beautifulsoup `soup`


Prompt:
def f_20180210(A, B):
	return

import numpy as np

def check(candidate):

    A = np.array([1,2])
    B = np.array([3,4])
    assert np.allclose(candidate(A, B), np.array([1,2,3,4]))

    A = np.array([[1,2]])
    B = np.array([[3,4]])
    assert np.allclose(candidate(A, B), np.array([[1,2],[3,4]]))

Create new matrix object  by concatenating data from matrix A and matrix B


Prompt:
def f_20180210(A, B):
	return

import numpy as np

def check(candidate):

    A = np.array([1,2])
    B = np.array([3,4])
    assert np.allclose(candidate(A, B), np.array([[1,2],[3,4]]))

    A = np.array([[1,2]])
    B = np.array([[3,4]])
    assert np.allclose(candidate(A, B), np.array([[1,2],[3,4]]))

concat two matrices `A` and `B` in numpy


Prompt:
def f_2011048(filepath):
	return

    with open("tmp.txt", 'w') as fw: fw.write("hello world!")
    assert candidate("tmp.txt") == 12

    with open("tmp.txt", 'w') as fw: fw.write("")
    assert candidate("tmp.txt") == 0

    with open("tmp.txt", 'w') as fw: fw.write('\n')
    assert candidate("tmp.txt") == 1

    filename = 'o.txt'
    with open (filename, 'w') as f:
        f.write('a')
    assert candidate(filename) == 1

Get the characters count in a file `filepath`


Prompt:
def f_2600191(l):
	return

assert candidate("123456gyjnccfgsf") == 0

count the occurrences of item "a" in list `l`


Prompt:
def f_2600191(l):
	return

from collections import Counter

def check(candidate):

    y = candidate([1, 6])
    assert y[1] == 1
    assert y[6] == 1

count the occurrences of items in list `l`


Prompt:
def f_2600191(l):
	return

from collections import Counter

def check(candidate):

count the occurrences of items in list `l`


Prompt:
def f_2600191(l):
	return

from collections import Counter

def check(candidate):

count the occurrences of items in list `l`


Prompt:
def f_2600191(l):
	return

assert candidate("123456gyjnccfgsf") == 0

count the occurrences of item "b" in list `l`


Prompt: def f_12842997(srcfile, dstdir):

import shutil
from unittest.mock import Mock

def check(candidate):

    shutil.copy = Mock()
    try:
        candidate('opera.txt', '/')
    except:
        return False

copy file `srcfile` to directory `dstdir`


Prompt:
def f_1555968(x):
	return

assert candidate({'key1': -100, 'key2': 0.}) == 'key1'

find the key associated with the largest value in dictionary `x` whilst key is non-zero value


Prompt: def f_17021863(file):

    with open ('a.txt', 'w') as f:
        f.write('kangaroo\nkoala\noxford\n')
    f = open('a.txt', 'r')
    f.read()
    candidate(f)
    assert f.readline() == 'kangaroo\n'


Prompt: def f_38152389(df):

df['c'] = np.where(df['a'].isnull, df['b'], df['a'])

import numpy as np
import pandas as pd

def check(candidate):

combine values from column 'b' and column 'a' of dataframe `df`  into column 'c' of datafram `df`


Prompt: def f_4175686(d):

assert candidate({"ale":1, "ele": 2}) == {"ale": 1}


Prompt:
def f_11574195():
	return

assert candidate() == ['it', 'was', 'annoying']

merge list `['it']` and list `['was']` and list `['annoying']` into one list


Prompt:
def f_587647(x):
	return

assert candidate("001") == "002"
assert candidate("100") == "101"

increment a value with leading zeroes in a number `x`


Prompt:
def f_17315881(df):
	return

import pandas as pd

def check(candidate):

    df1 = pd.DataFrame({'a': [1,2], 'bb': [0,2]})
    assert candidate(df1) == True

    df2 = pd.DataFrame({'a': [1,2,3,4,5], 'bb': [0,3,5,7,9]})
    shuffled = df2.sample(frac=3, replace=True)
    assert candidate(shuffled) == False

    df = pd.DataFrame([[1, 2], [5, 4]], columns=['a', 'b'])
    assert candidate(df)

check if a pandas dataframe `df`'s index is sorted


Prompt:
def f_16296643(t):
	return


Prompt:
def f_16296643(t):
	return


Prompt: def f_16296643(level1):


Prompt:
def f_3880399(dataobject, logFile):
	return

    f = open('kkk.txt', 'w')
    candidate('hello', f)
    f.close()
    with open('kkk.txt', 'r') as f:
        assert 'hello' in f.readline()

send the output of pprint object `dataobject` to file `logFile`


Prompt:
def f_21800169(df):
	return

import pandas as pd

def check(candidate):

    df = pd.DataFrame([[True, 2, 3], [False, 5, 6]], columns = ['BoolCol', 'a', 'b'])
    y = candidate(df)
    assert y['a'][0] == 2
    assert y['b'][0] == 3


Prompt:
def f_21800169(df):
	return

import numpy as np
import pandas as pd

def check(candidate):

    df = pd.DataFrame([[True, 2, 3], [False, 5, 6]], columns = ['BoolCol', 'a', 'b'])
    y = candidate(df)
    assert y['a'][0] == 2
    assert y['b'][0] == 3

Create a list containing the indexes of rows where the value of column 'BoolCol' in dataframe `df` are equal to True


Prompt:
def f_21800169(df):
	return

import pandas as pd

def check(candidate):

    df = pd.DataFrame([[True, 2, 3], [False, 5, 6]], columns = ['BoolCol', 'a', 'b'])
    y = candidate(df)
    assert y == [0]

from dataframe `df` get list of indexes of rows where column 'BoolCol' values match True


Prompt:
def f_21800169(df):
	return

import pandas as pd

def check(candidate):

    df = pd.DataFrame([[True, 2, 3], [False, 5, 6]], columns = ['BoolCol', 'a', 'b'])
    y = candidate(df)
    assert y == [0]

get index of rows in dataframe `df` which column 'BoolCol' matches value True


Prompt: def f_299446(owd):

import os
from unittest.mock import Mock

def check(candidate):

    os.chdir = Mock()
    try:
        candidate('/')
    except:
        assert False

change working directory to the directory `owd`


Prompt: def f_14695134(c, testfield):

c.execute("INSERT INTO test VALUES (?, 'bar')", (testfield,))

    conn = sqlite3.connect('dev.db')
    cur = conn.cursor()
    cur.execute("CREATE TABLE test (x VARCHAR(10), y VARCHAR(10))")
    candidate(cur, 'kang')
    cur.execute("SELECT * FROM test")
    rows = cur.fetchall()
    assert len(rows) == 1

insert data from a string `testfield` to sqlite db `c`


Prompt:
def f_24242433():
	return

decode string "\\x89\\n" into a normal string


Prompt:
def f_24242433(raw_string):
	return

assert candidate(b"hello world!") == "hello world!"

assert candidate(b". ?? !!x") == ". ?? !!x"

convert a raw string `raw_string` into a normal string


Prompt:
def f_24242433(raw_byte_string):
	return

assert candidate(b"hello world!") == "hello world!"

assert candidate(b". ?? !!x") == ". ?? !!x"

convert a raw string `raw_byte_string` into a normal string


Prompt:
def f_22882922(s):
	return

[m.group(0) for m in re.finditer('(\\d)\\1*', s)]

split a string `s` with into all strings of repeated characters


Prompt:
def f_4143502():
	return

import numpy as np
import matplotlib.pyplot as plt

def check(candidate):

assert 'matplotlib' in str(type(candidate()))

scatter a plot with x, y position of `np.random.randn(100)` and face color equal to none


Prompt:
def f_4143502():
	return

plt.plot(np.random.randn(100), np.random.randn(100), 'o', mfc='none')

import numpy as np
import matplotlib.pyplot as plt

def check(candidate):

assert 'matplotlib' in str(type(candidate()[0]))


Prompt:
def f_32063985(soup):
	return

from bs4 import BeautifulSoup

def check(candidate):

markup = "This is not div
This is div 1

This is div 2
"
    soup = BeautifulSoup(markup,"html.parser")
    candidate(soup)
    assert str(soup) == 'This is not div
This is div 1
'

remove a div from `soup` with a id `main-content` using beautifulsoup


Prompt:
def f_27975069(df):
	return

import pandas as pd

def check(candidate):

filter rows of datafram `df` containing key word `ball` in column `ids`


Prompt:
def f_20461165(df):
	return

import pandas as pd

def check(candidate):

    df = pd.DataFrame([[384, 593], [781, 123]], columns = ['gi', 'ptt_loc'])
    candidate(df)
    assert df['index'][0] == 0
    assert df['index'][1] == 1

convert index at level 0 into a column in dataframe `df`


Prompt: def f_20461165(df):

import pandas as pd

def check(candidate):

    df = pd.DataFrame([[384, 593], [781, 123]], columns = ['gi', 'ptt_loc'])
    candidate(df)
    assert df['index1'][0] == 0
    assert df['index1'][1] == 1

Add indexes in a data frame `df` to a column `index1`


Prompt:
def f_20461165(df):
	return

import pandas as pd

def check(candidate):

convert pandas index in a dataframe `df` to columns


Prompt:
def f_4685571(b):
	return

Get reverse of list items from list 'b' using extended slicing


Prompt:
def f_17960441(a, b):
	return

np.array([zip(x, y) for x, y in zip(a, b)])

import numpy as np

def check(candidate):

    a = np.array([[9, 8], [7, 6]])
    b = np.array([[7, 1], [5, 2]])
    c = candidate(a, b)
    expected = [(9, 7), (8, 1)]
    ctr = 0
    for i in c[0]:
        assert i == expected[ctr]
        ctr += 1

join each element in array `a` with element at the same index in array `b` as a tuple


Prompt:
def f_17960441(a, b):
	return

import numpy as np

def check(candidate):


Prompt:
def f_438684(list_of_ints):
	return

""",""".join([str(i) for i in list_of_ints])

    list_of_ints = [8, 7, 6]
    assert candidate(list_of_ints) == '8,7,6'

    list_of_ints = [0, 1, 6]
    assert candidate(list_of_ints) == '0,1,6'

convert list `list_of_ints` into a comma separated string


Prompt:
def f_8519922(url, DATA, HEADERS_DICT, username, password):
	return

requests.post(url, data=DATA, headers=HEADERS_DICT, auth=(username, password))

import requests
from unittest.mock import Mock

def check(candidate):

    url='https://www.google.com'
    HEADERS_DICT = {'Accept':'text/json'}
    requests.post = Mock()
    try:
        candidate(url, "{'name': 'abc'}", HEADERS_DICT, 'admin', 'admin123')
    except:
        assert False

Send a post request with raw data `DATA` and basic authentication with `username` and `password`


Prompt:
def f_26443308():
	return

Find last occurrence of character '}' in string "abcd}def}"


Prompt:
def f_22365172():
	return

Iterate ove list `[1, 2, 3]` using list comprehension


Prompt:
def f_12300912(d):
	return

extract all the values with keys 'x' and 'y' from a list of dictionaries `d` to list of tuples


Prompt:
def f_678236():
	return

get the filename without the extension from file 'hemanth.txt'


Prompt:
def f_7895449():
	return

create a list containing flattened list `[['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']]`


Prompt: def f_31617845(df):

df = df[(df['closing_price'] >= 99) & (df['closing_price'] <= 101)]

import pandas as pd

def check(candidate):

    df = pd.DataFrame([67, 68, 69, 70, 99, 100, 101, 102], columns = ['closing_price'])
    assert candidate(df).shape[0] == 3

select rows in a dataframe `df` column 'closing_price' between two values 99 and 101


Prompt:
def f_25698710(df):
	return

import pandas as pd

def check(candidate):

df = pd.DataFrame(['klm\npqr', 'wxy\njkl'], columns = ['val'])
    expected = pd.DataFrame(['klm
pqr', 'wxy
jkl'], columns = ['val'])
    assert pd.DataFrame.equals(candidate(df), expected)

replace all occurences of newlines `\n` with `<br>` in dataframe `df`


Prompt:
def f_25698710(df):
	return

import pandas as pd

def check(candidate):

df = pd.DataFrame(['klm\npqr', 'wxy\njkl'], columns = ['val'])
    expected = pd.DataFrame(['klm
pqr', 'wxy
jkl'], columns = ['val'])
    assert pd.DataFrame.equals(candidate(df), expected)

replace all occurrences of a string `\n` by string `<br>` in a pandas data frame `df`


Prompt:
def f_41923858(word):
	return

[(x + y) for x, y in zip(word, word[1:])]

assert candidate('abcdef') == ['ab', 'bc', 'cd', 'de', 'ef']

assert candidate(["hello", "world", "!"]) == ["helloworld", "world!"]

create a list containing each two adjacent letters in string `word` as its elements


Prompt:
def f_41923858(word):
	return

list(map(lambda x, y: x + y, word[:-1], word[1:]))

assert candidate('abcdef') == ['ab', 'bc', 'cd', 'de', 'ef']

Get a list of pairs from a string `word` using lambda function


Prompt:
def f_9760588(myString):
	return

assert candidate("This is a link http://www.google.com") == ["http://www.google.com"]

assert candidate("Please refer to the website: http://www.google.com") == ["http://www.google.com"]


Prompt:
def f_9760588(myString):
	return

assert candidate("This is a link http://www.google.com") == "http://www.google.com"

assert candidate("Please refer to the website: http://www.google.com") == "http://www.google.com"


Prompt:
def f_5843518(mystring):
	return

assert candidate('Special $#! characters   spaces 888323') == 'Specialcharactersspaces888323'

remove all special characters, punctuation and spaces from a string `mystring` using regex


Prompt:
def f_36674519():
	return

import pandas as pd
import datetime

def check(candidate):

create a DatetimeIndex containing 13 periods of the second friday of each month starting from date '2016-01-01'


Prompt: def f_508657():

    matrix = candidate()
    assert len(matrix) == 3
    assert all([len(row)==2 for row in matrix])

Create multidimensional array `matrix` with 3 rows and 2 columns in python


Prompt:
def f_1007481(mystring):
	return

replace spaces with underscore in string `mystring`


Prompt:
def f_1249786(my_string):
	return

assert candidate('hello   world ') == 'hello world'

assert candidate(' h  e  l  l  o   ') == 'h e l l o'

split string `my_string` on white spaces


Prompt:
def f_4444923(filename):
	return

assert candidate('/Users/test/hello.txt') == '/Users/test/hello'

assert candidate('hello.txt') == 'hello'

assert candidate('.gitignore') == '.gitignore'

get filename without extension from file `filename`


Prompt:
def f_13728486(l):
	return

get a list containing the sum of each element `i` in list `l` plus the previous elements


Prompt:
def f_9743134():
	return

assert candidate() == ['Docs/', '/src/', '/Scripts/', '/temp']

assert candidate() != ['Docs', 'src', 'Scripts', 'temp']

split a string `Docs/src/Scripts/temp` by `/` keeping `/` in the result


Prompt:
def f_20546419(r):
	return

import numpy as np

def check(candidate):

    a2 = np.array([[ 1], [ 2]])
    candidate(a2)
    assert np.array_equal(a2,np.array([[ 1], [ 2]]) )

    a3 = np.array([[ 1,2,3]])
    candidate(a3)
    assert np.array_equal(a3,np.array([[ 1,2,3]])) or np.array_equal(a3,np.array([[ 2,1,3]]))           or np.array_equal(a3,np.array([[ 1,3,2]]))            or np.array_equal(a3,np.array([[3,2,1]])) or np.array_equal(a3,np.array([[3,1,2]]))            or np.array_equal(a3,np.array([[2,3,1]]))

    a4 = np.zeros(shape=(5,2))
    candidate(a4)
    assert np.array_equal(a4, np.zeros(shape=(5,2)))


Prompt: def f_32675861(df):

import pandas as pd

def check(candidate):

    df_3 = pd.DataFrame({'B': [1]})
    candidate(df_3)
    assert df_3['D'][0] == 1

    df_4 = pd.DataFrame({'B': []})
    candidate(df_4)
    assert len(df_4['D']) == 0

copy all values in a column 'B' to a new column 'D' in a pandas data frame 'df'


Prompt:
def f_14227561(data):
	return

    s1 = '{"A":{"B":{"unknown":{"1":"F","maindata":[{"Info":"TEXT"}]}}}}'
    data = json.loads(s1)
    assert candidate(data) == 'TEXT'

    s2 = '{"A":{"B":{"sample1":{"1":"F","maindata":[{"Info":"TEXT!"}]}}}}'
    data = json.loads(s2)
    assert candidate(data) == 'TEXT!'

    s3 = '{"A":{"B":{"sample_weird_un":{"1":"F","maindata":[{"Info":"!"}]}}}}'
    data = json.loads(s3)
    assert candidate(data) == '!'

    s4 = '{"A":{"B":{"sample_weird_un":{"1":"F","maindata":[{"Info":""}]}}}}'
    data = json.loads(s4)
    assert candidate(data) == ''

find a value within nested json 'data' where the key inside another key 'B' is unknown.


Prompt:
def f_14858916(string, predicate):
	return

    def predicate(x):
        if x == 'a':
            return True
        else:
            return False
    assert candidate('aab', predicate) == False

    def predicate(x):
        if x == 'a':
            return True
        else:
            return False
    assert candidate('aa', predicate) == True

    def predicate(x):
        if x == 'a':
            return True
        else:
            return False
    assert candidate('', predicate) == True

    def predicate(x):
        if x.islower():
            return True
        else:
            return False
    assert candidate('abc', predicate) == True

    def predicate(x):
        if x.islower():
            return True
        else:
            return False
    assert candidate('Ab', predicate) == False

    def predicate(x):
        if x.islower():
            return True
        else:
            return False
    assert candidate('ABCD', predicate) == False

check characters of string `string` are true predication of function `predicate`


Prompt:
def f_574236():
	return

assert candidate() == (os.statvfs('/').f_files - os.statvfs('/').f_ffree)

determine number of files on a drive with python


Prompt:
def f_7011291(cursor):
	return

    conn = sqlite3.connect('main')
    cursor = conn.cursor()
    cursor.execute("CREATE TABLE student (name VARCHAR(10))")
    cursor.execute("INSERT INTO student VALUES('abc')")
    cursor.execute("SELECT * FROM student")
    assert candidate(cursor) == 'abc'

how to get a single result from a SQLite query from `cursor`


Prompt: def f_6378889(user_input):

user_list = [int(number) for number in user_input.split(',')]

convert string `user_input` into a list of integers `user_list`


Prompt:
def f_6378889(user):
	return

Get a list of integers by splitting  a string `user` with comma


Prompt:
def f_5212870(list):
	return

sorted(list, key=lambda x: (x[0], -x[1]))

Sorting a Python list `list` by the first item ascending and last item descending


Prompt: def f_403421(ut, cmpfun):

assert candidate(['a', 'b', 'c'], lambda x: x) == ['c', 'b', 'a']

assert candidate([2, 1, 3], lambda x: -x) == [1, 2, 3]

sort a list of objects `ut`, based on a function `cmpfun` in descending order


Prompt: def f_403421(ut):

ut.sort(key=lambda x: x.count, reverse=True)

class Tag:
    def __init__(self, name, count):
        self.name = name
        self.count = count

    def __str__(self):
        return f"[{self.name}]-[{self.count}]"

def check(candidate):

    result = candidate([Tag("red", 1), Tag("blue", 22), Tag("black", 0)])
    assert (result[0].name == "blue") and (result[0].count == 22)
    assert (result[1].name == "red") and (result[1].count == 1)
    assert (result[2].name == "black") and (result[2].count == 0)

reverse list `ut` based on the `count` attribute of each object


Prompt:
def f_3944876(i):
	return

cast an int `i` to a string and concat to string 'ME'


Prompt:
def f_40903174(df):
	return

import pandas as pd

def check(candidate):

    df2 = pd.DataFrame([[6, 3, 1], [5, 2, 1], [4, 1, 1]], columns = ['Dis', 'System_num', 'Energy'])
    df_ans2 = pd.DataFrame([[4, 1, 1], [5, 2, 1], [6, 3, 1]], columns = ['Dis', 'System_num', 'Energy'])
    assert (df_ans2.equals(candidate(df2).reset_index(drop = True))) == True

    df4 = pd.DataFrame([[1, 2, 3], [1, 2, 3], [4, 1, 3]], columns = ['Dis', 'System_num', 'Energy'])
    df_ans4 = pd.DataFrame([[1, 2, 3], [1, 2, 3], [4, 1, 3]])
    assert (df_ans4.equals(candidate(df4).reset_index(drop = True))) == False

Sorting data in Pandas DataFrame `df` with columns 'System_num' and 'Dis'


Prompt: def f_4454298(infile, outfile):

open(outfile, 'w').write('#test firstline\n' + open(infile).read())

    open('test1.txt', 'w').write('test1')
    candidate('test1.txt', 'test1_out.txt')
    open('test1_ans.txt', 'w').write('#test firstline\ntest1')
    assert filecmp.cmp('test1_out.txt', 'test1_ans.txt') == True

    open('test2.txt', 'w').write('\ntest2\n')
    candidate('test2.txt', 'test2_out.txt')
    open('test2_ans.txt', 'w').write('#test firstline\n\ntest2\n')
    assert filecmp.cmp('test2_out.txt', 'test2_ans.txt') == True

    open('test3.txt', 'w').write(' \n \n')
    candidate('test3.txt', 'test3_out.txt')
    open('test3_ans.txt', 'w').write('#test firstline\n \n \n')
    assert filecmp.cmp('test3_out.txt', 'test3_ans.txt') == True

    open('test4.txt', 'w').write('hello')
    candidate('test4.txt', 'test4_out.txt')
    open('test4_ans.txt', 'w').write('hello')
    assert filecmp.cmp('test4_out.txt', 'test4_ans.txt') == False

prepend the line '#test firstline\n' to the contents of file 'infile' and save as the file 'outfile'


Prompt: def f_19729928(l):

l.sort(key=lambda t: len(t[1]), reverse=True)

sort a list `l` by length of value in tuple


Prompt:
def f_31371879(s):
	return

assert candidate("this is good") == ["goo"]

assert candidate("this is interesting") == []

assert candidate("good bad dd") == ["goo", "ba", "d"]

split string `s` by words that ends with 'd'


Prompt:
def f_9012008():
	return

return `True` if string `foobarrrr` contains regex `ba[rzd]`


Prompt:
def f_7961363(t):
	return


Prompt:
def f_7961363(source_list):
	return

Removing duplicates in list `source_list`


Prompt:
def f_7961363():
	return

from collections import OrderedDict

def check(candidate):

assert candidate() == ['a', 'b', 'r', 'c', 'd']

Removing duplicates in list `abracadabra`


Prompt:
def f_5183533(a):
	return

assert candidate(['a', 'aa', 'abc']) == ['a', 'aa', 'abc']


Prompt:
def f_5183533(a):
	return

assert candidate(['a', 'aa', 'abc']) == 'a'

Convert the first row of numpy matrix `a` to a list


Prompt:
def f_5999747(soup):
	return

from bs4 import BeautifulSoup

def check(candidate):

assert candidate(BeautifulSoup("Address:	My home address	")) == "My home address"

assert candidate(BeautifulSoup("Address:	This is my home address	Not my home address	")) == "This is my home address"

assert candidate(BeautifulSoup("Address:	My home address
My home address in a list
	")) == "My home address"

In `soup`, get the content of the sibling of the `td`  tag with text content `Address:`


Prompt:
def f_4284648(l):
	return

convert elements of each tuple in list `l` into a string  separated by character `@`


Prompt:
def f_4284648(l):
	return

convert each tuple in list `l` to a string with '@' separating the tuples' elements


Prompt:
def f_29696641(teststr):
	return

[i for i in teststr if re.search('\\d+[xX]', i)]

assert candidate(['1 FirstString', '2x Sec String', '3rd String', 'x forString', '5X fifth']) == ['2x Sec String', '5X fifth']

assert candidate(['1x', '2', '3X', '4x random', '5X random']) == ['1x', '3X', '4x random', '5X random']

assert candidate(['1x', '2', '3X', '4xrandom', '5Xrandom']) == ['1x', '3X', '4xrandom', '5Xrandom']

Get all matches with regex pattern `\\d+[xX]` in list of string `teststr`


Prompt:
def f_15315452(df):
	return

import pandas as pd

def check(candidate):

select values from column 'A' for which corresponding values in column 'B' will be greater than 50, and in column 'C' - equal 900 in dataframe `df`


Prompt:
def f_4642501(o):
	return

import pandas as pd

def check(candidate):

assert candidate({"as2q":"piqr", "#wwq":"say", "Rwc":"koala", "35":"kangaroo"}) == [('#wwq', 'say'), ('35', 'kangaroo'), ('Rwc', 'koala'), ('as2q', 'piqr')]

Sort dictionary `o` in ascending order based on its keys and items


Prompt:
def f_4642501(d):
	return

assert candidate({"as2q":"piqr", "#wwq":"say", "Rwc":"koala", "35":"kangaroo"}) == ['#wwq', '35', 'Rwc', 'as2q']


Prompt:
def f_4642501(d):
	return


Prompt:
def f_642154():
	return

assert candidate() == 1
assert candidate() + 1 == 2


Prompt:
def f_642154(T1):
	return


Prompt: def f_3777301():

import subprocess
from unittest.mock import Mock

def check(candidate):

    subprocess.call = Mock()
    try:
        candidate()
    except:
        assert False

call a shell script `./test.sh` using subprocess


Prompt: def f_3777301():

import subprocess
from unittest.mock import Mock

def check(candidate):

    subprocess.call = Mock()
    try:
        candidate()
    except:
        assert False

call a shell script `notepad` using subprocess


Prompt:
def f_7946798(l1, l2):
	return

[val for pair in zip(l1, l2) for val in pair]

combine lists `l1` and `l2`  by alternating their elements


Prompt:
def f_8908287():
	return

assert candidate() == b'ZGF0YSB0byBiZSBlbmNvZGVk'


Prompt:
def f_8908287():
	return

assert candidate() == b'data to be encoded'

encode a string `data to be encoded` to `ascii` encoding


Prompt:
def f_7856296():
	return

    with open('text.txt', 'w', newline='') as csvfile:
        spamwriter = csv.writer(csvfile, delimiter='	')
        spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
        spamwriter.writerow(['hello', 'world', '!'])

    assert candidate() == [['Spam', 'Lovely Spam', 'Wonderful Spam'], ['hello', 'world', '!']]

parse tab-delimited CSV file 'text.txt' into a list


Prompt:
def f_9035479(my_object, my_str):
	return

    class Student:
        id = 9
        name = "abc"
        grade = 97.08

    s = Student()

    assert candidate(s, "name") == "abc"

    class Student:
        id = 9
        name = "abc"
        grade = 97.08

    s = Student()

    assert (candidate(s, "grade") - 97.08) < 1e-6

    class Student:
        id = 9
        name = "abc"
        grade = 97.08

    s = Student()

    assert (candidate(s, "grade") - 97.07) > 1e-6

    class Student:
        id = 9
        name = "abc"
        grade = 97.08

    s = Student()

    assert candidate(s, "id") == 9

Get attribute `my_str` of object `my_object`


Prompt:
def f_5558418(LD):
	return

dict(zip(LD[0], zip(*[list(d.values()) for d in LD])))

import collections

def check(candidate):

    employees = [{'name' : 'apple', 'id': 60}, {'name' : 'orange', 'id': 65}]
    exp_result = {'name': ('apple', 'orange'), 'id': (60, 65)}
    actual_result = candidate(employees)
    for key in actual_result:
        assert collections.Counter(list(exp_result[key])) == collections.Counter(list(actual_result[key]))

group a list of dicts `LD` into one dict by key


Prompt:
def f_638048(list_of_pairs):
	return

sum([pair[0] for pair in list_of_pairs])

sum the first value in each tuple in a list of tuples `list_of_pairs` in python


Prompt:
def f_14950260():
	return

    d = candidate()
    exp_result = {'code1' : 1, 'code2': 1}
    for key in d:
        if key not in exp_result:
            assert False
        else:
            assert d[key] == exp_result[key]

convert unicode string u"{'code1':1,'code2':1}" into dictionary


Prompt:
def f_11416772(mystring):
	return

[word for word in mystring.split() if word.startswith('$')]

    str = "$abc def $efg $hij klm $"
    exp_result = ['$abc', '$efg', '$hij', '$']
    assert sorted(candidate(str)) == sorted(exp_result)

find all words in a string `mystring` that start with the `$` sign


Prompt: def f_11331982(text):

text = re.sub('^https?:\\/\\/.*[\\r\\n]*', '', text, flags=re.MULTILINE)

assert candidate("https://www.wikipedia.org/ click at") == ""


Prompt:
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):

replace all elements in array `A` that are not present in array `[1, 3, 4]` with zeros


Prompt:
def f_15819980(a):
	return

import numpy as np

def check(candidate):

calculate mean across dimension in a 2d array `a`


Prompt:
def f_19894365():
	return

from unittest.mock import Mock
import subprocess

def check(candidate):

    subprocess.call = Mock(return_value = 0)
    assert candidate() == 0

running r script '/pathto/MyrScript.r' from python


Prompt:
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):

    subprocess.call = Mock(return_value = 0)
    assert candidate() == 0

run r script '/usr/bin/Rscript --vanilla /pathto/MyrScript.r'


Prompt:
def f_33058590(df):
	return

import pandas as pd
import numpy as np

def check(candidate):

replacing nan in the dataframe `df` with row average


Prompt:
def f_12400256():
	return

Convert unix timestamp '1347517370' to formatted string '%Y-%m-%d %H:%M:%S'


Prompt:
def f_23359886(a):
	return

import numpy as np

def check(candidate):

selecting rows in Numpy ndarray 'a', where the value in the first column is 0 and value in the second column is 1


Prompt:
def f_4383082(words):
	return

import regex as re

def check(candidate):

    s = "hello world sample text"
    res = ["hello", "world", "sample", "text"]
    assert candidate(s) == res

separate words delimited by one or more spaces into a list


Prompt:
def f_14637696(words):
	return

assert candidate(["hello", "world", "sample", "text", "superballer"]) == 11

length of longest element in list `words`


Prompt:
def f_3933478(result):
	return

    Contents = [{"hi": 7, "bye": 4, "from_user": 0}, {1: 2, 3: 4, 5: 6}]
    assert candidate(Contents) == 0

get the value associated with unicode key 'from_user' of first dictionary in list `result`


Prompt:
def f_39112645():
	return

[line.split() for line in open('File.txt')]

    with open('File.txt','w') as fw:
        fw.write("hi hello cat dog")
    assert candidate() == [['hi', 'hello', 'cat', 'dog']]

Retrieve each line from a file 'File.txt' as a list


Prompt:
def f_1031851(a):
	return

    a = {"one": 1, "two": 2}
    assert candidate(a) == {1: "one", 2: "two"}

swap keys with values in a dictionary `a`


Prompt:
def f_8577137():
	return

    path1 = os.path.join("", "path")
    os.mkdir(path1)
    path2 = os.path.join("path", "to")
    os.mkdir(path2)
    candidate()
    assert os.path.exists('path/to/FILE_NAME.ext')

Open a file `path/to/FILE_NAME.ext` in write mode


Prompt:
def f_17926273(df):
	return

import pandas as pd

def check(candidate):

count distinct values in a column 'col3' of a pandas dataframe `df` group by objects in 'col1' and 'col2'


Prompt:
def f_3735814(dict1):
	return

any(key.startswith('EMP$$') for key in dict1)

assert candidate({'EMP$$': 1, 'EMP$$112': 4}) == True

assert candidate({'EMP$$': 1, 'EM$$112': 4}) == True

assert candidate({'EMP$33': 0}) == False

Check if any key in the dictionary `dict1` starts with the string `EMP$$`


Prompt:
def f_3735814(dict1):
	return

[value for key, value in list(dict1.items()) if key.startswith('EMP$$')]

assert sorted(candidate({'EMP$33': 0})) == []

create list of values from dictionary `dict1` that have a key that starts with 'EMP$$'


Prompt: def f_26097916(sf):

df = pd.DataFrame({'email': sf.index, 'list': sf.values})

import pandas as pd

def check(candidate):

convert a pandas series `sf` into a pandas dataframe `df` with columns `email` and `list`


Prompt:
def f_4048964(list):
	return

assert candidate(['hello', 'world', '!']) == 'hello\tworld\t!'

assert candidate(["mconala"]) == "mconala"

assert candidate(["MCoNaLa"]) == "MCoNaLa"

concatenate elements of list `list` by tabs `	`


Prompt:
def f_3182716():
	return

assert candidate() == b'\xd0\xbf\xd1\x80\xd0\xb8'

print unicode string '\xd0\xbf\xd1\x80\xd0\xb8' with utf-8


Prompt:
def f_3182716():
	return

Encode a latin character in string `Sopet\xc3\xb3n` properly


Prompt:
def f_35622945(s):
	return

regex, find "n"s only in the middle of string `s`


Prompt:
def f_5306756():
	return

display the float `1/3*100` as a percentage


Prompt: def f_2878084(mylist):

    input = [
        {'title':'New York Times', 'title_url':'New_York_Times','id':4},
        {'title':'USA Today','title_url':'USA_Today','id':6},
        {'title':'Apple News','title_url':'Apple_News','id':2}
    ]
    res = [
        {'title': 'Apple News', 'title_url': 'Apple_News', 'id': 2},
        {'title': 'New York Times', 'title_url': 'New_York_Times', 'id': 4},
        {'title': 'USA Today', 'title_url': 'USA_Today', 'id': 6}
    ]
    assert candidate(input) == res

sort a list of dictionary `mylist` by the key `title`


Prompt: def f_2878084(l):

    input = [
        {'title':'New York Times', 'title_url':'New_York_Times','id':4},
        {'title':'USA Today','title_url':'USA_Today','id':6},
        {'title':'Apple News','title_url':'Apple_News','id':2}
    ]
    res = [
        {'title': 'Apple News', 'title_url': 'Apple_News', 'id': 2},
        {'title': 'New York Times', 'title_url': 'New_York_Times', 'id': 4},
        {'title': 'USA Today', 'title_url': 'USA_Today', 'id': 6}
    ]
    assert candidate(input) == res

sort a list `l` of dicts by dict value 'title'


Prompt: def f_2878084(l):

l.sort(key=lambda x: (x['title'], x['title_url'], x['id']))

    input = [
        {'title':'New York Times', 'title_url':'New_York_Times','id':4},
        {'title':'USA Today','title_url':'USA_Today','id':6},
        {'title':'Apple News','title_url':'Apple_News','id':2}
    ]
    res = [
        {'title': 'Apple News', 'title_url': 'Apple_News', 'id': 2},
        {'title': 'New York Times', 'title_url': 'New_York_Times', 'id': 4},
        {'title': 'USA Today', 'title_url': 'USA_Today', 'id': 6}
    ]
    assert candidate(input) == res

sort a list of dictionaries by the value of keys 'title', 'title_url', 'id' in ascending order.


Prompt:
def f_9323159(l1, l2):
	return

heapq.nlargest(10, range(len(l1)), key=lambda i: abs(l1[i] - l2[i]))

find 10 largest differences between each respective elements of list `l1` and list `l2`


Prompt:
def f_29877663(soup):
	return

soup.find_all('span', {'class': 'starGryB sp'})

html = '''4.1
             2.9
             2.9
             22'''
    soup = bs4.BeautifulSoup(html, features="html5lib")
    res = '''[2.9]'''
    assert(str(candidate(soup)) == res)

BeautifulSoup find all 'span' elements in HTML string `soup` with class of 'starGryB sp'


Prompt: def f_24189150(df, engine):

import pandas as pd
from sqlalchemy import create_engine

def check(candidate):

    engine = create_engine('sqlite://', echo=False)
    df = pd.DataFrame({'name' : ['User 1', 'User 2', 'User 3']})
    candidate(df, engine)
    result = pd.read_sql('SELECT name FROM test', engine)
    assert result.equals(df)

write records in dataframe `df` to table 'test' in schema 'a_schema' with `engine`


Prompt:
def f_30766151(s):
	return

assert candidate("(a(vdwvndw){}]") == "((){}]"


Prompt:
def f_1143379(L):
	return

list(dict((x[0], x) for x in L).values())

assert candidate(["a", "aa", "abc", "bac"]) == ["abc", "bac"]


Prompt:
def f_12330522(file):
	return

    res = ['1', '2', '3']
    f = open("myfile.txt", "a")
    f.write("1\n2\n3")
    f.close()
    f = open("myfile.txt", "r")
    assert candidate(f) == res


Prompt:
def f_364621(testlist):
	return

[i for (i, x) in enumerate(testlist) if (x == 1)]

    testlist = [1,2,3,5,3,1,2,1,6]
    assert candidate(testlist) == [0, 5, 7]

    testlist = [0, -1]
    assert candidate(testlist) == []

get the position of item 1 in `testlist`


Prompt:
def f_364621(testlist):
	return

[i for (i, x) in enumerate(testlist) if (x == 1)]

    testlist = [1,2,3,5,3,1,2,1,6]
    assert candidate(testlist) == [0, 5, 7]

    testlist = [0, -1]
    assert candidate(testlist) == []

get the position of item 1 in `testlist`


Prompt:
def f_364621(testlist, element):
	return

    testlist = [1,2,3,5,3,1,2,1,6]
    assert candidate(testlist, 1) == 0

    testlist = [1,2,3,5,3,1,2,1,6]
    try:
        candidate(testlist, 14)
    except:
        assert True

get the position of item `element` in list `testlist`


Prompt:
def f_13145368(lis):
	return

find the first element of the tuple with the maximum second element in a list of tuples `lis`


Prompt:
def f_13145368(lis):
	return

from operator import itemgetter

def check(candidate):

get the item at index 0 from the tuple that has maximum value at index 1 in list `lis`


Prompt: def f_2689189():

    t1 = time.time()
    candidate()
    t2 = time.time()
    assert t2 - t1 > 1


Prompt:
def f_12485244(L):
	return

    L = [("abc", "def"), ("hij", "klm")]
    assert candidate(L) == '(abc, def), (hij, klm)'


Prompt: def f_755857():

b = models.CharField(max_length=7, default='0000000', editable=False)

from django.db import models

def check(candidate):

assert candidate().get_default() == '0000000'

Django set default value of field `b` equal to '0000000'


Prompt:
def f_16193578(list5):
	return

sorted(list5, key = lambda x: (degrees(x), x))

from math import degrees

def check(candidate):

Sort lis `list5` in ascending order based on the degrees value of its elements


Prompt:
def f_16041405(l):
	return

    generator = candidate([1,2,3,5])
    assert str(type(generator)) == "<class 'generator'>"
    assert [x for x in generator] == [1, 2, 3, 5]

convert a list `l` into a generator object


Prompt:
def f_18837607(oldlist, removelist):
	return

[v for i, v in enumerate(oldlist) if i not in removelist]

assert candidate(["asdf","ghjk","qwer","tyui"], [1,3]) == ['asdf', 'qwer']

remove elements from list `oldlist` that have an index number mentioned in list `removelist`


Prompt:
def f_4710067():
	return

    fw = candidate()
    assert fw.name == "yourfile.txt"
    assert fw.mode == 'w'

Open a file `yourfile.txt` in write mode


Prompt:
def f_7373219(obj, attr):
	return

    class Student:
        student_id = ""
        student_name = ""

        def __init__(self, student_id=101, student_name="Adam"):
            self.student_id = student_id
            self.student_name = student_name

    student = Student()

    assert(candidate(student, 'student_name') == "Adam")
    assert(candidate(student, 'student_id') == 101)

    class Student:
        student_id = ""
        student_name = ""

        def __init__(self, student_id=101, student_name="Adam"):
            self.student_id = student_id
            self.student_name = student_name

    student = Student()

    try:
        value = candidate(student, 'student_none')
    except:
        assert True


Prompt:
def f_8171751():
	return

from functools import reduce

def check(candidate):

assert candidate() == ('aa', 'bb', 'cc')

convert tuple of tuples `(('aa',), ('bb',), ('cc',))` to tuple


Prompt:
def f_8171751():
	return

assert candidate() == ['aa', 'bb', 'cc']

convert tuple of tuples `(('aa',), ('bb',), ('cc',))` to list in one line


Prompt: def f_28986489(df):

import pandas as pd

def check(candidate):

replace a characters in a column of a dataframe `df`


Prompt:
def f_19339():
	return


Prompt:
def f_19339(original):
	return

([a for (a, b) in original], [b for (a, b) in original])


Prompt:
def f_19339(original):
	return

((a for (a, b) in original), (b for (a, b) in original))

    original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
    result = candidate(original)
    assert [a for gen in result for a in gen] == ['a','b','c','d',1,2,3,4]

    original2 = [([], 1), ([], 2), (5, 3), (6, 4)]
    result2 = candidate(original2)
    assert [a for gen in result2 for a in gen] == [[], [], 5, 6, 1, 2, 3, 4]

unzip list `original` and return a generator


Prompt:
def f_19339():
	return

assert list(candidate()) == [('a', 'b', 'c', 'd', 'e')]


Prompt:
def f_19339():
	return

from itertools import zip_longest

def check(candidate):

unzip list `[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', )]` and fill empty results with None


Prompt:
def f_1960516():
	return

    data = candidate()
    assert json.loads(data) == '3.9'

encode `Decimal('3.9')` to a JSON string


Prompt: def f_1024847(d):

assert candidate({'key': 'value'}) == {'key': 'value', 'mynewkey': 'mynewvalue'}

Add key "mynewkey" to dictionary `d` with value "mynewvalue"


Prompt: def f_1024847(data):

assert candidate({'key': 'value'}) == {'key': 'value', 'a': 1}

assert candidate({'key': 'value', 'a' : 2}) == {'key': 'value', 'a': 1}

Add key 'a' to dictionary `data` with value 1


Prompt: def f_1024847(data):

assert candidate({'key': 'value'}) == {'key': 'value', 'a': 1}

assert candidate({'key': 'value', 'a' : 2}) == {'key': 'value', 'a': 1}

Add key 'a' to dictionary `data` with value 1


Prompt: def f_1024847(data):

assert candidate({'key': 'value'}) == {'key': 'value', 'a': 1}

assert candidate({'key': 'value', 'a' : 2}) == {'key': 'value', 'a': 1}

Add key 'a' to dictionary `data` with value 1


Prompt:
def f_35837346(matrix):
	return


Prompt: def f_20457038(answer):

Round number `answer` to 2 precision after the decimal point


Prompt: def f_2890896(s):

assert candidate("<title>Current IP Check</title>Current IP Address: 165.91.15.131") == ["165.91.15.131"]

assert candidate("<title>Current IP Check</title>Current IP Address: 165.91.15.131 and this is not a IP Address: 165.91.15") == ["165.91.15.131"]

assert candidate("<title>Current IP Check</title>Current IP Address: 192.168.1.1 & this is another IP address: 192.168.1.2") == ["192.168.1.1", "192.168.1.2"]

extract ip address `ip` from an html string `s`


Prompt:
def f_29836836(df):
	return

df.groupby('A').filter(lambda x: len(x) > 1)

import pandas as pd

def check(candidate):

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

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

filter dataframe `df` by values in column `A` that appear more than once


Prompt:
def f_2545397(myfile):
	return

    with open('./tmp.txt', 'w') as fw:
        for s in ["hello", "world", "!!!"]:
            fw.write(f"{s}\n")

    with open('./tmp.txt', 'r') as myfile:
        lines = candidate(myfile)
        assert isinstance(lines, list)
        assert len(lines) == 3
        assert lines[0].strip() == "hello"

append each line in file `myfile` into a list


Prompt: def f_2545397():

lst = list(map(int, open('filename.txt').readlines()))

import pandas as pd

def check(candidate):

    with open('./filename.txt', 'w') as fw:
        for s in ["1", "2", "100"]:
            fw.write(f"{s}\n")

    assert candidate() == [1, 2, 100]

Get a list of integers `lst` from a file `filename.txt`


Prompt: def f_35420052(plt, mappable, 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):

    spl1 = Trace(data=np.arange(0, 10))
    fig = plt.figure()
    ax1 = fig.add_axes([0.1, 0.75, 0.7, 0.2]) #[left bottom width height]
    ax2 = fig.add_axes([0.1, 0.1, 0.7, 0.60], sharex=ax1)
    ax3 = fig.add_axes([0.83, 0.1, 0.03, 0.6])

    #make time vector
    t = np.arange(spl1.stats.npts) / spl1.stats.sampling_rate

    #plot waveform (top subfigure)
    ax1.plot(t, spl1.data, 'k')

    #plot spectrogram (bottom subfigure)
    spl2 = spl1
    fig = spl2.spectrogram(show=False, axes=ax2, wlen=10)
    mappable = ax2.images[0]
    candidate(plt, mappable, ax3)

    im=ax2.images
    assert im[-1].colorbar is not None

add color bar with image `mappable` to plot `plt`


Prompt:
def f_29903025(df):
	return

import pandas as pd
from collections import Counter

def check(candidate):

    df = pd.DataFrame({"text": [
      'Python is a high-level, general-purpose programming language.',
      'Its design philosophy emphasizes code readability with the use of significant indentation. Python is dynamically-typed and garbage-collected.'
    ]})
    assert candidate(df) == [('Python', 2),('is', 2),('a', 1),('high-level,', 1),('general-purpose', 1),
        ('programming', 1),('language.', 1),('Its', 1),('design', 1),('philosophy', 1),('emphasizes', 1),
        ('code', 1),('readability', 1),('with', 1), ('the', 1),('use', 1),('of', 1),('significant', 1),
        ('indentation.', 1),('dynamically-typed', 1),('and', 1),('garbage-collected.', 1)]

count most frequent 100 words in column 'text' of dataframe `df`


Prompt:
def f_7378180():
	return

list(itertools.combinations((1, 2, 3), 2))

generate all 2-element subsets of tuple `(1, 2, 3)`


Prompt:
def f_4530069():
	return

import pytz
import time
from datetime import datetime, timezone

def check(candidate):

assert (candidate() - datetime(1970, 1, 1).replace(tzinfo=timezone.utc)).total_seconds() - time.time() <= 1

get a value of datetime.today() in the UTC time zone


Prompt: def f_4842956(list1):

Get a new list `list2`by removing empty list from a list of lists `list1`


Prompt: def f_4842956(list1):

Create `list2` to contain the lists from list `list1` excluding the empty lists from `list1`


Prompt:
def f_9262278(data):
	return

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):

    if settings.DEBUG:
        assert candidate(json.dumps({"Sample-Key": "Sample-Value"})).content == b'{"Sample-Key": "Sample-Value"}'

    if settings.DEBUG:
        assert candidate(json.dumps({"Sample-Key": "Sample-Value"}))['content-type'] == 'application/json'


Prompt:
def f_17284947(example_str):
	return

    list_elems = candidate("Josie Smith [3996 COLLEGE AVENUE, SOMETOWN, MD 21003]Mugsy Dog Smith [2560 OAK ST, GLENMEADE, WI 14098]")
    assert "".join(list_elems).strip() == 'Josie Smith Mugsy Dog Smith'

get all text that is not enclosed within square brackets in string `example_str`


Prompt:
def f_17284947(example_str):
	return

    list_elems = candidate("Josie Smith [3996 COLLEGE AVENUE, SOMETOWN, MD 21003]Mugsy Dog Smith [2560 OAK ST, GLENMEADE, WI 14098]")
    assert "".join(list_elems).strip() == 'Josie Smith Mugsy Dog Smith'

Use a regex to get all text in a string `example_str` that is not surrounded by square brackets


Prompt:
def f_14182339():
	return

assert candidate() == ['(zyx)', 'b', 'c']

get whatever is between parentheses as a single match, and any char outside as an individual match in string '(zyx)bc'


Prompt:
def f_14182339():
	return

match regex '\\((.*?)\\)|(\\w)' with string '(zyx)bc'


Prompt:
def f_14182339():
	return

assert candidate() == ['(zyx)', 'b', 'c']

match multiple regex patterns with the alternation operator `|` in a string `(zyx)bc`


Prompt: def f_7126916(elements):

elements = ['%{0}%'.format(element) for element in elements]

    elements = ['abc', 'def', 'ijk', 'mno']
    assert candidate(elements) == ['%abc%', '%def%', '%ijk%', '%mno%']

formate each string cin list `elements` into pattern '%{0}%'


Prompt:
def f_3595685():
	return

import subprocess
from unittest.mock import Mock

def check(candidate):

    subprocess.Popen = Mock(return_value = 0)
    assert candidate() == 0

Open a background process 'background-process' with arguments 'arguments'


Prompt:
def f_18453566(mydict, mykeys):
	return

    mydict = {'one': 1, 'two': 2, 'three': 3}
    mykeys = ['three', 'one']
    assert candidate(mydict, mykeys) == [3, 1]

    mydict = {'one': 1.0, 'two': 2.0, 'three': 3.0}
    mykeys = ['one']
    assert candidate(mydict, mykeys) == [1.0]

get list of values from dictionary 'mydict' w.r.t. list of keys 'mykeys'


Prompt:
def f_12692135():
	return

assert candidate() == {'Name': 'Joe', 'Age': 22}

convert list `[('Name', 'Joe'), ('Age', 22)]` into a dictionary


Prompt:
def f_14401047(data):
	return

import numpy as np

def check(candidate):

    data = np.array([[1, 2, 3, 4, 4, 3, 7, 1], [6, 2, 3, 4, 3, 4, 4, 1]])
    expected_res = np.array([[3.125], [3.375]])
    assert np.array_equal(candidate(data), expected_res)

average each two columns of array `data`


Prompt:
def f_18886596(s):
	return

    s = 'This sentence has some "quotes" in it'
    assert candidate(s) == 'This sentence has some \"quotes\" in it'

double backslash escape all double quotes in string `s`


Prompt:
def f_5932059(s):
	return

    s = "this is  a\nsentence"
    assert candidate(s) == ['this', ' ', 'is', '  ', 'a', '\n', 'sentence']

split a string `s` into a list of words and whitespace


Prompt:
def f_9938130(df):
	return

import pandas as pd

def check(candidate):

    data = [[1, 3], [2, 5], [4, 8]]
    df = pd.DataFrame(data, columns = ['a', 'b'])
    assert str(candidate(df)).split('(')[0] == 'AxesSubplot'

plotting stacked barplots on a panda data frame `df`


Prompt:
def f_35945473(myDictionary):
	return

{i[1]: i[0] for i in list(myDictionary.items())}

reverse the keys and values in a dictionary `myDictionary`


Prompt:
def f_30729735(myList):
	return

[i for i, j in enumerate(myList) if 'how' in j.lower() or 'what' in j.lower()]

assert candidate(['abc', 'how', 'what', 'def']) == [1, 2]

finding the index of elements containing substring 'how' and 'what' in a list of strings 'myList'.


Prompt:
def f_1303243(obj):
	return


Prompt:
def f_1303243(o):
	return


Prompt:
def f_1303243(o):
	return


Prompt:
def f_1303243(obj_to_test):
	return


Prompt: def f_8177079(list1, list2):


Prompt: def f_8177079(mylog, list1):


Prompt: def f_8177079(a, c):


Prompt: def f_8177079(mylog, list1):

for line in mylog:
	    list1.append(line)


Prompt: def f_4126227(a, b):

append a tuple of elements from list `a` with indexes '[0][0] [0][2]' to list `b`


Prompt: def f_34902378(app):

from flask import Flask

def check(candidate):

    app = Flask("test")
    candidate(app)
    assert app.config['SECRET_KEY'] == 'Your_secret_string'

Initialize `SECRET_KEY` in flask config with `Your_secret_string `


Prompt:
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):

    df = pd.DataFrame(dict(x=np.random.randn(100), y=np.repeat(list("abcd"), 25)))
    out = df.groupby("y").x.apply(stats.ttest_1samp, 0)
    test = pd.DataFrame(out.tolist())
    test.columns = ['out-1', 'out-2']
    test.index = out.index
    res = candidate(out)
    assert(test.equals(res))

unpack a series of tuples in pandas `out` into a DataFrame with column names 'out-1' and 'out-2'


Prompt:
def f_1762484(stocks_list):
	return

[x for x in range(len(stocks_list)) if stocks_list[x] == 'MSFT']

    stocks_list = ['AAPL', 'MSFT', 'GOOG', 'MSFT', 'MSFT']
    assert(candidate(stocks_list) == [1,3,4])

    stocks_list = ['AAPL', 'MSXT', 'GOOG', 'MSAT', 'SFT']
    assert(candidate(stocks_list) == [])

find the index of an element 'MSFT' in a list `stocks_list`


Prompt:
def f_3464359(ax, labels):
	return

import matplotlib.pyplot as plt

def check(candidate):

    fig, ax = plt.subplots()
    ax.plot([1, 2, 3, 4], [1, 4, 2, 3])
    ret = candidate(ax, [f"#{i}" for i in range(7)])
    assert [tt.get_rotation() == 45.0 for tt in ret]

rotate the xtick `labels` of matplotlib plot `ax` by `45` degrees to make long labels readable


Prompt:
def f_875968(s):
	return

    s = "how much for the maple syrup? $20.99? That's ridiculous!!!"
    assert candidate(s) == 'how much for the maple syrup   20 99  That s ridiculous   '


Prompt:
def f_34750084(s):
	return

Find octal characters matches from a string `s` using regex


Prompt:
def f_13209288(input):
	return

assert candidate('HELLO there HOW are YOU') == ['HELLO there', 'HOW are', 'YOU']

assert candidate('hELLO there HoW are YOU') == ['hELLO there HoW are', 'YOU']

assert candidate('7 is a NUMBER') == ['7 is a', 'NUMBER']

assert candidate('NUMBER 7') == ['NUMBER 7']

split string `input` based on occurrences of regex pattern '[ ](?=[A-Z]+\\b)'


Prompt:
def f_13209288(input):
	return

assert candidate('HELLO there HOW are YOU') == ['HELLO there', 'HOW are', 'YOU']

assert candidate('hELLO there HoW are YOU') == ['hELLO there', 'HoW are', 'YOU']

assert candidate('7 is a NUMBER') == ['7 is a', 'NUMBER']

assert candidate('NUMBER 7') == ['NUMBER 7']

Split string `input` at every space followed by an upper-case letter


Prompt:
def f_24642040(url, files, headers, data):
	return

requests.post(url, files=files, headers=headers, data=data)

import requests
from unittest.mock import Mock

def check(candidate):

    requests.post = Mock()
    try:
        candidate('https://www.google.com', ['a.txt'], {'accept': 'text/json'}, {'name': 'abc'})
    except:
        assert False

send multipart encoded file `files` to url `url` with headers `headers` and metadata `data`


Prompt:
def f_4290716(filename, bytes_):
	return

    bytes_ = b'68 65 6c 6c 6f'
    candidate("tmpfile", bytes_)

    with open("tmpfile", 'rb') as fr:
        assert fr.read() == bytes_

write bytes `bytes_` to a file `filename` in python 3


Prompt:
def f_33078554(lst, dct):
	return

get a list from a list `lst` with values mapped into a dictionary `dct`


Prompt:
def f_15247628(x):
	return

import pandas as pd

def check(candidate):

assert candidate(pd.DataFrame([{'name': 'willy', 'age': 10}, {'name': 'wilson', 'age': 11}, {'name': 'zoe', 'age': 10}])).tolist() == []

assert candidate(pd.DataFrame([{'name': 'willy', 'age': 10}, {'name': 'willy', 'age': 11}, {'name': 'zoe', 'age': 10}])).tolist() == ['willy']

assert candidate(pd.DataFrame([{'name': 'willy', 'age': 11}, {'name': 'willy', 'age': 11}, {'name': 'zoe', 'age': 10}])).tolist() == ['willy']

assert candidate(pd.DataFrame([{'name': 'Willy', 'age': 11}, {'name': 'willy', 'age': 11}, {'name': 'zoe', 'age': 10}])).tolist() == []

find duplicate names in column 'name' of the dataframe `x`


Prompt:
def f_783897():
	return

truncate float 1.923328437452 to 3 decimal places


Prompt:
def f_22859493(li):
	return

sorted(li, key=lambda x: datetime.strptime(x[1], '%d/%m/%Y'), reverse=True)

from datetime import datetime

def check(candidate):

sort list `li` in descending order based on the date value in second element of each list in list `li`


Prompt: def f_29394552(ax):

import matplotlib.pyplot as plt

def check(candidate):

    ax = plt.subplot(111, polar=True)
    candidate(ax)
    assert ax.properties()['rlabel_position'] == 135.0

place the radial ticks in plot `ax` at 135 degrees


Prompt:
def f_3320406(my_path):
	return

assert candidate('.') == False
assert candidate('/') == True
assert candidate('/usr') == True

check if path `my_path` is an absolute path


Prompt:
def f_2212433(yourdict):
	return

get number of keys in dictionary `yourdict`


Prompt:
def f_2212433(yourdictfile):
	return

    with open('dict.txt', 'w') as fw:
        for w in ["apple", "banana", "tv", "apple", "phone"]:
            fw.write(f"{w}\n")
    assert candidate('dict.txt') == 4

count the number of keys in dictionary `yourdictfile`


Prompt:
def f_20067636(df):
	return

import pandas as pd

def check(candidate):

    df = pd.DataFrame({
        'id': [1, 1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 5, 6, 6, 6, 7, 7],
        'value': ['first', 'second', 'second', 'first', 'second', 'first', 'third', 'fourth', 'fifth', 'second', 'fifth', 'first', 'first', 'second', 'third', 'fourth', 'fifth']
    })
    assert candidate(df).to_dict() == {'value': {1: 'first', 2: 'first', 3: 'first', 4: 'second', 5: 'first', 6: 'first', 7: 'fourth'}}

pandas dataframe `df` get first row of each group by 'id'


Prompt:
def f_40924332(df):
	return

import numpy as np
import pandas as pd

def check(callerFunction):

split a list in first column into multiple columns keeping other columns as well in pandas data frame `df`


Prompt:
def f_30759776(data):
	return

    data = '<script type="text/javascript" src="js/jquery-1.9.1.min.js"/><script type="text/javascript" src="js/jquery-migrate-1.2.1.min.js"/><script type="text/javascript" src="js/jquery-ui.min.js"/><script type="text/javascript" src="js/abc_bsub.js"/><script type="text/javascript" src="js/abc_core.js"/>            <script type="text/javascript" src="js/abc_explore.js"/><script type="text/javascript" src="js/abc_qaa.js"/>'
    assert candidate(data) == ['jquery-1.9.1.min.js', 'jquery-migrate-1.2.1.min.js', 'jquery-ui.min.js']

extract attributes 'src="js/([^"]*\\bjquery\\b[^"]*)"' from string `data`


Prompt:
def f_25388796():
	return

sum(int(float(item)) for item in [_f for _f in ['', '3.4', '', '', '1.0'] if _f])

Sum integers contained in strings in list `['', '3.4', '', '', '1.0']`


Prompt:
def f_804995():
	return

import subprocess
from unittest.mock import Mock

def check(candidate):

    subprocess.Popen = Mock(return_value = 0)
    assert candidate() == 0

Call a subprocess with arguments `c:\\Program Files\\VMware\\VMware Server\\vmware-cmd.bat` that may contain spaces


Prompt: def f_26441253(q):

from queue import PriorityQueue

def check(candidate):

    q = PriorityQueue()
    q = candidate(q)
    expected = [4, 3, 2, 1]
    for i in range(0, len(expected)):
        assert q.get()[1] == expected[i]

reverse a priority queue `q` in python without using classes


Prompt:
def f_18897261(df):
	return

import pandas as pd

def check(candidate):

    df = pd.DataFrame([1, 3, 4, 5, 7, 9], columns = ['group'])
    a = candidate(df)
    assert 'AxesSubplot' in str(type(a))

make a barplot of data in column `group` of dataframe `df` colour-coded according to list `color`


Prompt:
def f_373194(data):
	return

assert candidate('6f96cfdfe5ccc627cadf24b41725caa4 gorilla') ==         ['6f96cfdfe5ccc627cadf24b41725caa4']

find all matches of regex pattern '([a-fA-F\\d]{32})' in string `data`


Prompt:
def f_518021(my_list):
	return

assert candidate([]) == 0
assert candidate([1]) == 1
assert candidate([1, 2]) == 2


Prompt:
def f_518021(l):
	return

import numpy as np

def check(candidate):


Prompt:
def f_518021(s):
	return

import numpy as np

def check(candidate):


Prompt:
def f_518021(my_tuple):
	return

assert candidate(('aa', 'wfseg', '')) == 3


Prompt:
def f_518021(my_string):
	return

assert candidate("sedfgbdjofgljnh") == 15


Prompt:
def f_40452956():
	return

remove escape character from string "\\a"


Prompt:
def f_8687018():
	return

"""obama""".replace('a', '%temp%').replace('b', 'a').replace('%temp%', 'b')

replace each 'a' with 'b' and each 'b' with 'a' in the string 'obama' in a single pass.


Prompt: def f_303200():

import os
import shutil
from unittest.mock import Mock

def check(candidate):

    shutil.rmtree = Mock()
    os.walk = Mock(return_value = [])
    candidate()
    assert os.walk('/') == []


Prompt: def f_13740672(data):

    def weekday(i):
        if i >=1 and i <= 5: return True
        else: return False
    data['weekday'] = data['my_dt'].apply(lambda x: weekday(x))

import pandas as pd

def check(candidate):

    data = pd.DataFrame([1, 2, 3, 4, 5, 6, 7], columns = ['my_dt'])
    data = candidate(data)
    assert data['weekday'][5] == False
    assert data['weekday'][6] == False
    for i in range (0, 5):
        assert data['weekday'][i]

create a new column `weekday` in pandas data frame `data` based on the values in column `my_dt`


Prompt:
def f_20950650(x):
	return

from collections import Counter

def check(candidate):

    x = Counter({'blue': 1, 'red': 2, 'green': 3})
    assert candidate(x) == ['green', 'red', 'blue']

    x = Counter({'blue': 1.234, 'red': 1.35, 'green': 1.789})
    assert candidate(x) == ['green', 'red', 'blue']

    x = Counter({'blue': "b", 'red': "r", 'green': "g"})
    assert candidate(x) == ['red', 'green', 'blue']


Prompt:
def f_20950650(x):
	return

sorted(list(x.items()), key=lambda pair: pair[1], reverse=True)

from collections import Counter

def check(candidate):

    x = Counter({'blue': 1, 'red': 2, 'green': 3})
    assert candidate(x) == [('green', 3), ('red', 2), ('blue', 1)]

    x = Counter({'blue': "b", 'red': "r", 'green': "g"})
    assert candidate(x) == [('red', "r"), ('green', "g"), ('blue', "b")]


Prompt:
def f_9775297(a, b):
	return

import numpy as np

def check(candidate):

append a numpy array 'b' to a numpy array 'a'


Prompt:
def f_21887754(a, b):
	return

import numpy as np

def check(candidate):

numpy concatenate two arrays `a` and `b` along the first axis


Prompt:
def f_21887754(a, b):
	return

import numpy as np

def check(candidate):

numpy concatenate two arrays `a` and `b` along the second axis


Prompt:
def f_21887754(a, b):
	return

import numpy as np

def check(candidate):

numpy concatenate two arrays `a` and `b` along the first axis


Prompt:
def f_21887754(a, b):
	return

import numpy as np

def check(candidate):

numpy concatenate two arrays `a` and `b` along the first axis


Prompt:
def f_2805231():
	return

    res = candidate()
    assert all([(add[4][1] == 80) for add in res])

fetch address information for host 'google.com' ion port 80


Prompt:
def f_17552997(df):
	return

import pandas as pd

def check(candidate):

add a column 'day' with value 'sat' to dataframe `df`


Prompt:
def f_4356842():
	return

from django.http import HttpResponse
from django.conf import settings

if not settings.configured:
    settings.configure(DEBUG=True)

def check(candidate):


Prompt:
def f_13598363():
	return

from flask import Flask

def check(candidate):

    __name__ == "test"
    assert candidate().template_folder == "wherever"

Flask set folder 'wherever' as the default template folder


Prompt: def f_3398589(c2):

sort a list of lists 'c2' such that third row comes first


Prompt: def f_3398589(c2):

c2.sort(key=lambda row: (row[2], row[1], row[0]))

sort a list of lists 'c2' in reversed row order


Prompt: def f_3398589(c2):

c2.sort(key=lambda row: (row[2], row[1]))

Sorting a list of lists `c2`, each by the third and second row


Prompt:
def f_10960463():
	return

matplotlib.rc('font', **{'sans-serif': 'Arial', 'family': 'sans-serif'})

import matplotlib

def check(candidate):

    try:
        candidate()
    except:
        assert False

set font `Arial` to display non-ascii characters in matplotlib


Prompt:
def f_20576618(df):
	return

import pandas as pd

def check(candidate):

Convert  DateTime column 'date' of pandas dataframe 'df' to ordinal


Prompt:
def f_31793195(df):
	return

import pandas as pd
import numpy as np

def check(candidate):

    df = pd.DataFrame(data=np.asarray([[1,2,3],[4,5,6],[7,8,9]]), index=['alice', 'bob', 'charlie'])
    index = candidate(df)
    assert index == 1

Get the integer location of a key `bob` in a pandas data frame `df`


Prompt: def f_10487278(my_dict):

    my_dict = {'a':1, 'b':2}
    assert candidate(my_dict) == {'a':1, 'b':2, 'third_key': 1}

    my_dict = {'c':1, 'd':2}
    assert candidate(my_dict) == {'c':1, 'd':2, 'third_key': 1}

add an item with key 'third_key' and value 1 to an dictionary `my_dict`


Prompt: def f_10487278():


Prompt: def f_10487278(my_list):


Prompt: def f_10155684(myList):

assert candidate([1,2]) == ['wuggah', 1, 2]

add an entry 'wuggah' at the beginning of list `myList`


Prompt:
def f_3519125(hex_str):
	return

assert candidate("\\xF3\\xBE\\x80\\x80") == b'\xf3\xbe\x80\x80'

convert a hex-string representation `hex_str` to actual bytes


Prompt:
def f_40144769(df):
	return

import pandas as pd

def check(candidate):

    df = pd.DataFrame([[1, 2, 3],[4,5,6]], columns=["a", "b", "c"])
    assert candidate(df).tolist() == [3,6]

    df = pd.DataFrame([["Hello", "world!"],["Hi", "world!"]], columns=["a", "b"])
    assert candidate(df).tolist() == ["world!", "world!"]

select the last column of dataframe `df`


Prompt:
def f_30787901(df):
	return

df.loc[df['Letters'] == 'C', 'Letters'].values[0]

import pandas as pd

def check(candidate):

    df = pd.DataFrame([["a", 1],["C", 6]], columns=["Letters", "Numbers"])
    assert candidate(df) == 'C'

    df = pd.DataFrame([[None, 1],["C", 789]], columns=["Letters", "Names"])
    assert candidate(df) == 'C'

get the first value from dataframe `df` where column 'Letters' is equal to 'C'


Prompt:
def f_18730044():
	return

import numpy as np

def check(candidate):

converting two lists `[1, 2, 3]` and `[4, 5, 6]` into a matrix


Prompt:
def f_402504(i):
	return

assert candidate("hello") is str
assert candidate(123) is int
assert candidate("123") is str
assert candidate(123.4) is float


Prompt:
def f_402504(v):
	return

assert candidate("hello") is str
assert candidate(123) is int
assert candidate("123") is str
assert candidate(123.4) is float


Prompt:
def f_402504(v):
	return

assert candidate("hello") is str
assert candidate(123) is int
assert candidate("123") is str
assert candidate(123.4) is float


Prompt:
def f_402504(variable_name):
	return

assert candidate("hello") is str
assert candidate(123) is int
assert candidate("123") is str
assert candidate(123.4) is float

get the type of variable `variable_name`


Prompt:
def f_2300756(g):
	return

    test = [1, 2, 3, 4, 5, 6, 7]
    assert(candidate(test) == 6)


Prompt:
def f_20056548(word):
	return

assert candidate('Some Random Word') == '"Some Random Word"'

return a string `word` with string format


Prompt:
def f_8546245(list):
	return

    test = ['hello', 'good', 'morning']
    assert candidate(test) == "hello good morning"

join a list of strings `list` using a space ' '


Prompt: def f_2276416():

create list `y` containing two empty lists


Prompt: def f_3925614(filename):

data = [line.strip() for line in open(filename, 'r')]

    file1 = open("myfile.txt", "w")
    L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
    file1.writelines(L)
    file1.close()
    assert candidate('myfile.txt') == ['This is Delhi', 'This is Paris', 'This is London']

read a file `filename` into a list `data`


Prompt:
def f_22187233():
	return

"""""".join([char for char in 'it is icy' if char != 'i'])

delete all occurrences of character 'i' in string 'it is icy'


Prompt:
def f_22187233():
	return

delete all instances of a character 'i' in a string 'it is icy'


Prompt:
def f_22187233():
	return

delete all characters "i" in string "it is icy"


Prompt:
def f_13413590(df):
	return

import numpy as np
import pandas as pd

def check(candidate):

Drop rows of pandas dataframe `df` having NaN in column at index "1"


Prompt:
def f_598398(myList):
	return

import numpy as np
import pandas as pd

def check(candidate):

    class Data:
        def __init__(self, a, n):
            self.a = a
            self.n = n

    myList = [Data(i, 10*(i%4)) for i in range(20)]
    assert candidate(myList) == [myList[i] for i in [3, 7, 11, 15, 19]]

get elements from list `myList`, that have a field `n` value 30


Prompt: def f_10351772(intstringlist):

converting list of strings `intstringlist` to list of integer `nums`


Prompt:
def f_493386():
	return


Prompt:
def f_6569528():
	return

round off the float that is the product of `2.52 * 100` and convert it to an int


Prompt: def f_3964681():

	os.chdir('/mydir')
	files = []
	for file in glob.glob('*.txt'):
		files.append(file)

import os
import glob
from unittest.mock import Mock

def check(candidate):

    samples = ['abc.txt']
    os.chdir = Mock()
    glob.glob = Mock(return_value = samples)
    assert candidate() == samples

Find all files `files` in directory '/mydir' with extension '.txt'


Prompt:
def f_3964681():
	return

[file for file in os.listdir('/mydir') if file.endswith('.txt')]

import os
from unittest.mock import Mock

def check(candidate):

    samples = ['abc.txt', 'f.csv']
    os.listdir = Mock(return_value = samples)
    assert candidate() == ['abc.txt']

Find all files in directory "/mydir" with extension ".txt"


Prompt:
def f_3964681():
	return

[file for (root, dirs, files) in os.walk('/mydir') for file in files if file.endswith('.txt')]

import os
from unittest.mock import Mock

def check(candidate):

    name = '/mydir'
    samples = [(name, [], ['abc.txt', 'f.csv'])]
    os.walk = Mock(return_value = samples)
    assert candidate() == ['abc.txt']

Find all files in directory "/mydir" with extension ".txt"


Prompt:
def f_20865487(df):
	return

import os
import pandas as pd

def check(candidate):

    df = pd.DataFrame([1, 2, 3, 4, 5], columns = ['Vals'])
    res = candidate(df)
    assert 'AxesSubplot' in str(type(res))
    assert res.legend_ is None


Prompt:
def f_13368659():
	return

    addrs = candidate()
    assert len(addrs) == 256*256
    assert addrs == [f'192.168.{i}.{j}' for i in range(256) for j in range(256)]

loop through the IP address range "192.168.x.x"


Prompt:
def f_4065737(x):
	return

sum(1 << i for i, b in enumerate(x) if b)

assert candidate([1,2,None,3,None]) == 11

Sum the corresponding decimal values for binary values of each boolean element in list `x`


Prompt: def f_8691311(line1, line2, line3, target):

target.write('%r\n%r\n%r\n' % (line1, line2, line3))

    file_name = 'abc.txt'
    lines = ['fgh', 'ijk', 'mnop']
    f = open(file_name, 'a')
    candidate(lines[0], lines[1], lines[2], f)
    f.close()
    with open(file_name, 'r') as f:
        f_lines = f.readlines()
        for i in range (0, len(lines)):
            assert lines[i] in f_lines[i]

write multiple strings `line1`, `line2` and `line3` in one line in a file `target`


Prompt:
def f_10632111(data):
	return

[y for x in data for y in (x if isinstance(x, list) else [x])]

    data = [[1, 2], [3]]
    assert candidate(data) == [1, 2, 3]

    data = [1,2,3]
    assert candidate(data) == [1, 2, 3]

Convert list of lists `data` into a flat list


Prompt:
def f_15392730():
	return

Print new line character as `\n` in a string `foo\nbar`


Prompt:
def f_1010961(s):
	return

assert candidate('abc, def, klm') == 'abc, def klm'

remove last comma character ',' in string `s`


Prompt:
def f_23855976(x):
	return

import numpy as np

def check(candidate):

calculate the mean of each element in array `x` with the element previous to it


Prompt:
def f_23855976(x):
	return

import numpy as np

def check(candidate):

get an array of the mean of each two consecutive values in numpy array `x`


Prompt: def f_6375343():

arr = numpy.fromiter(codecs.open('new.txt', encoding='utf-8'), dtype='<U2')

import numpy
import codecs
import numpy as np

def check(candidate):

    with open ('new.txt', 'a', encoding='utf-8') as f:
        f.write('ट')
        f.write('ज')
    arr = candidate()
    assert arr[0] == 'टज'

load data containing `utf-8` from file `new.txt` into numpy array `arr`


Prompt: def f_1547733(l):

l = sorted(l, key=itemgetter('time'), reverse=True)

from operator import itemgetter

def check(candidate):

reverse sort list of dicts `l` by value for key `time`


Prompt: def f_1547733(l):

l = sorted(l, key=lambda a: a['time'], reverse=True)

Sort a list of dictionary `l` based on key `time` in descending order


Prompt:
def f_37080612(df):
	return

import pandas as pd

def check(candidate):

    df = pd.DataFrame([['Hello', 'World'], ['Just', 'Wanted'], ['To', 'Say'], ['I\'m', 'Tired']])
    df1 = candidate(df)
    assert df1[0][0] == 'Hello'
    assert df1[0][1] == 'Just'

get rows of dataframe `df` that match regex '(Hel|Just)'


Prompt:
def f_14716342(your_string):
	return

assert candidate('[uranus]') == 'uranus'

assert candidate('hello[world] !') == 'world'

find the string in `your_string` between two special characters "[" and "]"


Prompt:
def f_18684076():
	return

create a list of date string in 'yyyymmdd' format with Python Pandas from '20130226' to '20130302'


Prompt:
def f_1666700():
	return

"""The big brown fox is brown""".count('brown')

count number of times string 'brown' occurred in string 'The big brown fox is brown'


Prompt:
def f_18979111(request_body):
	return

    x = """{
    "Name": "Jennifer Smith",
    "Contact Number": 7867567898,
    "Email": "jen123@gmail.com",
    "Hobbies":["Reading", "Sketching", "Horse Riding"]
    }"""
    assert candidate(x) == {'Hobbies': ['Reading', 'Sketching', 'Horse Riding'], 'Name': 'Jennifer Smith', 'Email': 'jen123@gmail.com', 'Contact Number': 7867567898}

decode json string `request_body` to python dict


Prompt:
def f_7243750(url, file_name):
	return

    file_name = 'g.html'
    candidate('https://asia.nikkei.com/Business/Tech/Semiconductors/U.S.-chip-tool-maker-Synopsys-expands-in-Vietnam-amid-China-tech-war', file_name)
    with open (file_name, 'r') as f:
        lines = f.readlines()
        if len(lines) == 0: assert False
        else: assert True

download the file from url `url` and save it under file `file_name`


Prompt:
def f_743806(text):
	return

assert candidate('The quick brown fox') == ['The', 'quick', 'brown', 'fox']

assert candidate('hello!') == ['hello!']

assert candidate('hello world !') == ['hello', 'world', '!']


Prompt:
def f_743806(text):
	return

assert candidate('The quick brown fox') == ['The quick brown fox']

assert candidate('The,quick,brown,fox') == ['The', 'quick', 'brown', 'fox']


Prompt:
def f_743806(line):
	return

assert candidate('The  quick brown  fox') == ['The', 'quick', 'brown', 'fox']

Split string `line` into a list by whitespace


Prompt:
def f_35044115(s):
	return

replace dot characters  '.' associated with ascii letters in list `s` with space ' '


Prompt:
def f_38388799(list_of_strings):
	return

sorted(list_of_strings, key=lambda s: s.split(',')[1])

assert candidate(['parrot, medicine', 'abott, kangaroo', 'sriracha, coriander', 'phone, bottle']) == ['phone, bottle', 'sriracha, coriander', 'abott, kangaroo', 'parrot, medicine']

assert candidate(['abott, kangaroo', 'parrot, medicine', 'sriracha, coriander', 'phone, bottle']) == ['phone, bottle', 'sriracha, coriander', 'abott, kangaroo', 'parrot, medicine']

sort list `list_of_strings` based on second index of each string `s`


Prompt:
def f_37004138(lst):
	return

[element for element in lst if isinstance(element, int)]

    lst = [1, "hello", "string", 2, 4.46]
    assert candidate(lst) == [1, 2]

    lst = ["hello", "string"]
    assert candidate(lst) == []

eliminate non-integer items from list `lst`


Prompt:
def f_37004138(lst):
	return

[element for element in lst if not isinstance(element, str)]

    lst = [1, "hello", "string", 2, 4.46]
    assert candidate(lst) == [1, 2, 4.46]

    lst = ["hello", "string"]
    assert candidate(lst) == []

get all the elements except strings from the list 'lst'.


Prompt:
def f_72899(list_to_be_sorted):
	return

sorted(list_to_be_sorted, key=lambda k: k['name'])

    list_to_be_sorted = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]
    assert candidate(list_to_be_sorted) == [{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}]

    list_to_be_sorted = [{'name': 'ABCD'}, {'name': 'AABCD'}]
    assert candidate(list_to_be_sorted) == [{'name': 'AABCD'}, {'name': 'ABCD'}]

Sort a list of dictionaries `list_to_be_sorted` by the value of the dictionary key `name`


Prompt:
def f_72899(l):
	return

from operator import itemgetter

def check(candidate):

    list_to_be_sorted = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]
    assert candidate(list_to_be_sorted) == [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]

    list_to_be_sorted = [{'name': 'ABCD'}, {'name': 'AABCD'}]
    assert candidate(list_to_be_sorted) == [{'name': 'ABCD'}, {'name': 'AABCD'}]

sort a list of dictionaries `l` by values in key `name` in descending order


Prompt: def f_72899(list_of_dicts):

    list_to_be_sorted = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]
    assert candidate(list_to_be_sorted) == [{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}]

    list_to_be_sorted = [{'name': 'ABCD'}, {'name': 'AABCD'}]
    assert candidate(list_to_be_sorted) == [{'name': 'AABCD'}, {'name': 'ABCD'}]

sort a list of dictionaries `list_of_dicts` by `name` values of the dictionary


Prompt: def f_72899(list_of_dicts):

    list_to_be_sorted = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]
    assert candidate(list_to_be_sorted) == [{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}]

    list_to_be_sorted = [{'name': 'ABCD', 'age': 10}, {'name': 'AABCD', 'age': 9}]
    assert candidate(list_to_be_sorted) == [{'name': 'AABCD', 'age': 9}, {'name': 'ABCD', 'age': 10}]

sort a list of dictionaries `list_of_dicts` by `age` values of the dictionary