task_id
stringlengths
8
10
code
stringlengths
263
3.91k
entry_point
stringlengths
1
24
test
stringlengths
1.48k
19.6k
inputs
listlengths
2
26
outputs
listlengths
0
26
DREval/100
from datetime import datetime class Classroom: def __init__(self, id): self.id = id self.courses = [] def add_course(self, course): if course not in self.courses: self.courses.append(course) def remove_course(self, course): if course in self.courses: ...
Classroom
import unittest from datetime import datetime class ClassroomTestAddCourse(unittest.TestCase): def test_add_course_1(self): classroom = Classroom(1) course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'} classroom.add_course(course) self.assertIn(course, classroom.co...
[ "classroom = Classroom(1)\ncourse = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\nclassroom.add_course(course)\nassertIn(course, classroom.courses)\n", "classroom = Classroom(1)\ncourse = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\nclassroom.add_course(course)\nclassroom.remove_c...
[]
DREval/101
class ClassRegistrationSystem: def __init__(self): self.students = [] self.students_registration_classes = {} def register_student(self, student): if student in self.students: return 0 else: self.students.append(student) return 1 def reg...
ClassRegistrationSystem
import unittest class ClassRegistrationSystemTestRegisterStudent(unittest.TestCase): def setUp(self): self.registration_system = ClassRegistrationSystem() def test_register_student(self): student1 = {"name": "John", "major": "Computer Science"} self.assertEqual(self.registration_syst...
[ "student1 = {\"name\": \"John\", \"major\": \"Computer Science\"}\nassertEqual(self.registration_system.register_student(student1), 1)\n", "assertEqual(self.registration_system.register_class(student_name=\"John\", class_name=\"CS101\"), [\"CS101\"])\n", "self.registration_system.students = [{\"name\": \"John\"...
[]
DREval/102
import math from typing import List class CombinationCalculator: def __init__(self, datas: List[str]): self.datas = datas @staticmethod def count(n: int, m: int) -> int: if m == 0 or n == m: return 1 return math.factorial(n) // (math.factorial(n - m) * math.factorial(m)...
CombinationCalculator
import unittest class CombinationCalculatorTestCount(unittest.TestCase): def test_count(self): self.assertEqual(CombinationCalculator.count(4, 2), 6) def test_count_2(self): self.assertEqual(CombinationCalculator.count(5, 3), 10) def test_count_3(self): self.assertEqual(Combination...
[ "assertEqual(CombinationCalculator.count(4, 2), 6)\n", "assertEqual(CombinationCalculator.count_all(4), 15)\n", "calc = CombinationCalculator([\"A\", \"B\", \"C\", \"D\"])\nassertEqual(calc.count(4, 2), 6)\n", "calc = CombinationCalculator([\"A\"])\nassertEqual(calc.select_all(), [['A']])\n", "calc = Combin...
[]
DREval/103
class ComplexCalculator: def __init__(self): pass @staticmethod def add(c1, c2): real = c1.real + c2.real imaginary = c1.imag + c2.imag answer = complex(real, imaginary) return answer @staticmethod def subtract(c1, c2): real = c1.real - c2.real ...
ComplexCalculator
import unittest class ComplexCalculatorTestAdd(unittest.TestCase): def test_add(self): complexCalculator = ComplexCalculator() self.assertEqual(complexCalculator.add(1+2j, 3+4j), (4+6j)) def test_add_2(self): complexCalculator = ComplexCalculator() self.assertEqual(complexCalcu...
[ "complexCalculator = ComplexCalculator()\nassertEqual(complexCalculator.add(1+2j, 3+4j), (4+6j))\n", "complexCalculator = ComplexCalculator()\nassertEqual(complexCalculator.subtract(1+2j, 3+4j), (-2-2j))\n", "complexCalculator = ComplexCalculator()\nassertEqual(complexCalculator.multiply(1+2j, 3+4j), (-5+10j))\...
[]
DREval/104
class CurrencyConverter: def __init__(self): self.rates = { 'USD': 1.0, 'EUR': 0.85, 'GBP': 0.72, 'JPY': 110.15, 'CAD': 1.23, 'AUD': 1.34, 'CNY': 6.40, } def convert(self, amount, from_currency, to_currency): ...
CurrencyConverter
import unittest class CurrencyConverterTestConvert(unittest.TestCase): def test_convert_1(self): cc = CurrencyConverter() res = cc.convert(64, 'CNY', 'USD') self.assertEqual(res, 10.0) def test_convert_2(self): cc = CurrencyConverter() res = cc.convert(64, 'USD', 'USD'...
[ "cc = CurrencyConverter()\nres = cc.convert(64, 'CNY', 'USD')\nassertEqual(res, 10.0)\n", "cc = CurrencyConverter()\nres = cc.get_supported_currencies()\nassertEqual(res, ['USD', 'EUR', 'GBP', 'JPY', 'CAD', 'AUD', 'CNY'])\n", "cc = CurrencyConverter()\ncc.add_currency_rate('KRW', 1308.84)\nassertEqual(cc.rates[...
[]
DREval/105
from collections import Counter class DataStatistics: def mean(self, data): return round(sum(data) / len(data), 2) def median(self, data): sorted_data = sorted(data) n = len(sorted_data) if n % 2 == 0: middle = n // 2 return round((sorted_data[middle - ...
DataStatistics
import unittest class DataStatisticsTestMean(unittest.TestCase): def test_mean_1(self): ds = DataStatistics() res = ds.mean([1, 2, 3, 4, 5]) self.assertEqual(res, 3.00) def test_mean_2(self): ds = DataStatistics() res = ds.mean([1, 2, 3, 4, 5, 6]) self.assertEq...
[ "ds = DataStatistics()\nres = ds.mean([1, 2, 3, 4, 5])\nassertEqual(res, 3.00)\n", "ds = DataStatistics()\nres = ds.median([2, 5, 1, 3, 4])\nassertEqual(res, 3)\n", "ds = DataStatistics()\nres = ds.mode([2, 2, 3, 3, 4])\nassertEqual(res, [2, 3])\n", "ds = DataStatistics()\nres = ds.mean([1, 2, 3, 4, 5])\nasse...
[]
DREval/106
import numpy as np class DataStatistics2: def __init__(self, data): self.data = np.array(data) def get_sum(self): return np.sum(self.data) def get_min(self): return np.min(self.data) def get_max(self): return np.max(self.data) def get_variance(self): ret...
DataStatistics2
import unittest class DataStatistics2TestGetSum(unittest.TestCase): def test_get_sum_1(self): ds2 = DataStatistics2([1, 2, 3, 4]) res = ds2.get_sum() self.assertEqual(res, 10) def test_get_sum_2(self): ds2 = DataStatistics2([1, 2, 203, 4]) res = ds2.get_sum() s...
[ "ds2 = DataStatistics2([1, 2, 3, 4])\nres = ds2.get_sum()\nassertEqual(res, 10)\n", "ds2 = DataStatistics2([1, 2, 3, 4])\nres = ds2.get_min()\nassertEqual(res, 1)\n", "ds2 = DataStatistics2([1, 2, 3, 4])\nres = ds2.get_max()\nassertEqual(res, 4)\n", "ds2 = DataStatistics2([1, 2, 3, 4])\nres = ds2.get_variance...
[]
DREval/107
import math class DataStatistics4: @staticmethod def correlation_coefficient(data1, data2): n = len(data1) mean1 = sum(data1) / n mean2 = sum(data2) / n numerator = sum((data1[i] - mean1) * (data2[i] - mean2) for i in range(n)) denominator = math.sqrt(sum((data1[i] - m...
DataStatistics4
import unittest class DataStatistics4TestCorrelationCoefficient(unittest.TestCase): def test_correlation_coefficient(self): self.assertEqual(DataStatistics4.correlation_coefficient([1, 2, 3], [4, 5, 6]), 0.9999999999999998) def test_correlation_coefficient_2(self): self.assertEqual(DataStatis...
[ "assertEqual(DataStatistics4.correlation_coefficient([1, 2, 3], [4, 5, 6]), 0.9999999999999998)\n", "assertEqual(DataStatistics4.skewness([1, 2, 5]), 2.3760224064818463)\n", "assertEqual(DataStatistics4.kurtosis([1, 2, 5]), -1.5000000000000002)\n", "assertEqual(DataStatistics4.pdf([1, 2, 3], 1, 1),\n[0.398942...
[]
DREval/108
class DecryptionUtils: def __init__(self, key): self.key = key def caesar_decipher(self, ciphertext, shift): plaintext = "" for char in ciphertext: if char.isalpha(): if char.isupper(): ascii_offset = 65 else: ...
DecryptionUtils
import unittest class DecryptionUtilsTestCaesarDecipher(unittest.TestCase): def test_caesar_decipher(self): d = DecryptionUtils('key') self.assertEqual(d.caesar_decipher('ifmmp', 1), 'hello') def test_caesar_decipher_2(self): d = DecryptionUtils('key') self.assertEqual(d.caesa...
[ "d = DecryptionUtils('key')\nassertEqual(d.caesar_decipher('ifmmp', 1), 'hello')\n", "d = DecryptionUtils('key')\nassertEqual(d.vigenere_decipher('ifmmp'), 'ybocl')\n", "d = DecryptionUtils('key')\nassertEqual(d.rail_fence_decipher('Hoo!el,Wrdl l', 3), 'Hello, World!')\n", "d = DecryptionUtils('key')\nassertE...
[]
DREval/109
class DiscountStrategy: def __init__(self, customer, cart, promotion=None): self.customer = customer self.cart = cart self.promotion = promotion self.__total = self.total() def total(self): self.__total = sum(item['quantity'] * item['price'] for item in self.cart) ...
DiscountStrategy
import unittest class DiscountStrategyTestTotal(unittest.TestCase): def test_total_1(self): customer = {'name': 'John Doe', 'fidelity': 1200} cart = [{'product': 'product1', 'quantity': 10, 'price': 20.0}, {'product': 'product2', 'quantity': 5, 'price': 10.0}] order = Disco...
[ "customer = {'name': 'John Doe', 'fidelity': 1200}\ncart = [{'product': 'product1', 'quantity': 10, 'price': 20.0},\n{'product': 'product2', 'quantity': 5, 'price': 10.0}]\norder = DiscountStrategy(customer, cart)\nexpected_total = 250.0\nactual_total = order.total()\nassertEqual(actual_total, expected_total)\n", ...
[]
DREval/110
class EightPuzzle: def __init__(self, initial_state): self.initial_state = initial_state self.goal_state = [[1, 2, 3], [4, 5, 6], [7, 8, 0]] def find_blank(self, state): for i in range(3): for j in range(3): if state[i][j] == 0: return i, ...
EightPuzzle
import unittest class EightPuzzleTestFindBlank(unittest.TestCase): def test_find_blank_1(self): state = [[2, 3, 4], [5, 8, 1], [6, 0, 7]] eightPuzzle = EightPuzzle(state) self.assertEqual(eightPuzzle.find_blank(state), (2, 1)) def test_find_blank_2(self): state = [[2, 3, 4], [5...
[ "state = [[2, 3, 4], [5, 8, 1], [6, 0, 7]]\neightPuzzle = EightPuzzle(state)\nassertEqual(eightPuzzle.find_blank(state), (2, 1))\n", "result = self.eightPuzzle.move(self.initial_state, 'up')\nexpected = [[2, 0, 4], [5, 3, 1], [6, 8, 7]]\nassertEqual(result, expected)\n", "eightPuzzle = EightPuzzle(None)\nstate ...
[]
DREval/111
class EncryptionUtils: def __init__(self, key): self.key = key def caesar_cipher(self, plaintext, shift): ciphertext = "" for char in plaintext: if char.isalpha(): if char.isupper(): ascii_offset = 65 else: ...
EncryptionUtils
import unittest class EncryptionUtilsTestCaesarCipher(unittest.TestCase): def test_caesar_cipher(self): encryption_utils = EncryptionUtils("key") self.assertEqual(encryption_utils.caesar_cipher("abc", 1), "bcd") def test_caesar_cipher_2(self): encryption_utils = EncryptionUtils("key")...
[ "encryption_utils = EncryptionUtils(\"key\")\nassertEqual(encryption_utils.caesar_cipher(\"abc\", 1), \"bcd\")\n", "encryption_utils = EncryptionUtils(\"key\")\nassertEqual(encryption_utils.vigenere_cipher(\"abc\"), \"kfa\")\n", "encryption_utils = EncryptionUtils(\"key\")\nassertEqual(encryption_utils.rail_fen...
[]
DREval/112
import re from collections import deque from decimal import Decimal class ExpressionCalculator: def __init__(self): self.postfix_stack = deque() self.operat_priority = [0, 3, 2, 1, -1, 1, 0, 2] def calculate(self, expression): self.prepare(self.transform(expression)) result_s...
ExpressionCalculator
import unittest class ExpressionCalculatorTestCalculate(unittest.TestCase): def setUp(self): self.expression_calculator = ExpressionCalculator() def test_calculate_1(self): result = self.expression_calculator.calculate("2 + 3 * 4") self.assertEqual(result, 14.0) def test_calculat...
[ "result = self.expression_calculator.calculate(\"2 + 3 * 4\")\nassertEqual(result, 14.0)\n", "self.expression_calculator.prepare(\"2+3*4\")\nassertEqual(self.expression_calculator.postfix_stack, deque(['2', '3', '4', '*', '+']))\n", "assertTrue(self.expression_calculator.is_operator(\"+\"))\n", "result = self...
[]
DREval/113
class FitnessTracker: def __init__(self, height, weight, age, sex) -> None: self.height = height self.weight = weight self.age = age self.sex = sex self.BMI_std = [ {"male": [20, 25]}, {"female": [19, 24]} ] def get_BMI(self): retu...
FitnessTracker
import unittest class FitnessTrackerTestGetBMI(unittest.TestCase): def test_get_BMI(self): fitnessTracker = FitnessTracker(1.8, 70, 20, "male") self.assertEqual(fitnessTracker.get_BMI(), 21.604938271604937) def test_get_BMI_2(self): fitnessTracker = FitnessTracker(1.8, 50, 20, "male")...
[ "fitnessTracker = FitnessTracker(1.8, 70, 20, \"male\")\nassertEqual(fitnessTracker.get_BMI(), 21.604938271604937)\n", "fitnessTracker = FitnessTracker(1.8, 45, 20, \"female\")\nassertEqual(fitnessTracker.condition_judge(), -1)\n", "fitnessTracker = FitnessTracker(1.8, 70, 20, \"female\")\nassertEqual(fitnessTr...
[]
DREval/114
class GomokuGame: def __init__(self, board_size): self.board_size = board_size self.board = [[' ' for _ in range(board_size)] for _ in range(board_size)] self.current_player = 'X' def make_move(self, row, col): if self.board[row][col] == ' ': self.board[row][col] = s...
GomokuGame
import unittest class GomokuGameTestMakeMove(unittest.TestCase): def setUp(self) -> None: self.board_size = 10 self.gomokuGame = GomokuGame(self.board_size) def test_make_move_1(self): board = [[' ' for _ in range(self.board_size)] for _ in range(self.board_size)] self.assertEq...
[ "board = [[' ' for _ in range(self.board_size)] for _ in range(self.board_size)]\nassertEqual(True, self.gomokuGame.make_move(0, 0))\nboard[0][0] = 'X'\nassertEqual(board, self.gomokuGame.board)\n", "gomokuGame = GomokuGame(10)\nassertEqual(None, gomokuGame.check_winner())\n", "assertEqual(True, self.gomokuGame...
[]
DREval/115
class Hotel: def __init__(self, name, rooms): self.name = name self.available_rooms = rooms # available_rooms = {room_type1: room_number1, room_type2: room_number2, ...} # available_rooms = {'single': 5, 'double': 3} self.booked_rooms = {} # booked_rooms = {room_type1...
Hotel
import unittest class HotelTestBookRoom(unittest.TestCase): def setUp(self): self.hotel = Hotel('peace hotel', {'single': 3, 'double': 2}) def test_book_room_1(self): result = self.hotel.book_room('single', 2, 'guest 1') self.assertEqual(result, 'Success!') self.assertEqual(se...
[ "result = self.hotel.book_room('single', 2, 'guest 1')\nassertEqual(result, 'Success!')\nassertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2}})\nassertEqual(self.hotel.available_rooms, {'single': 1, 'double': 2})\n", "self.hotel.check_in('single', 1, 'guest 1')\nassertEqual(self.hotel.booked_rooms, {'si...
[]
DREval/116
class HRManagementSystem: def __init__(self): self.employees = {} def add_employee(self, employee_id, name, position, department, salary): if employee_id in self.employees: return False else: self.employees[employee_id] = { 'name': name, ...
HRManagementSystem
import unittest class HRManagementSystemTestAddEmployee(unittest.TestCase): def test_add_employee(self): hr_system = HRManagementSystem() self.assertEqual(hr_system.add_employee(1, "John Doe", "Manager", "HR", 5000), True) self.assertEqual(hr_system.employees[1], {'name': 'John Doe', 'posit...
[ "hr_system = HRManagementSystem()\nassertEqual(hr_system.add_employee(1, \"John Doe\", \"Manager\", \"HR\", 5000), True)\nassertEqual(hr_system.employees[1], {'name': 'John Doe', 'position': 'Manager', 'department': 'HR', 'salary': 5000})\n", "hr_system = HRManagementSystem()\nhr_system.employees = {1: {'name': '...
[]
DREval/117
import re import string import gensim from bs4 import BeautifulSoup class HtmlUtil: def __init__(self): self.SPACE_MARK = '-SPACE-' self.JSON_MARK = '-JSON-' self.MARKUP_LANGUAGE_MARK = '-MARKUP_LANGUAGE-' self.URL_MARK = '-URL-' self.NUMBER_MARK = '-NUMBER-' self....
HtmlUtil
import unittest import sys class HtmlUtilTestFormatLineFeed(unittest.TestCase): def test_format_line_feed_1(self): self.assertEqual(HtmlUtil._HtmlUtil__format_line_feed('aaa\n\n\n'), 'aaa\n') def test_format_line_feed_2(self): self.assertEqual(HtmlUtil._HtmlUtil__format_line_feed('aaa\n\n\n\n'...
[ "assertEqual(HtmlUtil._HtmlUtil__format_line_feed('aaa\\n\\n\\n'), 'aaa\\n')\n", "htmlutil = HtmlUtil()\nres = htmlutil.format_line_html_text('''\n<html>\n<body>\n<h1>Title</h1>\n<p>This is a paragraph.</p>\n<pre>print('Hello, world!')</pre>\n<p>Another paragraph.</p>\n<pre><code>for i in range(5):\nprint(i)</cod...
[]
DREval/118
class Interpolation: def __init__(self): pass @staticmethod def interpolate_1d(x, y, x_interp): y_interp = [] for xi in x_interp: for i in range(len(x) - 1): if x[i] <= xi <= x[i+1]: yi = y[i] + (y[i+1] - y[i]) * (xi - x[i]) / (x[i+1] ...
Interpolation
import unittest class InterpolationTestInterpolate1d(unittest.TestCase): def test_interpolate_1d(self): interpolation = Interpolation() self.assertEqual(interpolation.interpolate_1d([1, 2, 3], [1, 2, 3], [1.5, 2.5]), [1.5, 2.5]) def test_interpolate_1d_2(self): interpolation = Interpo...
[ "interpolation = Interpolation()\nassertEqual(interpolation.interpolate_1d([1, 2, 3], [1, 2, 3], [1.5, 2.5]), [1.5, 2.5])\n", "interpolation = Interpolation()\nassertEqual(\ninterpolation.interpolate_2d([1, 2, 3], [1, 2, 3], [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [1.5, 2.5],\n[1.5, 2.5]), [3.0, 7.0])\n", "interpola...
[]
DREval/119
class IPAddress: def __init__(self, ip_address): self.ip_address = ip_address def is_valid(self): octets = self.ip_address.split('.') if len(octets) != 4: return False for octet in octets: if not octet.isdigit() or int(octet) < 0 or int(octet) > 255: ...
IPAddress
import unittest class IPAddressTestIsValid(unittest.TestCase): def test_is_valid_1(self): ipaddress = IPAddress("10.10.10.10") self.assertEqual(ipaddress.is_valid(), True) def test_is_valid_2(self): ipaddress = IPAddress("-1.10.10.10") self.assertEqual(ipaddress.is_valid(), Fa...
[ "ipaddress = IPAddress(\"10.10.10.10\")\nassertEqual(ipaddress.is_valid(), True)\n", "ipaddress = IPAddress(\"10.10.10.10\")\nassertEqual(ipaddress.get_octets(), [\"10\", \"10\", \"10\", \"10\"])\n", "ipaddress = IPAddress(\"10.10.10.10\")\nassertEqual(ipaddress.get_binary(), \"00001010.00001010.00001010.000010...
[]
DREval/120
import socket class IpUtil: @staticmethod def is_valid_ipv4(ip_address): try: socket.inet_pton(socket.AF_INET, ip_address) return True except socket.error: return False @staticmethod def is_valid_ipv6(ip_address): try: socket.in...
IpUtil
import unittest class IpUtilTestIsValidIpv4(unittest.TestCase): def test_is_valid_ipv4_1(self): result = IpUtil.is_valid_ipv4('192.168.0.123') self.assertEqual(result, True) def test_is_valid_ipv4_2(self): result = IpUtil.is_valid_ipv4('10.10.10.10') self.assertEqual(result, T...
[ "result = IpUtil.is_valid_ipv4('192.168.0.123')\nassertEqual(result, True)\n", "result = IpUtil.is_valid_ipv6('2001:0db8:85a3:0000:0000:8a2e:0370:7334')\nassertEqual(result, True)\n", "result = IpUtil.get_hostname('110.242.68.3')\nassertEqual(result, None)\n", "result = IpUtil.is_valid_ipv4('192.168.0.123')\n...
[]
DREval/121
class JobMarketplace: def __init__(self): self.job_listings = [] self.resumes = [] def post_job(self, job_title, company, requirements): # requirements = ['requirement1', 'requirement2'] job = {"job_title": job_title, "company": company, "requirements": requirements} sel...
JobMarketplace
import unittest class JobMarketplaceTestPostJob(unittest.TestCase): def test_post_job(self): jobMarketplace = JobMarketplace() jobMarketplace.post_job("Software Engineer", "ABC Company", ['requirement1', 'requirement2']) self.assertEqual(jobMarketplace.job_listings, [{'job_title': 'Software ...
[ "jobMarketplace = JobMarketplace()\njobMarketplace.post_job(\"Software Engineer\", \"ABC Company\", ['requirement1', 'requirement2'])\nassertEqual(jobMarketplace.job_listings, [{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}])\n", "jobMarketplace = Jo...
[]
DREval/122
import numpy as np class KappaCalculator: @staticmethod def kappa(testData, k): dataMat = np.mat(testData) P0 = 0.0 for i in range(k): P0 += dataMat[i, i] * 1.0 xsum = np.sum(dataMat, axis=1) ysum = np.sum(dataMat, axis=0) sum = np.sum(dataMat) ...
KappaCalculator
import unittest class KappaCalculatorTestKappa(unittest.TestCase): def test_kappa_1(self): self.assertAlmostEqual(KappaCalculator.kappa([[2, 1, 1], [1, 2, 1], [1, 1, 2]], 3), 0.25) def test_kappa_2(self): self.assertAlmostEqual(KappaCalculator.kappa([[2, 2, 1], [1, 2, 1], [1, 1, 2]], 3), 0.19...
[ "assertAlmostEqual(KappaCalculator.kappa([[2, 1, 1], [1, 2, 1], [1, 1, 2]], 3), 0.25)\n", "assertAlmostEqual(KappaCalculator.fleiss_kappa([[0, 0, 0, 0, 14],\n[0, 2, 6, 4, 2],\n[0, 0, 3, 5, 6],\n[0, 3, 9, 2, 0],\n[2, 2, 8, 1, 1],\n[7, 7, 0, 0, 0],\n[3, 2, 6, 3, 0],\n[2, 5, 3, 2, 2],\n[6, 5, 2, 1, 0],\n[0, 2, 2, 3,...
[]
DREval/123
import re import string class LongestWord: def __init__(self): self.word_list = [] def add_word(self, word): self.word_list.append(word) def find_longest_word(self, sentence): longest_word = "" sentence = sentence.lower() sentence = re.sub('[%s]' % re.escape(stri...
LongestWord
import unittest class LongestWordTestAddWord(unittest.TestCase): def test_add_word_1(self): longestWord = LongestWord() longestWord.add_word("hello") self.assertEqual(['hello'], longestWord.word_list) def test_add_word_2(self): longestWord = LongestWord() longestWord.ad...
[ "longestWord = LongestWord()\nlongestWord.add_word(\"hello\")\nassertEqual(['hello'], longestWord.word_list)\n", "longestWord = LongestWord()\nlongestWord.add_word(\"a\")\nsentence = 'I am a student.'\nassertEqual('a', longestWord.find_longest_word(sentence))\n" ]
[]
DREval/124
class Manacher: def __init__(self, input_string) -> None: self.input_string = input_string def palindromic_length(self, center, diff, string): if (center - diff == -1 or center + diff == len(string) or string[center - diff] != string[center + diff]): return 0 ...
Manacher
import unittest class ManacherTestPalindromicLength(unittest.TestCase): def test_palindromic_length(self): manacher = Manacher('ababa') self.assertEqual(manacher.palindromic_length(2, 1, 'a|b|a|b|a'), 2) def test_palindromic_length_2(self): manacher = Manacher('ababaxse') self.a...
[ "manacher = Manacher('ababa')\nassertEqual(manacher.palindromic_length(2, 1, 'a|b|a|b|a'), 2)\n", "manacher = Manacher('ababaxse')\nassertEqual(manacher.palindromic_string(), 'ababa')\n", "manacher = Manacher('ababa')\nassertEqual(manacher.palindromic_length(2, 1, 'a|b|a|b|a'), 2)\nassertEqual(manacher.palindro...
[]
DREval/125
class MetricsCalculator: def __init__(self): self.true_positives = 0 self.false_positives = 0 self.false_negatives = 0 self.true_negatives = 0 def update(self, predicted_labels, true_labels): for predicted, true in zip(predicted_labels, true_labels): if predi...
MetricsCalculator
import unittest class MetricsCalculatorTestUpdate(unittest.TestCase): def test_update_1(self): mc = MetricsCalculator() self.assertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (0, 0, 0, 0)) mc.update([1, 1, 0, 0], [1, 0, 0, 1]) self.assertEq...
[ "mc = MetricsCalculator()\nassertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (0, 0, 0, 0))\nmc.update([1, 1, 0, 0], [1, 0, 0, 1])\nassertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (1, 1, 1, 1))\n", "mc = MetricsCalculator()\ntemp...
[]
DREval/126
import numpy as np class MetricsCalculator2: def __init__(self): pass @staticmethod def mrr(data): if type(data) != list and type(data) != tuple: raise Exception("the input must be a tuple([0,...,1,...],int) or a iteration of list of tuple") if len(data) == 0: ...
MetricsCalculator2
import unittest class MetricsCalculator2TestMrr(unittest.TestCase): def test_mrr_1(self): mc2 = MetricsCalculator2() res1, res2 = MetricsCalculator2.mrr(([1, 0, 1, 0], 4)) self.assertEqual(res1, 1.0) self.assertEqual(res2, [1.0]) def test_mrr_2(self): res1, res2 = Metr...
[ "mc2 = MetricsCalculator2()\nres1, res2 = MetricsCalculator2.mrr(([1, 0, 1, 0], 4))\nassertEqual(res1, 1.0)\nassertEqual(res2, [1.0])\n", "res1, res2 = MetricsCalculator2.map(([1, 0, 1, 0], 4))\nassertEqual(res1, 0.41666666666666663)\nassertEqual(res2, [0.41666666666666663])\n", "res1, res2 = MetricsCalculator2...
[]
DREval/127
from datetime import datetime import numpy as np class MovieBookingSystem: def __init__(self): self.movies = [] def add_movie(self, name, price, start_time, end_time, n): movie = { 'name': name, 'price': price, 'start_time': datetime.strptime(start_time, '%H...
MovieBookingSystem
import unittest class MovieBookingSystemTestAddMovie(unittest.TestCase): def setUp(self): self.system = MovieBookingSystem() def tearDown(self): self.system = None def test_add_movie_1(self): self.system.add_movie('Batman', 49.9, '17:05', '19:25', 3) self.assertEqual(len(...
[ "self.system.add_movie('Batman', 49.9, '17:05', '19:25', 3)\nassertEqual(len(self.system.movies), 1)\nassertEqual(self.system.movies[0]['name'], 'Batman')\nassertEqual(self.system.movies[0]['price'], 49.9)\nassertEqual(self.system.movies[0]['start_time'], datetime.strptime('17:05', '%H:%M'))\nassertEqual(self.syste...
[]
DREval/128
class NLPDataProcessor: def construct_stop_word_list(self): stop_word_list = ['a', 'an', 'the'] return stop_word_list def remove_stop_words(self, string_list, stop_word_list): answer = [] for string in string_list: string_split = string.split() for word ...
NLPDataProcessor
import unittest class NLPDataProcessorTestConstruct(unittest.TestCase): def setUp(self): self.processor = NLPDataProcessor() def test_construct_stop_word_list(self): stop_word_list = self.processor.construct_stop_word_list() expected_stop_words = ['a', 'an', 'the'] self.assertE...
[ "stop_word_list = self.processor.construct_stop_word_list()\nexpected_stop_words = ['a', 'an', 'the']\nassertEqual(stop_word_list, expected_stop_words)\n", "string_list = ['This is a test', 'This is an apple', 'This is the dog']\nstop_word_list = ['a', 'an', 'the']\nwords_list = self.processor.remove_stop_words(s...
[]
DREval/129
class NumberConverter: @staticmethod def decimal_to_binary(decimal_num): binary_num = bin(decimal_num)[2:] return binary_num @staticmethod def binary_to_decimal(binary_num): decimal_num = int(binary_num, 2) return decimal_num @staticmethod def decimal_to_octal(d...
NumberConverter
import unittest class NumberConverterTestDecimalToBinary(unittest.TestCase): def test_decimal_to_binary(self): self.assertEqual('1010010110110111', NumberConverter.decimal_to_binary(42423)) def test_decimal_to_binary_2(self): self.assertEqual('101001100010111', NumberConverter.decimal_to_bina...
[ "assertEqual('1010010110110111', NumberConverter.decimal_to_binary(42423))\n", "assertEqual(42423, NumberConverter.binary_to_decimal('1010010110110111'))\n" ]
[]
DREval/130
class NumberWordFormatter: def __init__(self): self.NUMBER = ["", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE"] self.NUMBER_TEEN = ["TEN", "ELEVEN", "TWELVE", "THIRTEEN", "FOURTEEN", "FIFTEEN", "SIXTEEN", "SEVENTEEN", "EIGHTEEN", ...
NumberWordFormatter
import unittest class NumberWordFormatterTestFormat(unittest.TestCase): def test_format_1(self): formatter = NumberWordFormatter() self.assertEqual(formatter.format(123456), "ONE HUNDRED AND TWENTY THREE THOUSAND FOUR HUNDRED AND FIFTY SIX ONLY") def test_format_2(sel...
[ "formatter = NumberWordFormatter()\nassertEqual(formatter.format(123456),\n\"ONE HUNDRED AND TWENTY THREE THOUSAND FOUR HUNDRED AND FIFTY SIX ONLY\")\n", "formatter = NumberWordFormatter()\nassertEqual(formatter.format_string('123456'),\n\"ONE HUNDRED AND TWENTY THREE THOUSAND FOUR HUNDRED AND FIFTY SIX ONLY\")\n...
[]
DREval/131
class NumericEntityUnescaper: def __init__(self): pass def replace(self, string): out = [] pos = 0 length = len(string) while pos < length - 2: if string[pos] == '&' and string[pos + 1] == '#': start = pos + 2 is_hex = False ...
NumericEntityUnescaper
import unittest class NumericEntityUnescaperTestReplace(unittest.TestCase): def test_replace_1(self): unescaper = NumericEntityUnescaper() res = unescaper.replace("&#65;&#66;&#67;") self.assertEqual(res, "ABC") def test_replace_2(self): unescaper = NumericEntityUnescaper() ...
[ "unescaper = NumericEntityUnescaper()\nres = unescaper.replace(\"&#65;&#66;&#67;\")\nassertEqual(res, \"ABC\")\n", "unescaper = NumericEntityUnescaper()\nres = unescaper.is_hex_char('0')\nassertEqual(res, True)\n" ]
[]
DREval/132
class Order: def __init__(self): self.menu = [] # menu = [{"dish": dish name, "price": price, "count": count}, ...] self.selected_dishes = [] # selected_dish = {"dish": dish name, "count": count, price: price} self.sales = {} # def add_dish(self, dish): ...
Order
import unittest class OrderTestAddDish(unittest.TestCase): def setUp(self): self.order = Order() self.order.menu.append({"dish": "dish1", "price": 10, "count": 5}) self.order.menu.append({"dish": "dish2", "price": 15, "count": 3}) self.order.menu.append({"dish": "dish3", "price": ...
[ "result = self.order.add_dish({\"dish\": \"dish3\", \"price\": 15, \"count\": 4})\nassertTrue(result)\n# test the status of menu and selected_dishes\nmenu = self.order.menu\nfor menu_dish in menu:\n\tif menu_dish[\"dish\"] == \"dish1\":\n\t\tassertEqual(menu_dish[\"count\"], 5)\n\tif menu_dish[\"dish\"] == \"dish2\...
[]
DREval/133
class PageUtil: def __init__(self, data, page_size): self.data = data self.page_size = page_size self.total_items = len(data) self.total_pages = (self.total_items + page_size - 1) // page_size def get_page(self, page_number): if page_number < 1 or page_number > self.tota...
PageUtil
import unittest class PageUtilTestGetPage(unittest.TestCase): def setUp(self): self.data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] self.page_size = 3 self.page_util = PageUtil(self.data, self.page_size) def test_get_page_1(self): page_number = 1 expected_page = [1, 2, 3] ...
[ "page_number = 1\nexpected_page = [1, 2, 3]\nactual_page = self.page_util.get_page(page_number)\nassertEqual(actual_page, expected_page)\n", "page_number = 2\nexpected_info = {\n\"current_page\": 2,\n\"per_page\": 3,\n\"total_pages\": 4,\n\"total_items\": 10,\n\"has_previous\": True,\n\"has_next\": True,\n\"data\...
[]
DREval/134
class PersonRequest: def __init__(self, name: str, sex: str, phoneNumber: str): self.name = self._validate_name(name) self.sex = self._validate_sex(sex) self.phoneNumber = self._validate_phoneNumber(phoneNumber) def _validate_name(self, name: str) -> str: if not name: ...
PersonRequest
import unittest class PersonRequestTestValidateName(unittest.TestCase): def test_validate_name_1(self): pr = PersonRequest("", "Man", "12345678901") self.assertIsNone(pr.name) def test_validate_name_2(self): pr = PersonRequest("This is a very long name that exceeds the character limit...
[ "pr = PersonRequest(\"\", \"Man\", \"12345678901\")\nassertIsNone(pr.name)\n", "pr = PersonRequest(\"John Doe\", \"Unknown\", \"12345678901\")\nassertIsNone(pr.sex)\n", "pr = PersonRequest(\"John Doe\", \"Man\", \"\")\nassertIsNone(pr.phoneNumber)\n", "pr = PersonRequest(\"\", \"Man\", \"12345678901\")\nasser...
[]
DREval/135
class PushBoxGame: def __init__(self, map): self.map = map self.player_row = 0 self.player_col = 0 self.targets = [] self.boxes = [] self.target_count = 0 self.is_game_over = False self.init_game() def init_game(self): for row in range(le...
PushBoxGame
import unittest class PushBoxGameTestInitGame(unittest.TestCase): def setUp(self) -> None: self.game_map = [ "#####", "#O #", "# X #", "# G#", "#####" ] self.game = PushBoxGame(self.game_map) def test_init_game_1(self): ...
[ "assertEqual(self.game.map, self.game_map)\n", "assertFalse(self.game.check_win())\n", "moves = ['d', 's', 'a', 's']\nfor move in moves:\n\tassertFalse(self.game.move(move))\nassertTrue(self.game.move('d'))\n" ]
[]
DREval/136
class RPGCharacter: def __init__(self, name, hp, attack_power, defense, level=1): self.name = name self.hp = hp self.attack_power = attack_power self.defense = defense self.level = level self.exp = 0 def attack(self, other_character): damage = max(self.at...
RPGCharacter
import unittest class RPGCharacterTestAttack(unittest.TestCase): def test_attack(self): character1 = RPGCharacter("John", 100, 20, 10) character2 = RPGCharacter("Enemy", 100, 15, 5) character1.attack(character2) self.assertEqual(character2.hp, 85) def test_attack_2(self): ...
[ "character1 = RPGCharacter(\"John\", 100, 20, 10)\ncharacter2 = RPGCharacter(\"Enemy\", 100, 15, 5)\ncharacter1.attack(character2)\nassertEqual(character2.hp, 85)\n", "character = RPGCharacter(\"John\", 90, 20, 10)\ncharacter.heal()\nassertEqual(character.hp, 100)\n", "character = RPGCharacter(\"John\", 100, 20...
[]
DREval/137
class Server: def __init__(self): self.white_list = [] self.send_struct = {} self.receive_struct = {} def add_white_list(self, addr): if addr in self.white_list: return False else: self.white_list.append(addr) return self.white_list ...
Server
import unittest class ServerTestAddWhiteList(unittest.TestCase): def test_add_white_list_1(self): server = Server() server.add_white_list(88) self.assertEqual(server.white_list, [88]) def test_add_white_list_2(self): server = Server() server.add_white_list(88) ...
[ "server = Server()\nserver.add_white_list(88)\nassertEqual(server.white_list, [88])\n", "server = Server()\nserver.add_white_list(88)\nserver.del_white_list(88)\nassertEqual(server.white_list, [])\n", "server = Server()\nserver.add_white_list(88)\nserver.recv({\"addr\": 88, \"content\": \"abc\"})\nassertEqual(s...
[]
DREval/138
class ShoppingCart: def __init__(self): self.items = {} def add_item(self, item, price, quantity=1): if item in self.items: self.items[item] = {'price': price, 'quantity': quantity} else: self.items[item] = {'price': price, 'quantity': quantity} def remove_i...
ShoppingCart
import unittest class ShoppingCartTestAddItem(unittest.TestCase): def test_add_item_1(self): shoppingcart = ShoppingCart() shoppingcart.add_item("apple", 1, 5) self.assertEqual(shoppingcart.items, {"apple": {"price": 1, "quantity": 5}}) def test_add_item_2(self): shoppingcart ...
[ "shoppingcart = ShoppingCart()\nshoppingcart.add_item(\"apple\", 1, 5)\nassertEqual(shoppingcart.items, {\"apple\": {\"price\": 1, \"quantity\": 5}})\n", "shoppingcart = ShoppingCart()\nshoppingcart.add_item(\"apple\", 1, 5)\nshoppingcart.remove_item(\"apple\", 3)\nassertEqual(shoppingcart.items, {\"apple\": {\"p...
[]
DREval/139
class SignInSystem: def __init__(self): self.users = {} def add_user(self, username): if username in self.users: return False else: self.users[username] = False return True def sign_in(self, username): if username not in self.users: ...
SignInSystem
import unittest class SignInSystemTestAddUser(unittest.TestCase): def test_add_user_1(self): signin_system = SignInSystem() result = signin_system.add_user("user1") self.assertTrue(result) def test_add_user_2(self): signin_system = SignInSystem() signin_system.add_user...
[ "signin_system = SignInSystem()\nresult = signin_system.add_user(\"user1\")\nassertTrue(result)\n", "signin_system = SignInSystem()\nsignin_system.add_user(\"user1\")\nresult = signin_system.sign_in(\"user1\")\nassertTrue(result)\n", "signin_system = SignInSystem()\nsignin_system.add_user(\"user1\")\nsignin_sys...
[]
DREval/140
import re class SplitSentence: def split_sentences(self, sentences_string): sentences = re.split(r'(?<!\w\.\w.)(?<![A-Z][a-z]\.)(?<=\.|\?)\s', sentences_string) return sentences def count_words(self, sentence): sentence = re.sub(r'[^a-zA-Z\s]', '', sentence) words = sentence....
SplitSentence
import unittest class SplitSentenceTestSplitSentences(unittest.TestCase): def test_split_sentences_1(self): ss = SplitSentence() lst = ss.split_sentences("aaa aaaa. bb bbbb bbb? cccc cccc. dd ddd?") self.assertEqual(lst, ['aaa aaaa.', 'bb bbbb bbb?', 'cccc cccc.', 'dd ddd?']) def test...
[ "ss = SplitSentence()\nlst = ss.split_sentences(\"aaa aaaa. bb bbbb bbb? cccc cccc. dd ddd?\")\nassertEqual(lst, ['aaa aaaa.', 'bb bbbb bbb?', 'cccc cccc.', 'dd ddd?'])\n", "ss = SplitSentence()\ncnt = ss.count_words(\"abc def\")\nassertEqual(cnt, 2)\n", "ss = SplitSentence()\ncnt = ss.process_text_file(\"aaa a...
[]
DREval/141
class SQLGenerator: def __init__(self, table_name): self.table_name = table_name def select(self, fields=None, condition=None): if fields is None: fields = "*" else: fields = ", ".join(fields) sql = f"SELECT {fields} FROM {self.table_name}" if con...
SQLGenerator
import unittest class SQLGeneratorTestSelect(unittest.TestCase): def test_select_1(self): sql = SQLGenerator('table1') result = sql.select(['field1'], "field2 = value1") self.assertEqual(result, "SELECT field1 FROM table1 WHERE field2 = value1;") def test_select_2(self): sql = ...
[ "sql = SQLGenerator('table1')\nresult = sql.select(['field1'], \"field2 = value1\")\nassertEqual(result, \"SELECT field1 FROM table1 WHERE field2 = value1;\")\n", "sql = SQLGenerator('table1')\nresult = sql.insert({'field1': 'value1', 'field2': 'value2'})\nassertEqual(result, \"INSERT INTO table1 (field1, field2)...
[]
DREval/142
class SQLQueryBuilder: @staticmethod def select(table, columns='*', where=None): if columns != '*': columns = ', '.join(columns) query = f"SELECT {columns} FROM {table}" if where: query += " WHERE " + ' AND '.join(f"{k}='{v}'" for k, v in where.items()) r...
SQLQueryBuilder
import unittest class SQLQueryBuilderTestSelect(unittest.TestCase): def test_select_1(self): self.assertEqual( SQLQueryBuilder.select('users', ["id", "name"], {'age': 30}), "SELECT id, name FROM users WHERE age='30'" ) def test_select_2(self): self.assertEqual(...
[ "assertEqual(\nSQLQueryBuilder.select('users', [\"id\", \"name\"], {'age': 30}),\n\"SELECT id, name FROM users WHERE age='30'\"\n)\n", "assertEqual(\nSQLQueryBuilder.insert('users', {'name': 'Tom', 'age': 30}),\n\"INSERT INTO users (name, age) VALUES ('Tom', '30')\"\n)\n", "assertEqual(\nSQLQueryBuilder.delete(...
[]
DREval/143
import math class Statistics3: @staticmethod def median(data): sorted_data = sorted(data) n = len(sorted_data) if n % 2 == 1: return sorted_data[n // 2] else: return (sorted_data[n // 2 - 1] + sorted_data[n // 2]) / 2 @staticmethod def mode(data):...
Statistics3
import unittest class Statistics3TestMedian(unittest.TestCase): def test_median(self): statistics3 = Statistics3() self.assertEqual(statistics3.median([1, 2, 3, 4]), 2.5) def test_median_2(self): statistics3 = Statistics3() self.assertEqual(statistics3.median([1, 2, 3, 4, 5]), ...
[ "statistics3 = Statistics3()\nassertEqual(statistics3.median([1, 2, 3, 4]), 2.5)\n", "statistics3 = Statistics3()\nassertEqual(statistics3.mode([1, 2, 3, 3]), [3])\n", "statistics3 = Statistics3()\nassertEqual(statistics3.correlation([1, 2, 3], [4, 5, 6]), 1.0)\n", "statistics3 = Statistics3()\nassertEqual(st...
[]
DREval/144
class StockPortfolioTracker: def __init__(self, cash_balance): self.portfolio = [] self.cash_balance = cash_balance def add_stock(self, stock): for pf in self.portfolio: if pf['name'] == stock['name']: pf['quantity'] += stock['quantity'] retur...
StockPortfolioTracker
import unittest class StockPortfolioTrackerTestAddStock(unittest.TestCase): def test_add_stock(self): tracker = StockPortfolioTracker(10000.0) tracker.add_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity...
[ "tracker = StockPortfolioTracker(10000.0)\ntracker.add_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10})\nassertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}])\n", "tracker = StockPortfolioTracker(10000.0)\ntracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity'...
[]
DREval/145
import time class Thermostat: def __init__(self, current_temperature, target_temperature, mode): self.current_temperature = current_temperature self.target_temperature = target_temperature self.mode = mode def get_target_temperature(self): return self.target_temperature de...
Thermostat
import unittest class ThermostatTestGetTargetTemperature(unittest.TestCase): def test_get_target_temperature_1(self): t = Thermostat(20, 25, 'heat') self.assertEqual(t.get_target_temperature(), 25) def test_get_target_temperature_2(self): t = Thermostat(20, 25, 'cool') self.ass...
[ "t = Thermostat(20, 25, 'heat')\nassertEqual(t.get_target_temperature(), 25)\n", "t = Thermostat(20, 25, 'heat')\nt.set_target_temperature(30)\nassertEqual(t.get_target_temperature(), 30)\n", "t = Thermostat(20, 25, 'heat')\nassertEqual(t.get_mode(), 'heat')\n", "t = Thermostat(20, 25, 'heat')\nt.set_mode('co...
[]
DREval/146
from math import pi, fabs class TriCalculator: def __init__(self): pass def cos(self, x): return round(self.taylor(x, 50), 10) def factorial(self, a): b = 1 while a != 1: b *= a a -= 1 return b def taylor(self, x, n): a = 1 ...
TriCalculator
import unittest class TriCalculatorTestCos(unittest.TestCase): def test_cos_1(self): tricalculator = TriCalculator() self.assertEqual(tricalculator.cos(60), 0.5) def test_cos_2(self): tricalculator = TriCalculator() self.assertAlmostEqual(tricalculator.cos(30), 0.8660254038) ...
[ "tricalculator = TriCalculator()\nassertEqual(tricalculator.cos(60), 0.5)\n", "tricalculator = TriCalculator()\nassertEqual(tricalculator.factorial(5), 120)\n", "tricalculator = TriCalculator()\nassertAlmostEqual(tricalculator.taylor(60, 50), 0.5)\n", "tricalculator = TriCalculator()\nassertEqual(tricalculato...
[]
DREval/147
class URLHandler: def __init__(self, url): self.url = url def get_scheme(self): scheme_end = self.url.find("://") if scheme_end != -1: return self.url[:scheme_end] return None def get_host(self): scheme_end = self.url.find("://") if scheme_end !=...
URLHandler
import unittest class URLHandlerTestGetScheme(unittest.TestCase): def test_get_scheme_1(self): urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page") temp = urlhandler.get_scheme() self.assertEqual(temp, "https") def test_get_scheme_2(self): urlhandler = URLH...
[ "urlhandler = URLHandler(\"https://www.baidu.com/s?wd=aaa&rsv_spt=1#page\")\ntemp = urlhandler.get_scheme()\nassertEqual(temp, \"https\")\n", "urlhandler = URLHandler(\"https://www.baidu.com/s?wd=aaa&rsv_spt=1#page\")\ntemp = urlhandler.get_host()\nassertEqual(temp, \"www.baidu.com\")\n", "urlhandler = URLHandl...
[]
DREval/148
import urllib.parse class UrlPath: def __init__(self): self.segments = [] self.with_end_tag = False def add(self, segment): self.segments.append(self.fix_path(segment)) def parse(self, path, charset): if path: if path.endswith('/'): self.with_e...
UrlPath
import unittest class UrlPathTestAdd(unittest.TestCase): def test_add_1(self): url_path = UrlPath() url_path.add('foo') url_path.add('bar') self.assertEqual(url_path.segments, ['foo', 'bar']) def test_add_2(self): url_path = UrlPath() url_path.add('aaa') ...
[ "url_path = UrlPath()\nurl_path.add('foo')\nurl_path.add('bar')\nassertEqual(url_path.segments, ['foo', 'bar'])\n", "url_path = UrlPath()\nurl_path.parse('/foo/bar/', 'utf-8')\nassertEqual(url_path.segments, ['foo', 'bar'])\nassertEqual(url_path.with_end_tag, True)\n", "fixed_path = UrlPath.fix_path('/foo/bar/'...
[]
DREval/149
import numpy as np from gensim import matutils from numpy import dot, array class VectorUtil: @staticmethod def similarity(vector_1, vector_2): return dot(matutils.unitvec(vector_1), matutils.unitvec(vector_2)) @staticmethod def cosine_similarities(vector_1, vectors_all): norm = np.li...
VectorUtil
import unittest class VectorUtilTestSimilarity(unittest.TestCase): def test_similarity_1(self): vector_1 = np.array([1, 1]) vector_2 = np.array([1, 0]) similarity = VectorUtil.similarity(vector_1, vector_2) self.assertAlmostEqual(similarity, 0.7071067811865475) def test_simila...
[ "vector_1 = np.array([1, 1])\nvector_2 = np.array([1, 0])\nsimilarity = VectorUtil.similarity(vector_1, vector_2)\nassertAlmostEqual(similarity, 0.7071067811865475)\n", "vector1 = np.array([1, 1])\nvectors_all = [np.array([1, 0]), np.array([1, 1])]\nsimilarities = VectorUtil.cosine_similarities(vector1, vectors_a...
[]
DREval/150
class VendingMachine: def __init__(self): self.inventory = {} self.balance = 0 def add_item(self, item_name, price, quantity): if not self.restock_item(item_name, quantity): self.inventory[item_name] = {'price': price, 'quantity': quantity} def insert_coin(self, amount)...
VendingMachine
import unittest class VendingMachineTestAddItem(unittest.TestCase): def test_add_item(self): vendingMachine = VendingMachine() vendingMachine.add_item('Coke', 1.25, 10) self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}}) def test_add_item_2(self): ...
[ "vendingMachine = VendingMachine()\nvendingMachine.add_item('Coke', 1.25, 10)\nassertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}})\n", "vendingMachine = VendingMachine()\nassertEqual(vendingMachine.insert_coin(1.25), 1.25)\n", "vendingMachine = VendingMachine()\nvendingMachine.inven...
[]
DREval/151
class Warehouse: def __init__(self): self.inventory = {} # Product ID: Product self.orders = {} # Order ID: Order def add_product(self, product_id, name, quantity): if product_id not in self.inventory: self.inventory[product_id] = {'name': name, 'quantity': quantity} ...
Warehouse
import unittest class WarehouseTestAddProduct(unittest.TestCase): def test_add_product_1(self): warehouse = Warehouse() warehouse.add_product(1, 'product 1', 10) self.assertEqual(warehouse.inventory, {1: {'name': 'product 1', 'quantity': 10}}) def test_add_product_2(self): war...
[ "warehouse = Warehouse()\nwarehouse.add_product(1, 'product 1', 10)\nassertEqual(warehouse.inventory, {1: {'name': 'product 1', 'quantity': 10}})\n", "warehouse = Warehouse()\nwarehouse.add_product(1, 'product 1', 10)\nwarehouse.update_product_quantity(1, 5)\nassertEqual(warehouse.inventory, {1: {'name': 'product...
[]
DREval/152
class WeatherSystem: def __init__(self, city) -> None: self.temperature = None self.weather = None self.city = city self.weather_list = {} def query(self, weather_list, tmp_units = 'celsius'): self.weather_list = weather_list if self.city not in weather_list:...
WeatherSystem
import unittest class WeatherSystemTestQuery(unittest.TestCase): def test_query(self): weatherSystem = WeatherSystem('New York') weather_list = { 'New York': { 'weather': 'sunny', 'temperature': 27, 'temperature units': 'celsius' ...
[ "weatherSystem = WeatherSystem('New York')\nweather_list = {\n'New York': {\n'weather': 'sunny',\n'temperature': 27,\n'temperature units': 'celsius'\n},\n'Beijing': {\n'weather': 'cloudy',\n'temperature': 23,\n'temperature units': 'celsius'\n}\n}\nassertEqual(weatherSystem.query(weather_list), (27, 'sunny'))\n", ...
[]
DREval/153
class Words2Numbers: def __init__(self): self.numwords = {} self.units = [ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"...
Words2Numbers
import unittest class Words2NumbersTestText2Int(unittest.TestCase): def test_text2int(self): w2n = Words2Numbers() self.assertEqual(w2n.text2int("thirty-two"), "32") def test_text2int2(self): w2n = Words2Numbers() self.assertEqual(w2n.text2int("one hundred and twenty-three"), ...
[ "w2n = Words2Numbers()\nassertEqual(w2n.text2int(\"thirty-two\"), \"32\")\n", "w2n = Words2Numbers()\nassertTrue(w2n.is_valid_input(\"twenty-five thousand three hundred and forty-two\"))\n", "w2n = Words2Numbers()\nassertEqual(w2n.is_valid_input(\"seventy two thousand and hundred eleven\"), True)\nassertEqual(w...
[]