task_id stringlengths 11 12 | skeleton stringlengths 929 4.57k | test stringlengths 1.48k 20.1k | solution_code stringlengths 496 3.91k | import_statement listlengths 0 4 | class_description stringlengths 69 249 | methods_info listlengths 2 10 | class_name stringlengths 4 24 | test_classes listlengths 2 11 | class_constructor stringlengths 15 1.13k | fields listlengths 0 9 |
|---|---|---|---|---|---|---|---|---|---|---|
ClassEval_0 | import logging
import datetime
class AccessGatewayFilter:
"""
This class is a filter used for accessing gateway filtering, primarily for authentication and access log recording.
"""
def __init__(self):
pass
def filter(self, request):
"""
Filter the incoming request based o... | import unittest
class AccessGatewayFilterTestFilter(unittest.TestCase):
def test_filter_1(self):
agf = AccessGatewayFilter()
request = {'path': '/api/data', 'method': 'GET'}
res = agf.filter(request)
self.assertTrue(res)
def test_filter_2(self):
agf = AccessGatewayFilte... | import logging
import datetime
class AccessGatewayFilter:
def __init__(self):
pass
def filter(self, request):
request_uri = request['path']
method = request['method']
if self.is_start_with(request_uri):
return True
try:
token = self.get_jwt_u... | [
"import logging",
"import datetime"
] | """
This class is a filter used for accessing gateway filtering, primarily for authentication and access log recording.
"""
| [
{
"method_name": "filter",
"method_description": "def filter(self, request):\n \"\"\"\n Filter the incoming request based on certain rules and conditions.\n :param request: dict, the incoming request details\n :return: bool, True if the request is allowed, False otherwise\n ... | AccessGatewayFilter | [
"AccessGatewayFilterTestFilter",
"AccessGatewayFilterTestIsStartWith",
"AccessGatewayFilterTestGetJwtUser",
"AccessGatewayFilterTest"
] | class AccessGatewayFilter:
def __init__(self):
pass
| [] |
ClassEval_1 | import math
class AreaCalculator:
"""
This is a class for calculating the area of different shapes, including circle, sphere, cylinder, sector and annulus.
"""
def __init__(self, radius):
"""
Initialize the radius for shapes.
:param radius: float
"""
self.radius... | import unittest
class AreaCalculatorTestCalculateCircleArea(unittest.TestCase):
def test_calculate_circle_area(self):
areaCalculator = AreaCalculator(2)
self.assertAlmostEqual(12.56, areaCalculator.calculate_circle_area(), delta=0.01)
def test_calculate_circle_area_2(self):
areaCalculat... | import math
class AreaCalculator:
def __init__(self, radius):
self.radius = radius
def calculate_circle_area(self):
return math.pi * self.radius ** 2
def calculate_sphere_area(self):
return 4 * math.pi * self.radius ** 2
def calculate_cylinder_area(self, height):
re... | [
"import math"
] | """
This is a class for calculating the area of different shapes, including circle, sphere, cylinder, sector and annulus.
"""
| [
{
"method_name": "calculate_circle_area",
"method_description": "def calculate_circle_area(self):\n \"\"\"\n calculate the area of circle based on self.radius\n :return: area of circle, float\n >>> areaCalculator = AreaCalculator(2)\n >>> areaCalculator.calculate_circle_ar... | AreaCalculator | [
"AreaCalculatorTestCalculateCircleArea",
"AreaCalculatorTestCalculateSphereArea",
"AreaCalculatorTestCalculateCylinderArea",
"AreaCalculatorTestCalculateSectorArea",
"AreaCalculatorTestCalculateAnnulusArea",
"AreaCalculatorTestCalculateMain"
] | class AreaCalculator:
def __init__(self, radius):
"""
Initialize the radius for shapes.
:param radius: float
"""
self.radius = radius
| [
"self.radius"
] |
ClassEval_2 | class ArgumentParser:
"""
This is a class for parsing command line arguments to a dictionary.
"""
def __init__(self):
"""
Initialize the fields.
self.arguments is a dict that stores the args in a command line
self.requried is a set that stores the required arguments
... | import unittest
class ArgumentParserTestParseArguments(unittest.TestCase):
def setUp(self):
self.parser = ArgumentParser()
# key value arguments
def test_parse_arguments_1(self):
command_str = "script --name=John --age=25"
self.parser.add_argument("name")
self.parser.add_a... | class ArgumentParser:
def __init__(self):
self.arguments = {}
self.required = set()
self.types = {}
def parse_arguments(self, command_string):
args = command_string.split()[1:]
for i in range(len(args)):
arg = args[i]
if arg.startswith('--'):
... | [] | """
This is a class for parsing command line arguments to a dictionary.
"""
| [
{
"method_name": "parse_arguments",
"method_description": "def parse_arguments(self, command_string):\n \"\"\"\n Parses the given command line argument string and invoke _convert_type to stores the parsed result in specific type in the arguments dictionary.\n Checks for missing required... | ArgumentParser | [
"ArgumentParserTestParseArguments",
"ArgumentParserTestGetArgument",
"ArgumentParserTestAddArgument",
"ArgumentParserTestConvertType",
"ArgumentParserTestMain"
] | class ArgumentParser:
def __init__(self):
"""
Initialize the fields.
self.arguments is a dict that stores the args in a command line
self.requried is a set that stores the required arguments
self.types is a dict that stores type of every arguments.
>>> parser.argumen... | [
"self.arguments",
"self.required",
"self.types"
] |
ClassEval_3 | import itertools
class ArrangementCalculator:
"""
The Arrangement class provides permutation calculations and selection operations for a given set of data elements.
"""
def __init__(self, datas):
"""
Initializes the ArrangementCalculator object with a list of datas.
:param data... | import unittest
class ArrangementCalculatorTestCount(unittest.TestCase):
def test_count_1(self):
res = ArrangementCalculator.count(5, 3)
self.assertEqual(res, 60)
def test_count_2(self):
res = ArrangementCalculator.count(4, 3)
self.assertEqual(res, 24)
def test_count_3(se... | import itertools
class ArrangementCalculator:
def __init__(self, datas):
self.datas = datas
@staticmethod
def count(n, m=None):
if m is None or n == m:
return ArrangementCalculator.factorial(n)
else:
return ArrangementCalculator.factorial(n) // ArrangementC... | [
"import itertools"
] | """
The Arrangement class provides permutation calculations and selection operations for a given set of data elements.
"""
| [
{
"method_name": "count",
"method_description": "def count(n, m=None):\n \"\"\"\n Counts the number of arrangements by choosing m items from n items (permutations).\n If m is not provided or n equals m, returns factorial(n).\n :param n: int, the total number of items.\n :p... | ArrangementCalculator | [
"ArrangementCalculatorTestCount",
"ArrangementCalculatorTestCountAll",
"ArrangementCalculatorTestSelect",
"ArrangementCalculatorTestSelectAll",
"ArrangementCalculatorTestFactorial",
"ArrangementCalculatorTest"
] | class ArrangementCalculator:
def __init__(self, datas):
"""
Initializes the ArrangementCalculator object with a list of datas.
:param datas: List, the data elements to be used for arrangements.
"""
self.datas = datas
| [
"self.datas"
] |
ClassEval_4 | class AssessmentSystem:
"""
This is a class as an student assessment system, which supports add student, add course score, calculate GPA, and other functions for students and courses.
"""
def __init__(self):
"""
Initialize the students dict in assessment system.
"""
self... | import unittest
class AssessmentSystemTestAddStudent(unittest.TestCase):
def test_add_student(self):
assessment_system = AssessmentSystem()
assessment_system.add_student("Alice", 3, "Mathematics")
self.assertEqual(assessment_system.students["Alice"],
{'name': 'Alice... | class AssessmentSystem:
def __init__(self):
self.students = {}
def add_student(self, name, grade, major):
self.students[name] = {'name': name, 'grade': grade, 'major': major, 'courses': {}}
def add_course_score(self, name, course, score):
if name in self.students:
self.... | [] | """
This is a class as an student assessment system, which supports add student, add course score, calculate GPA, and other functions for students and courses.
"""
| [
{
"method_name": "add_student",
"method_description": "def add_student(self, name, grade, major):\n \"\"\"\n Add a new student into self.students dict\n :param name: str, student name\n :param grade: int, student grade\n :param major: str, student major\n >>> system... | AssessmentSystem | [
"AssessmentSystemTestAddStudent",
"AssessmentSystemTestAddCourseScore",
"AssessmentSystemTestGetGPA",
"AssessmentSystemTestGetAllStudentsWithFailCourse",
"AssessmentSystemTestGetCourseAverage",
"AssessmentSystemTestGetTopStudent",
"AssessmentSystemTestMain"
] | class AssessmentSystem:
def __init__(self):
"""
Initialize the students dict in assessment system.
"""
self.students = {}
| [
"self.students"
] |
ClassEval_5 | '''
# This class is an automatic guitar simulator that can interpret and play based on the input guitar sheet music.
class AutomaticGuitarSimulator:
def __init__(self, text) -> None:
"""
Initialize the score to be played
:param text:str, score to be played
"""
self.play_text... | import unittest
class AutomaticGuitarSimulatorTestInterpret(unittest.TestCase):
def test_interpret_1(self):
context = AutomaticGuitarSimulator("C53231323")
play_list = context.interpret()
self.assertEqual(play_list, [{'Chord': 'C', 'Tune': '53231323'}])
def test_interpret_2(self):
... | class AutomaticGuitarSimulator:
def __init__(self, text) -> None:
self.play_text = text
def interpret(self, display=False):
if not self.play_text.strip():
return []
else:
play_list = []
play_segs = self.play_text.split(" ")
for play_seg in... | [] | """
This class is an automatic guitar simulator that can interpret and play based on the input guitar sheet music.
"""
| [
{
"method_name": "interpret",
"method_description": "def interpret(self, display=False):\n \"\"\"\n Interpret the music score to be played\n :param display:Bool, representing whether to print the interpreted score\n :return: list of dict, The dict includes two fields, Chord and Tune, which are l... | AutomaticGuitarSimulator | [
"AutomaticGuitarSimulatorTestInterpret",
"AutomaticGuitarSimulatorTestDisplay",
"AutomaticGuitarSimulatorTest"
] | class AutomaticGuitarSimulator:
def __init__(self, text) -> None:
"""
Initialize the score to be played
:param text:str, score to be played
"""
self.play_text = text
| [
"self.play_text"
] |
ClassEval_6 | class AvgPartition:
"""
This is a class that partitions the given list into different blocks by specifying the number of partitions, with each block having a uniformly distributed length.
"""
def __init__(self, lst, limit):
"""
Initialize the class with the given list and the number of ... | import unittest
class AvgPartitionTestSetNum(unittest.TestCase):
def test_setNum(self):
a = AvgPartition([1, 2, 3, 4], 2)
self.assertEqual(a.setNum(), (2, 0))
def test_setNum_2(self):
a = AvgPartition([1, 2, 3, 4, 5], 2)
self.assertEqual(a.setNum(), (2, 1))
def test_setNum... | class AvgPartition:
def __init__(self, lst, limit):
self.lst = lst
self.limit = limit
def setNum(self):
size = len(self.lst) // self.limit
remainder = len(self.lst) % self.limit
return size, remainder
def get(self, index):
size, remainder = self.set... | [] | """
This is a class that partitions the given list into different blocks by specifying the number of partitions, with each block having a uniformly distributed length.
"""
| [
{
"method_name": "setNum",
"method_description": "def setNum(self):\n \"\"\"\n Calculate the size of each block and the remainder of the division.\n :return: the size of each block and the remainder of the division, tuple.\n >>> a = AvgPartition([1, 2, 3, 4], 2)\n >>> a.se... | AvgPartition | [
"AvgPartitionTestSetNum",
"AvgPartitionTestGet",
"AvgPartitionTestMain"
] | class AvgPartition:
def __init__(self, lst, limit):
"""
Initialize the class with the given list and the number of partitions, and check if the number of partitions is greater than 0.
"""
self.lst = lst
self.limit = limit
| [
"self.limit",
"self.lst"
] |
ClassEval_7 | class BalancedBrackets:
"""
This is a class that checks for bracket matching
"""
def __init__(self, expr):
"""
Initializes the class with an expression.
:param expr: The expression to check for balanced brackets,str.
"""
self.stack = []
self.left_brackets... | import unittest
class BalancedBracketsTestClearExpr(unittest.TestCase):
def test_clear_expr(self):
b = BalancedBrackets("a(b)c")
b.clear_expr()
self.assertEqual(b.expr, "()")
def test_clear_expr_2(self):
b = BalancedBrackets("a(b){c}")
b.clear_expr()
self.asser... | class BalancedBrackets:
def __init__(self, expr):
self.stack = []
self.left_brackets = ["(", "{", "["]
self.right_brackets = [")", "}", "]"]
self.expr = expr
def clear_expr(self):
self.expr = ''.join(c for c in self.expr if (c in self.left_brackets or c in self.right_bra... | [] | """
This is a class that checks for bracket matching
"""
| [
{
"method_name": "clear_expr",
"method_description": "def clear_expr(self):\n \"\"\"\n Clears the expression of all characters that are not brackets.\n >>> b = BalancedBrackets(\"a(b)c\")\n >>> b.clear_expr()\n >>> b.expr\n '()'\n\n \"\"\"",
"test_class":... | BalancedBrackets | [
"BalancedBracketsTestClearExpr",
"BalancedBracketsTestCheckBalancedBrackets",
"BalancedBracketsTestMain"
] | class BalancedBrackets:
def __init__(self, expr):
"""
Initializes the class with an expression.
:param expr: The expression to check for balanced brackets,str.
"""
self.stack = []
self.left_brackets = ["(", "{", "["]
self.right_brackets = [")", "}", "]"]
... | [
"self.expr",
"self.left_brackets",
"self.right_brackets",
"self.stack"
] |
ClassEval_8 | class BankAccount:
"""
This is a class as a bank account system, which supports deposit money, withdraw money, view balance, and transfer money.
"""
def __init__(self, balance=0):
"""
Initializes a bank account object with an attribute balance, default value is 0.
"""
se... | import unittest
class BankAccountTestDeposit(unittest.TestCase):
def test_deposit(self):
account1 = BankAccount()
ret = account1.deposit(1000)
self.assertEqual(ret, 1000)
def test_deposit_2(self):
account1 = BankAccount()
account1.deposit(1000)
ret = account1.d... | class BankAccount:
def __init__(self, balance=0):
self.balance = balance
def deposit(self, amount):
if amount < 0:
raise ValueError("Invalid amount")
self.balance += amount
return self.balance
def withdraw(self, amount):
if amount < 0:
raise ... | [] | """
This is a class as a bank account system, which supports deposit money, withdraw money, view balance, and transfer money.
"""
| [
{
"method_name": "deposit",
"method_description": "def deposit(self, amount):\n \"\"\"\n Deposits a certain amount into the account, increasing the account balance, return the current account balance.\n If amount is negative, raise a ValueError(\"Invalid amount\").\n :param amoun... | BankAccount | [
"BankAccountTestDeposit",
"BankAccountTestWithdraw",
"BankAccountTestViewBalance",
"BankAccountTestTransfer",
"BankAccountTest"
] | class BankAccount:
def __init__(self, balance=0):
"""
Initializes a bank account object with an attribute balance, default value is 0.
"""
self.balance = balance
| [
"self.balance"
] |
ClassEval_9 | class BigNumCalculator:
"""
This is a class that implements big number calculations, including adding, subtracting and multiplying.
"""
@staticmethod
def add(num1, num2):
"""
Adds two big numbers.
:param num1: The first number to add,str.
:param num2: The second numb... | import unittest
class BigNumCalculatorTestAdd(unittest.TestCase):
def test_add(self):
bigNum = BigNumCalculator()
self.assertEqual(bigNum.add("12345678901234567890", "98765432109876543210"), "111111111011111111100")
def test_add_2(self):
bigNum = BigNumCalculator()
self.assertE... | class BigNumCalculator:
@staticmethod
def add(num1, num2):
max_length = max(len(num1), len(num2))
num1 = num1.zfill(max_length)
num2 = num2.zfill(max_length)
carry = 0
result = []
for i in range(max_length - 1, -1, -1):
digit_sum = int(num1[i]) + int(... | [] | """
This is a class that implements big number calculations, including adding, subtracting and multiplying.
"""
| [
{
"method_name": "add",
"method_description": "def add(num1, num2):\n \"\"\"\n Adds two big numbers.\n :param num1: The first number to add,str.\n :param num2: The second number to add,str.\n :return: The sum of the two numbers,str.\n >>> bigNum = BigNumCalculator()... | BigNumCalculator | [
"BigNumCalculatorTestAdd",
"BigNumCalculatorTestSubtract",
"BigNumCalculatorTestMultiply",
"BigNumCalculatorTestMain"
] | class BigNumCalculator:
| [] |
ClassEval_10 | class BinaryDataProcessor:
"""
This is a class used to process binary data, which includes functions such as clearing non 0 or 1 characters, counting binary string information, and converting to corresponding strings based on different encoding methods.
"""
def __init__(self, binary_string):
""... | import unittest
class BinaryDataProcessorTestCleanNonBinaryChars(unittest.TestCase):
def test_clean_non_binary_chars(self):
bdp = BinaryDataProcessor("01101000daf3e4r01100101011011000110110001101111")
self.assertEqual(bdp.binary_string, "0110100001100101011011000110110001101111")
def test_clea... | class BinaryDataProcessor:
def __init__(self, binary_string):
self.binary_string = binary_string
self.clean_non_binary_chars()
def clean_non_binary_chars(self):
self.binary_string = ''.join(filter(lambda x: x in '01', self.binary_string))
def calculate_binary_info(self):
ze... | [] | """
This is a class used to process binary data, which includes functions such as clearing non 0 or 1 characters, counting binary string information, and converting to corresponding strings based on different encoding methods.
"""
| [
{
"method_name": "clean_non_binary_chars",
"method_description": "def clean_non_binary_chars(self):\n \"\"\"\n Clean the binary string by removing all non 0 or 1 characters.\n >>> bdp = BinaryDataProcessor(\"01101000daf3e4r01100101011011000110110001101111\")\n >>> bdp.clean_non_b... | BinaryDataProcessor | [
"BinaryDataProcessorTestCleanNonBinaryChars",
"BinaryDataProcessorTestCalculateBinaryInfo",
"BinaryDataProcessorTestConvertToAscii",
"BinaryDataProcessorTestConvertToUtf8",
"BinaryDataProcessorTestMain"
] | class BinaryDataProcessor:
def __init__(self, binary_string):
"""
Initialize the class with a binary string and clean it by removing all non 0 or 1 characters.
"""
self.binary_string = binary_string
self.clean_non_binary_chars()
| [
"self.binary_string"
] |
ClassEval_11 | class BitStatusUtil:
"""
This is a utility class that provides methods for manipulating and checking status using bitwise operations.
"""
@staticmethod
def add(states, stat):
"""
Add a status to the current status,and check the parameters wheather they are legal.
:param stat... | import unittest
class BitStatusUtilTestAdd(unittest.TestCase):
def test_add(self):
bit_status_util = BitStatusUtil()
self.assertEqual(bit_status_util.add(2, 4), 6)
def test_add_2(self):
bit_status_util = BitStatusUtil()
self.assertEqual(bit_status_util.add(2, 0), 2)
def t... | class BitStatusUtil:
@staticmethod
def add(states, stat):
BitStatusUtil.check([states, stat])
return states | stat
@staticmethod
def has(states, stat):
BitStatusUtil.check([states, stat])
return (states & stat) == stat
@staticmethod
def remove(states, stat):
... | [] | """
This is a utility class that provides methods for manipulating and checking status using bitwise operations.
"""
| [
{
"method_name": "add",
"method_description": "def add(states, stat):\n \"\"\"\n Add a status to the current status,and check the parameters wheather they are legal.\n :param states: Current status,int.\n :param stat: Status to be added,int.\n :return: The status after add... | BitStatusUtil | [
"BitStatusUtilTestAdd",
"BitStatusUtilTestHas",
"BitStatusUtilTestRemove",
"BitStatusUtilTestCheck",
"BitStatusUtilTestMain"
] | class BitStatusUtil:
| [] |
ClassEval_12 | import random
class BlackjackGame:
"""
This is a class representing a game of blackjack, which includes creating a deck, calculating the value of a hand, and determine the winner based on the hand values of the player and dealer.
"""
def __init__(self):
"""
Initialize the Blackjack Game... | import unittest
class BlackjackGameTestCreateDeck(unittest.TestCase):
def setUp(self):
self.blackjackGame = BlackjackGame()
self.deck = self.blackjackGame.deck
def test_create_deck_1(self):
self.assertEqual(len(self.deck), 52)
def test_create_deck_2(self):
suits = ['S', 'C... | import random
class BlackjackGame:
def __init__(self):
self.deck = self.create_deck()
self.player_hand = []
self.dealer_hand = []
def create_deck(self):
deck = []
suits = ['S', 'C', 'D', 'H']
ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q',... | [
"import random"
] | """
This is a class representing a game of blackjack, which includes creating a deck, calculating the value of a hand, and determine the winner based on the hand values of the player and dealer.
"""
| [
{
"method_name": "create_deck",
"method_description": "def create_deck(self):\n \"\"\"\n Create a deck of 52 cards, which stores 52 rondom order poker with the Jokers removed.\n :return: a list of 52 rondom order poker with the Jokers removed, format is ['AS', '2S', ...].\n >>> b... | BlackjackGame | [
"BlackjackGameTestCreateDeck",
"BlackjackGameTestCalculateHandValue",
"BlackjackGameTestCheckWinner",
"BlackjackGameTestMain"
] | class BlackjackGame:
def __init__(self):
"""
Initialize the Blackjack Game with the attribute deck, player_hand and dealer_hand.
While initializing deck attribute, call the create_deck method to generate.
The deck stores 52 rondom order poker with the Jokers removed, format is ['AS'... | [
"self.dealer_hand",
"self.deck",
"self.player_hand"
] |
ClassEval_13 | class BookManagement:
"""
This is a class as managing books system, which supports to add and remove books from the inventory dict, view the inventory, and check the quantity of a specific book.
"""
def __init__(self):
"""
Initialize the inventory of Book Manager.
"""
se... | import unittest
class BookManagementTestAddBook(unittest.TestCase):
def test_add_book_1(self):
bookManagement = BookManagement()
bookManagement.add_book("book1")
self.assertEqual({"book1": 1}, bookManagement.inventory)
def test_add_book_2(self):
bookManagement = BookManagement... | class BookManagement:
def __init__(self):
self.inventory = {}
def add_book(self, title, quantity=1):
if title in self.inventory:
self.inventory[title] += quantity
else:
self.inventory[title] = quantity
def remove_book(self, title, quantity):
if title... | [] | """
This is a class as managing books system, which supports to add and remove books from the inventory dict, view the inventory, and check the quantity of a specific book.
"""
| [
{
"method_name": "add_book",
"method_description": "def add_book(self, title, quantity=1):\n \"\"\"\n Add one or several books to inventory which is sorted by book title.\n :param title: str, the book title\n :param quantity: int, default value is 1.\n \"\"\"",
"test_c... | BookManagement | [
"BookManagementTestAddBook",
"BookManagementTestRemoveBook",
"BookManagementTestViewInventory",
"BookManagementTestViewBookQuantity",
"BookManagementTestMain"
] | class BookManagement:
def __init__(self):
"""
Initialize the inventory of Book Manager.
"""
self.inventory = {}
| [
"self.inventory"
] |
ClassEval_14 | import sqlite3
class BookManagementDB:
"""
This is a database class as a book management system, used to handle the operations of adding, removing, updating, and searching books.
"""
def __init__(self, db_name):
"""
Initializes the class by creating a database connection and cursor,
... | import unittest
import os
class BookManagementDBTestCreateTable(unittest.TestCase):
def setUp(self):
self.db_name = "test.db"
self.db = BookManagementDB(self.db_name)
self.connection = sqlite3.connect(self.db_name)
self.cursor = self.connection.cursor()
def test_create_table_1... | import sqlite3
class BookManagementDB:
def __init__(self, db_name):
self.connection = sqlite3.connect(db_name)
self.cursor = self.connection.cursor()
self.create_table()
def create_table(self):
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS books (
... | [
"import sqlite3"
] | """
This is a database class as a book management system, used to handle the operations of adding, removing, updating, and searching books.
"""
| [
{
"method_name": "create_table",
"method_description": "def create_table(self):\n \"\"\"\n Creates the book table in the database if it does not already exist.\n >>> book_db = BookManagementDB(\"test.db\")\n >>> book_db.create_table()\n \"\"\"",
"test_class": "BookMana... | BookManagementDB | [
"BookManagementDBTestCreateTable",
"BookManagementDBTestAddBook",
"BookManagementDBTestRemoveBook",
"BookManagementDBTestBorrowBook",
"BookManagementDBTestReturnBook",
"BookManagementDBTestSearchBooks"
] | class BookManagementDB:
def __init__(self, db_name):
"""
Initializes the class by creating a database connection and cursor,
and creates the book table if it does not already exist
:param db_name: str, the name of db file
"""
self.connection = sqlite3.connect(db_nam... | [
"self.connection",
"self.cursor"
] |
ClassEval_15 | class BoyerMooreSearch:
"""
his is a class that implements the Boyer-Moore algorithm for string searching, which is used to find occurrences of a pattern within a given text.
"""
def __init__(self, text, pattern):
"""
Initializes the BoyerMooreSearch class with the given text and patter... | import unittest
class BoyerMooreSearchTestMatchInPattern(unittest.TestCase):
def test_match_in_pattern(self):
boyerMooreSearch = BoyerMooreSearch("ABAABA", "AB")
self.assertEqual(boyerMooreSearch.match_in_pattern("A"), 0)
def test_match_in_pattern_2(self):
boyerMooreSearch = BoyerMoore... | class BoyerMooreSearch:
def __init__(self, text, pattern):
self.text, self.pattern = text, pattern
self.textLen, self.patLen = len(text), len(pattern)
def match_in_pattern(self, char):
for i in range(self.patLen - 1, -1, -1):
if char == self.pattern[i]:
retur... | [] | """
his is a class that implements the Boyer-Moore algorithm for string searching, which is used to find occurrences of a pattern within a given text.
"""
| [
{
"method_name": "match_in_pattern",
"method_description": "def match_in_pattern(self, char):\n \"\"\"\n Finds the rightmost occurrence of a character in the pattern.\n :param char: The character to be searched for, str.\n :return: The index of the rightmost occurrence of the cha... | BoyerMooreSearch | [
"BoyerMooreSearchTestMatchInPattern",
"BoyerMooreSearchTestMismatchInText",
"BoyerMooreSearchTestBadCharacterHeuristic",
"BoyerMooreSearchTestMain"
] | class BoyerMooreSearch:
def __init__(self, text, pattern):
"""
Initializes the BoyerMooreSearch class with the given text and pattern.
:param text: The text to be searched, str.
:param pattern: The pattern to be searched for, str.
"""
self.text, self.pattern = text, ... | [
"self.patLen",
"self.pattern",
"self.text",
"self.textLen"
] |
ClassEval_16 | class Calculator:
"""
This is a class for a calculator, capable of performing basic arithmetic calculations on numerical expressions using the operators +, -, *, /, and ^ (exponentiation).
"""
def __init__(self):
"""
Initialize the operations performed by the five operators'+','-','*','... | import unittest
class CalculatorTestCalculate(unittest.TestCase):
def test_calculate_1(self):
calculator = Calculator()
res = calculator.calculate('1+2')
self.assertEqual(res, 3)
def test_calculate_2(self):
calculator = Calculator()
res = calculator.calculate('1+2*3')
... | class Calculator:
def __init__(self):
self.operators = {
'+': lambda x, y: x + y,
'-': lambda x, y: x - y,
'*': lambda x, y: x * y,
'/': lambda x, y: x / y,
'^': lambda x, y: x ** y
}
def calculate(self, expression):
operand_st... | [] | """
This is a class for a calculator, capable of performing basic arithmetic calculations on numerical expressions using the operators +, -, *, /, and ^ (exponentiation).
"""
| [
{
"method_name": "calculate",
"method_description": "def calculate(self, expression):\n \"\"\"\n Calculate the value of a given expression\n :param expression: string, given expression\n :return:If successful, returns the value of the expression; otherwise, returns None\n ... | Calculator | [
"CalculatorTestCalculate",
"CalculatorTestPrecedence",
"CalculatorTestApplyOperator",
"CalculatorTest"
] | class Calculator:
def __init__(self):
"""
Initialize the operations performed by the five operators'+','-','*','/','^'
"""
self.operators = {
'+': lambda x, y: x + y,
'-': lambda x, y: x - y,
'*': lambda x, y: x * y,
'/': lambda x, y: ... | [
"self.operators"
] |
ClassEval_17 | from datetime import datetime, timedelta
class CalendarUtil:
"""
This is a class as CalendarUtil that provides functionalities to manage calendar events, schedule appointments, and perform conflict checks.
"""
def __init__(self):
"""
Initialize the calendar with an empty list of events... | import unittest
from datetime import datetime
class CalendarTestAddEvent(unittest.TestCase):
def test_add_event(self):
calendar = CalendarUtil()
calendar.add_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),
'end_time': datetime(2023, ... | from datetime import datetime, timedelta
class CalendarUtil:
def __init__(self):
self.events = []
def add_event(self, event):
self.events.append(event)
def remove_event(self, event):
if event in self.events:
self.events.remove(event)
def get_events(self, date):
... | [
"from datetime import datetime, timedelta"
] | """
This is a class as CalendarUtil that provides functionalities to manage calendar events, schedule appointments, and perform conflict checks.
"""
| [
{
"method_name": "add_event",
"method_description": "def add_event(self, event):\n \"\"\"\n Add an event to the calendar.\n :param event: The event to be added to the calendar,dict.\n >>> calendar = CalendarUtil()\n >>> calendar.add_event({'date': datetime(2023, 1, 1, 0, 0... | CalendarUtil | [
"CalendarTestAddEvent",
"CalendarTestRemoveEvent",
"CalendarTestGetEvents",
"CalendarTestIsAvailable",
"CalendarTestGetAvailableSlots",
"CalendarTestGetUpcomingEvents",
"CalendarTestMain"
] | class CalendarUtil:
def __init__(self):
"""
Initialize the calendar with an empty list of events.
"""
self.events = []
| [
"self.events"
] |
ClassEval_18 | class CamelCaseMap:
"""
This is a custom class that allows keys to be in camel case style by converting them from underscore style, which provides dictionary-like functionality.
"""
def __init__(self):
"""
Initialize data to an empty dictionary
"""
self._data = {}
d... | import unittest
class CamelCaseMapTestGetitem(unittest.TestCase):
def test_getitem_1(self):
camelize_map = CamelCaseMap()
camelize_map['first_name'] = 'John'
self.assertEqual(camelize_map.__getitem__('first_name'), 'John')
def test_getitem_2(self):
camelize_map = CamelCaseMap(... | class CamelCaseMap:
def __init__(self):
self._data = {}
def __getitem__(self, key):
return self._data[self._convert_key(key)]
def __setitem__(self, key, value):
self._data[self._convert_key(key)] = value
def __delitem__(self, key):
del self._data[self._convert_key(key)... | [] | """
This is a custom class that allows keys to be in camel case style by converting them from underscore style, which provides dictionary-like functionality.
"""
| [
{
"method_name": "__getitem__",
"method_description": "def __getitem__(self, key):\n \"\"\"\n Return the value corresponding to the key\n :param key:str\n :return:str,the value corresponding to the key\n >>> camelize_map = CamelCaseMap()\n >>> camelize_map['first_na... | CamelCaseMap | [
"CamelCaseMapTestGetitem",
"CamelCaseMapTestSetitem",
"CamelCaseMapTestDelitem",
"CamelCaseMapTestIter",
"CamelCaseMapTestLen",
"CamelCaseMapTestConvertKey",
"CamelCaseMapTestToCamelCase",
"CamelCaseMapTest"
] | class CamelCaseMap:
def __init__(self):
"""
Initialize data to an empty dictionary
"""
self._data = {}
| [
"self._data"
] |
ClassEval_19 | class ChandrasekharSieve:
"""
This is a class that uses the Chandrasekhar's Sieve method to find all prime numbers within the range
"""
def __init__(self, n):
"""
Initialize the ChandrasekharSieve class with the given limit.
:param n: int, the upper limit for generating prime nu... | import unittest
class ChandrasekharSieveTestGeneratePrimes(unittest.TestCase):
def test_generate_primes_1(self):
cs = ChandrasekharSieve(20)
res = cs.generate_primes()
self.assertEqual(res, [2, 3, 5, 7, 11, 13, 17, 19])
def test_generate_primes_2(self):
cs = ChandrasekharSieve... | class ChandrasekharSieve:
def __init__(self, n):
self.n = n
self.primes = self.generate_primes()
def generate_primes(self):
if self.n < 2:
return []
sieve = [True] * (self.n + 1)
sieve[0] = sieve[1] = False
p = 2
while p * p <= self.n:
... | [] | """
This is a class that uses the Chandrasekhar's Sieve method to find all prime numbers within the range
"""
| [
{
"method_name": "generate_primes",
"method_description": "def generate_primes(self):\n \"\"\"\n Generate prime numbers up to the specified limit using the Chandrasekhar sieve algorithm.\n :return: list, a list of prime numbers\n >>> cs = ChandrasekharSieve(20)\n >>> cs.ge... | ChandrasekharSieve | [
"ChandrasekharSieveTestGeneratePrimes",
"ChandrasekharSieveTestGetPrimes",
"ChandrasekharSieveTest"
] | class ChandrasekharSieve:
def __init__(self, n):
"""
Initialize the ChandrasekharSieve class with the given limit.
:param n: int, the upper limit for generating prime numbers
"""
self.n = n
self.primes = self.generate_primes()
| [
"self.n",
"self.primes"
] |
ClassEval_20 | from datetime import datetime
class Chat:
"""
This is a chat class with the functions of adding users, removing users, sending messages, and obtaining messages.
"""
def __init__(self):
"""
Initialize the Chat with an attribute users, which is an empty dictionary.
"""
se... | import unittest
class ChatTestAddUser(unittest.TestCase):
def test_add_user(self):
chat = Chat()
self.assertEqual(chat.add_user('John'), True)
self.assertEqual(chat.users, {'John': []})
def test_add_user_2(self):
chat = Chat()
chat.users = {'John': []}
self.asser... | from datetime import datetime
class Chat:
def __init__(self):
self.users = {}
def add_user(self, username):
if username in self.users:
return False
else:
self.users[username] = []
return True
def remove_user(self, username):
if username ... | [
"from datetime import datetime"
] | """
This is a chat class with the functions of adding users, removing users, sending messages, and obtaining messages.
"""
| [
{
"method_name": "add_user",
"method_description": "def add_user(self, username):\n \"\"\"\n Add a new user to the Chat.\n :param username: The user's name, str.\n :return: If the user is already in the Chat, returns False, otherwise, returns True.\n >>> chat = Chat()\n ... | Chat | [
"ChatTestAddUser",
"ChatTestRemoveUser",
"ChatTestSendMessage",
"ChatTestGetMessages",
"ChatTestMain"
] | class Chat:
def __init__(self):
"""
Initialize the Chat with an attribute users, which is an empty dictionary.
"""
self.users = {}
| [
"self.users"
] |
ClassEval_21 | from datetime import datetime
class Classroom:
"""
This is a class representing a classroom, capable of adding and removing courses, checking availability at a given time, and detecting conflicts when scheduling new courses.
"""
def __init__(self, id):
"""
Initialize the classroom mana... | 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... | 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:
... | [
"from datetime import datetime"
] | """
This is a class representing a classroom, capable of adding and removing courses, checking availability at a given time, and detecting conflicts when scheduling new courses.
"""
| [
{
"method_name": "add_course",
"method_description": "def add_course(self, course):\n \"\"\"\n Add course to self.courses list if the course wasn't in it.\n :param course: dict, information of the course, including 'start_time', 'end_time' and 'name'\n >>> classroom = Classroom(1... | Classroom | [
"ClassroomTestAddCourse",
"ClassroomTestRemoveCourse",
"ClassroomTestIsFreeAt",
"ClassroomTestCheckCourseConflict",
"ClassroomTestMain"
] | class Classroom:
def __init__(self, id):
"""
Initialize the classroom management system.
:param id: int, the id of classroom
"""
self.id = id
self.courses = []
| [
"self.courses",
"self.id"
] |
ClassEval_22 | class ClassRegistrationSystem:
"""
This is a class as a class registration system, allowing to register students, register them for classes, retrieve students by major, get a list of all majors, and determine the most popular class within a specific major.
"""
def __init__(self):
"""
I... | 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... | 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... | [] | """
This is a class as a class registration system, allowing to register students, register them for classes, retrieve students by major, get a list of all majors, and determine the most popular class within a specific major.
"""
| [
{
"method_name": "register_student",
"method_description": "def register_student(self, student):\n \"\"\"\n register a student to the system, add the student to the students list, if the student is already registered, return 0, else return 1\n \"\"\"",
"test_class": "ClassRegistrati... | ClassRegistrationSystem | [
"ClassRegistrationSystemTestRegisterStudent",
"ClassRegistrationSystemTestRegisterClass",
"ClassRegistrationSystemTestGetStudent",
"ClassRegistrationSystemTestGetMajor",
"ClassRegistrationSystemTestPopularClass",
"ClassRegistrationSystemTest"
] | class ClassRegistrationSystem:
def __init__(self):
"""
Initialize the registration system with the attribute students and students_registration_class.
students is a list of student dictionaries, each student dictionary has the key of name and major.
students_registration_class is a ... | [
"self.students",
"self.students_registration_classes"
] |
ClassEval_23 | import math
from typing import List
class CombinationCalculator:
"""
This is a class that provides methods to calculate the number of combinations for a specific count, calculate all possible combinations, and generate combinations with a specified number of elements.
"""
def __init__(self, datas: Lis... | 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... | 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)... | [
"import math",
"from typing import List"
] | """
This is a class that provides methods to calculate the number of combinations for a specific count, calculate all possible combinations, and generate combinations with a specified number of elements.
"""
| [
{
"method_name": "count",
"method_description": "def count(n: int, m: int) -> int:\n \"\"\"\n Calculate the number of combinations for a specific count.\n :param n: The total number of elements,int.\n :param m: The number of elements in each combination,int.\n :return: The... | CombinationCalculator | [
"CombinationCalculatorTestCount",
"CombinationCalculatorTestCountAll",
"CombinationCalculatorTestSelect",
"CombinationCalculatorTestSelectAll",
"CombinationCalculatorTestSelect2",
"CombinationCalculatorTestMain"
] | class CombinationCalculator:
def __init__(self, datas: List[str]):
"""
Initialize the calculator with a list of data.
"""
self.datas = datas
| [
"self.datas"
] |
ClassEval_24 | class ComplexCalculator:
"""
This is a class that implements addition, subtraction, multiplication, and division operations for complex numbers.
"""
def __init__(self):
pass
@staticmethod
def add(c1, c2):
"""
Adds two complex numbers.
:param c1: The first compl... | 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... | 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
... | [] | """
This is a class that implements addition, subtraction, multiplication, and division operations for complex numbers.
"""
| [
{
"method_name": "add",
"method_description": "def add(c1, c2):\n \"\"\"\n Adds two complex numbers.\n :param c1: The first complex number,complex.\n :param c2: The second complex number,complex.\n :return: The sum of the two complex numbers,complex.\n >>> complexCa... | ComplexCalculator | [
"ComplexCalculatorTestAdd",
"ComplexCalculatorTestSubtract",
"ComplexCalculatorTestMultiply",
"ComplexCalculatorTestDivide",
"ComplexCalculatorTestMain"
] | class ComplexCalculator:
def __init__(self):
pass
| [] |
ClassEval_25 | import json
class CookiesUtil:
"""
This is a class as utility for managing and manipulating Cookies, including methods for retrieving, saving, and setting Cookies data.
"""
def __init__(self, cookies_file):
"""
Initializes the CookiesUtil with the specified cookies file.
:param... | import unittest
class CookiesUtilTestGetCookies(unittest.TestCase):
def test_get_cookies(self):
self.cookies_util = CookiesUtil('cookies.json')
self.response = {'cookies': {'key1': 'value1', 'key2': 'value2'}}
self.cookies_util.get_cookies(self.response)
self.assertEqual(self.cook... | import json
class CookiesUtil:
def __init__(self, cookies_file):
self.cookies_file = cookies_file
self.cookies = None
def get_cookies(self, reponse):
self.cookies = reponse['cookies']
self._save_cookies()
def load_cookies(self):
try:
with open(self.cook... | [
"import json"
] | """
This is a class as utility for managing and manipulating Cookies, including methods for retrieving, saving, and setting Cookies data.
"""
| [
{
"method_name": "get_cookies",
"method_description": "def get_cookies(self, reponse):\n \"\"\"\n Gets the cookies from the specified response,and save it to cookies_file.\n :param reponse: The response to get cookies from, dict.\n >>> cookies_util = CookiesUtil('cookies.json')\n... | CookiesUtil | [
"CookiesUtilTestGetCookies",
"CookiesUtilTestLoadCookies",
"CookiesUtilTestSaveCookies",
"CookiesUtilTestSetCookies",
"CookiesUtilTestMain"
] | class CookiesUtil:
def __init__(self, cookies_file):
"""
Initializes the CookiesUtil with the specified cookies file.
:param cookies_file: The cookies file to use, str.
"""
self.cookies_file = cookies_file
self.cookies = None
| [
"self.cookies",
"self.cookies_file"
] |
ClassEval_26 | import csv
class CSVProcessor:
"""
This is a class for processing CSV files, including readring and writing CSV data, as well as processing specific operations and saving as a new CSV file.
"""
def __init__(self):
pass
def read_csv(self, file_name):
"""
Read the csv file ... | import unittest
import os
class CSVProcessorTestReadCSV(unittest.TestCase):
def test_read_csv_1(self):
self.file = 'read_test.csv'
with open(self.file, 'w') as f:
f.write('a,b,c,d\nhElLo,YoU,ME,LoW')
expected_title = ['a', 'b', 'c', 'd']
expected_data = [['hElLo', 'Yo... | import csv
class CSVProcessor:
def __init__(self):
pass
def read_csv(self, file_name):
data = []
with open(file_name, 'r') as file:
reader = csv.reader(file)
title = next(reader)
for row in reader:
data.append(row)
return ti... | [
"import csv"
] | """
This is a class for processing CSV files, including readring and writing CSV data, as well as processing specific operations and saving as a new CSV file.
"""
| [
{
"method_name": "read_csv",
"method_description": "def read_csv(self, file_name):\n \"\"\"\n Read the csv file by file_name, get the title and data from it\n :param file_name: str, name of the csv file\n :return title, data: (list, list), first row is title, the rest is data\n ... | CSVProcessor | [
"CSVProcessorTestReadCSV",
"CSVProcessorTestWriteCSV",
"CSVProcessorTestProcessCSVData",
"CSVProcessorTestMain"
] | class CSVProcessor:
def __init__(self):
pass
| [] |
ClassEval_27 | class CurrencyConverter:
"""
This is a class for currency conversion, which supports to convert amounts between different currencies, retrieve supported currencies, add new currency rates, and update existing currency rates.
"""
def __init__(self):
"""
Initialize the exchange rate of th... | 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'... | 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):
... | [] | """
This is a class for currency conversion, which supports to convert amounts between different currencies, retrieve supported currencies, add new currency rates, and update existing currency rates.
"""
| [
{
"method_name": "convert",
"method_description": "def convert(self, amount, from_currency, to_currency):\n \"\"\"\n Convert the value of a given currency to another currency type\n :param amount: float, The value of a given currency\n :param from_currency: string, source currenc... | CurrencyConverter | [
"CurrencyConverterTestConvert",
"CurrencyConverterTestGetSupportedCurrencies",
"CurrencyConverterTestAddCurrencyRate",
"CurrencyConverterTestUpdateCurrencyRate",
"CurrencyConverterTest"
] | class CurrencyConverter:
def __init__(self):
"""
Initialize the exchange rate of the US dollar against various currencies
"""
self.rates = {
'USD': 1.0,
'EUR': 0.85,
'GBP': 0.72,
'JPY': 110.15,
'CAD': 1.23,
'AUD... | [
"self.rates"
] |
ClassEval_28 | import sqlite3
import pandas as pd
class DatabaseProcessor:
"""
This is a class for processing a database, supporting to create tables, insert data into the database, search for data based on name, and delete data from the database.
"""
def __init__(self, database_name):
"""
Initializ... | import unittest
import sqlite3
class DatabaseProcessorTestCreateTable(unittest.TestCase):
def setUp(self):
self.database_name = "test.db"
self.processor = DatabaseProcessor(self.database_name)
def tearDown(self):
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor(... | import sqlite3
import pandas as pd
class DatabaseProcessor:
def __init__(self, database_name):
self.database_name = database_name
def create_table(self, table_name, key1, key2):
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
create_table_query = f"CREATE T... | [
"import sqlite3",
"import pandas as pd"
] | """
This is a class for processing a database, supporting to create tables, insert data into the database, search for data based on name, and delete data from the database.
"""
| [
{
"method_name": "create_table",
"method_description": "def create_table(self, table_name, key1, key2):\n \"\"\"\n Create a new table in the database if it doesn't exist.\n And make id (INTEGER) as PRIMARY KEY, make key1 as TEXT, key2 as INTEGER\n :param table_name: str, the name... | DatabaseProcessor | [
"DatabaseProcessorTestCreateTable",
"DatabaseProcessorTestInsertIntoDatabase",
"DatabaseProcessorTestSearchDatabase",
"DatabaseProcessorTestDeteleFromDatabase",
"DatabaseProcessorTest"
] | class DatabaseProcessor:
def __init__(self, database_name):
"""
Initialize database name of database processor
"""
self.database_name = database_name
| [
"self.database_name"
] |
ClassEval_29 | from collections import Counter
class DataStatistics:
"""
This is a class for performing data statistics, supporting to calculate the mean, median, and mode of a given data set.
"""
def mean(self, data):
"""
Calculate the average value of a group of data, accurate to two digits after t... | 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... | 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 - ... | [
"from collections import Counter"
] | """
This is a class for performing data statistics, supporting to calculate the mean, median, and mode of a given data set.
"""
| [
{
"method_name": "mean",
"method_description": "def mean(self, data):\n \"\"\"\n Calculate the average value of a group of data, accurate to two digits after the Decimal separator\n :param data:list, data list\n :return:float, the mean value\n >>> ds = DataStatistics()\n ... | DataStatistics | [
"DataStatisticsTestMean",
"DataStatisticsTestMedian",
"DataStatisticsTestMode",
"DataStatisticsTest"
] | class DataStatistics:
| [] |
ClassEval_30 | import numpy as np
class DataStatistics2:
"""
This is a class for performing data statistics, supporting to get the sum, minimum, maximum, variance, standard deviation, and correlation of a given dataset.
"""
def __init__(self, data):
"""
Initialize Data List
:param data:list
... | 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... | 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... | [
"import numpy as np"
] | """
This is a class for performing data statistics, supporting to get the sum, minimum, maximum, variance, standard deviation, and correlation of a given dataset.
"""
| [
{
"method_name": "get_sum",
"method_description": "def get_sum(self):\n \"\"\"\n Calculate the sum of data\n :return:float\n >>> ds2 = DataStatistics2([1, 2, 3, 4])\n >>> ds2.get_sum()\n 10\n \"\"\"",
"test_class": "DataStatistics2TestGetSum",
"test_c... | DataStatistics2 | [
"DataStatistics2TestGetSum",
"DataStatistics2TestGetMin",
"DataStatistics2TestGetMax",
"DataStatistics2TestGetVariance",
"DataStatistics2TestGetStdDeviation",
"DataStatistics2TestGetCorrelation",
"DataStatistics2Test"
] | class DataStatistics2:
def __init__(self, data):
"""
Initialize Data List
:param data:list
"""
self.data = np.array(data)
| [
"self.data"
] |
ClassEval_31 | import math
class DataStatistics4:
"""
This is a class that performs advanced mathematical calculations and statistics, including correlation coefficient, skewness, kurtosis, and probability density function (PDF) for a normal distribution.
"""
@staticmethod
def correlation_coefficient(data1, dat... | 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... | 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... | [
"import math"
] | """
This is a class that performs advanced mathematical calculations and statistics, including correlation coefficient, skewness, kurtosis, and probability density function (PDF) for a normal distribution.
"""
| [
{
"method_name": "correlation_coefficient",
"method_description": "def correlation_coefficient(data1, data2):\n \"\"\"\n Calculate the correlation coefficient of two sets of data.\n :param data1: The first set of data,list.\n :param data2: The second set of data,list.\n :r... | DataStatistics4 | [
"DataStatistics4TestCorrelationCoefficient",
"DataStatistics4TestSkewness",
"DataStatistics4TestKurtosis",
"DataStatistics4TestPDF",
"DataStatistics4TestMain"
] | class DataStatistics4:
| [] |
ClassEval_32 | class DecryptionUtils:
"""
This is a class that provides methods for decryption, including the Caesar cipher, Vigenere cipher, and Rail Fence cipher.
"""
def __init__(self, key):
"""
Initializes the decryption utility with a key.
:param key: The key to use for decryption,str.
... | 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... | 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:
... | [] | """
This is a class that provides methods for decryption, including the Caesar cipher, Vigenere cipher, and Rail Fence cipher.
"""
| [
{
"method_name": "caesar_decipher",
"method_description": "def caesar_decipher(self, ciphertext, shift):\n \"\"\"\n Deciphers the given ciphertext using the Caesar cipher\n :param ciphertext: The ciphertext to decipher,str.\n :param shift: The shift to use for decryption,int.\n ... | DecryptionUtils | [
"DecryptionUtilsTestCaesarDecipher",
"DecryptionUtilsTestVigenereDecipher",
"DecryptionUtilsTestRailFenceDecipher",
"DecryptionUtilsTestMain"
] | class DecryptionUtils:
def __init__(self, key):
"""
Initializes the decryption utility with a key.
:param key: The key to use for decryption,str.
"""
self.key = key
| [
"self.key"
] |
ClassEval_33 | class DiscountStrategy:
"""
This is a class that allows to use different discount strategy based on shopping credit or shopping cart in supermarket.
"""
def __init__(self, customer, cart, promotion=None):
"""
Initialize the DiscountStrategy with customer information, a cart of items, an... | 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... | 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)
... | [] | """
This is a class that allows to use different discount strategy based on shopping credit or shopping cart in supermarket.
"""
| [
{
"method_name": "total",
"method_description": "def total(self):\n \"\"\"\n Calculate the total cost of items in the cart.\n :return: float, total cost of items\n >>> customer = {'name': 'John Doe', 'fidelity': 1200}\n >>> cart = [{'product': 'product', 'quantity': 14, 'p... | DiscountStrategy | [
"DiscountStrategyTestTotal",
"DiscountStrategyTestDue",
"DiscountStrategyTestFidelityPromo",
"DiscountStrategyTestBulkItemPromo",
"DiscountStrategyTestLargeOrderPromo",
"DiscountStrategyTest"
] | class DiscountStrategy:
def __init__(self, customer, cart, promotion=None):
"""
Initialize the DiscountStrategy with customer information, a cart of items, and an optional promotion.
:param customer: dict, customer information
:param cart: list of dicts, a cart of items with details... | [
"self.cart",
"self.customer",
"self.promotion"
] |
ClassEval_34 | from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
class DocFileHandler:
"""
This is a class that handles Word documents and provides functionalities for reading, writing, and modifying the content of Word documents.
"""
def __init__(self, file_path... | import unittest
import os
class DocFileHandlerTestReadText(unittest.TestCase):
def test_read_text_1(self):
self.file_path = "test_example.docx"
self.handler = DocFileHandler(self.file_path)
doc = Document()
doc.add_paragraph("Initial content")
doc.save(self.file_path)
... | from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
class DocFileHandler:
def __init__(self, file_path):
self.file_path = file_path
def read_text(self):
doc = Document(self.file_path)
text = []
for paragraph in doc.paragraphs:... | [
"from docx import Document",
"from docx.shared import Pt",
"from docx.enum.text import WD_PARAGRAPH_ALIGNMENT"
] | """
This is a class that handles Word documents and provides functionalities for reading, writing, and modifying the content of Word documents.
"""
| [
{
"method_name": "read_text",
"method_description": "def read_text(self):\n \"\"\"\n Reads the content of a Word document and returns it as a string.\n :return: str, the content of the Word document.\n \"\"\"",
"test_class": "DocFileHandlerTestReadText",
"test_code": "cla... | DocFileHandler | [
"DocFileHandlerTestReadText",
"DocFileHandlerTestWriteText",
"DocFileHandlerTestAddHeading",
"DocFileHandlerTestAddTable",
"DocFileHandlerTest"
] | class DocFileHandler:
def __init__(self, file_path):
"""
Initializes the DocFileHandler object with the specified file path.
:param file_path: str, the path to the Word document file.
"""
self.file_path = file_path
| [
"self.file_path"
] |
ClassEval_35 | class EightPuzzle:
"""
This class is an implementation of the classic 8-puzzle game, including methods for finding the blank tile, making moves, getting possible moves, and solving the puzzle using a breadth-first search algorithm.
"""
def __init__(self, initial_state):
"""
Initializing... | 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... | 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, ... | [] | """
This class is an implementation of the classic 8-puzzle game, including methods for finding the blank tile, making moves, getting possible moves, and solving the puzzle using a breadth-first search algorithm.
"""
| [
{
"method_name": "find_blank",
"method_description": "def find_blank(self, state):\n \"\"\"\n Find the blank position of current state, which is the 0 element.\n :param state: a 3*3 size list of Integer, stores the current state.\n :return i, j: two Integers, represent the coordi... | EightPuzzle | [
"EightPuzzleTestFindBlank",
"EightPuzzleTestMove",
"EightPuzzleTestGetPossibleMoves",
"EightPuzzleTestSolve"
] | class EightPuzzle:
def __init__(self, initial_state):
"""
Initializing the initial state of Eight Puzzle Game, stores in attribute self.initial_state.
And set the goal state of this game, stores in self.goal_state. In this case, set the size as 3*3
:param initial_state: a 3*3 size l... | [
"self.goal_state",
"self.initial_state"
] |
ClassEval_36 | from datetime import datetime
class EmailClient:
"""
This is a class that serves as an email client, implementing functions such as checking emails, determining whether there is sufficient space, and cleaning up space
"""
def __init__(self, addr, capacity) -> None:
"""
Initializes the ... | import unittest
class EmailClientTestSendTo(unittest.TestCase):
def test_send_to(self):
sender = EmailClient('sender@example.com', 100)
receiver = EmailClient('receiver@example.com', 50)
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
self.assertTrue(sender.send_to(receiver... | from datetime import datetime
class EmailClient:
def __init__(self, addr, capacity) -> None:
self.addr = addr
self.capacity = capacity
self.inbox = []
def send_to(self, recv, content, size):
if not recv.is_full_with_one_more_email(size):
timestamp = datetime.now... | [
"from datetime import datetime"
] | """
This is a class that serves as an email client, implementing functions such as checking emails, determining whether there is sufficient space, and cleaning up space
"""
| [
{
"method_name": "send_to",
"method_description": "def send_to(self, recv, content, size):\n \"\"\"\n Sends an email to the given email address.\n :param recv: The email address of the receiver, str.\n :param content: The content of the email, str.\n :param size: The size ... | EmailClient | [
"EmailClientTestSendTo",
"EmailClientTestFetch",
"EmailClientTestIsFullWithOneMoreEmail",
"EmailClientTestGetOccupiedSize",
"EmailClientTestClearInbox",
"EmailClientTestMain"
] | class EmailClient:
def __init__(self, addr, capacity) -> None:
"""
Initializes the EmailClient class with the email address and the capacity of the email box.
:param addr: The email address, str.
:param capacity: The capacity of the email box, float.
"""
self.addr = ... | [
"self.addr",
"self.capacity",
"self.inbox"
] |
ClassEval_37 | class EncryptionUtils:
"""
This is a class that provides methods for encryption, including the Caesar cipher, Vigenere cipher, and Rail Fence cipher.
"""
def __init__(self, key):
"""
Initializes the class with a key.
:param key: The key to use for encryption, str.
"""
... | 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")... | 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:
... | [] | """
This is a class that provides methods for encryption, including the Caesar cipher, Vigenere cipher, and Rail Fence cipher.
"""
| [
{
"method_name": "caesar_cipher",
"method_description": "def caesar_cipher(self, plaintext, shift):\n \"\"\"\n Encrypts the plaintext using the Caesar cipher.\n :param plaintext: The plaintext to encrypt, str.\n :param shift: The number of characters to shift each character in th... | EncryptionUtils | [
"EncryptionUtilsTestCaesarCipher",
"EncryptionUtilsTestVigenereCipher",
"EncryptionUtilsTestRailFenceCipher",
"EncryptionUtilsTestMain"
] | class EncryptionUtils:
def __init__(self, key):
"""
Initializes the class with a key.
:param key: The key to use for encryption, str.
"""
self.key = key
| [
"self.key"
] |
ClassEval_38 | import openpyxl
class ExcelProcessor:
"""
This is a class for processing excel files, including readring and writing excel data, as well as processing specific operations and saving as a new excel file.
"""
def __init__(self):
pass
def read_excel(self, file_name):
"""
Rea... | import unittest
import os
class ExcelProcessorTestReadExcel(unittest.TestCase):
def test_read_excel_1(self):
self.test_file_name = 'test_data.xlsx'
data = [['Name', 'Age', 'Country'],
['John', 25, 'USA'],
['Alice', 30, 'Canada'],
['Bob', 35, 'Austral... | import openpyxl
class ExcelProcessor:
def __init__(self):
pass
def read_excel(self, file_name):
data = []
try:
workbook = openpyxl.load_workbook(file_name)
sheet = workbook.active
for row in sheet.iter_rows(values_only=True):
data.ap... | [
"import openpyxl"
] | """
This is a class for processing excel files, including readring and writing excel data, as well as processing specific operations and saving as a new excel file.
"""
| [
{
"method_name": "read_excel",
"method_description": "def read_excel(self, file_name):\n \"\"\"\n Reading data from Excel files\n :param file_name:str, Excel file name to read\n :return:list of data, Data in Excel\n \"\"\"",
"test_class": "ExcelProcessorTestReadExcel",... | ExcelProcessor | [
"ExcelProcessorTestReadExcel",
"ExcelProcessorTestWriteExcel",
"ExcelProcessorTestProcessExcelData",
"ExcelProcessorTest"
] | class ExcelProcessor:
def __init__(self):
pass
| [] |
ClassEval_39 | class ExpressionCalculator:
"""
This is a class in Python that can perform calculations with basic arithmetic operations, including addition, subtraction, multiplication, division, and modulo.
"""
def __init__(self):
"""
Initialize the expression calculator
"""
self.post... | 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... | 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... | [
"import re",
"from collections import deque",
"from decimal import Decimal"
] | """
This is a class in Python that can perform calculations with basic arithmetic operations, including addition, subtraction, multiplication, division, and modulo.
"""
| [
{
"method_name": "calculate",
"method_description": "def calculate(self, expression):\n \"\"\"\n Calculate the result of the given postfix expression\n :param expression: string, the postfix expression to be calculated\n :return: float, the calculated result\n >>> expressi... | ExpressionCalculator | [
"ExpressionCalculatorTestCalculate",
"ExpressionCalculatorTestPrepare",
"ExpressionCalculatorTestIsOperator",
"ExpressionCalculatorTestCompare",
"ExpressionCalculatorTestCalculateMethod",
"ExpressionCalculatorTestTransform",
"ExpressionCalculatorTest"
] | class ExpressionCalculator:
def __init__(self):
"""
Initialize the expression calculator
"""
self.postfix_stack = deque()
self.operat_priority = [0, 3, 2, 1, -1, 1, 0, 2]
| [
"self.operat_priority",
"self.postfix_stack"
] |
ClassEval_40 | class FitnessTracker:
"""
This is a class as fitness tracker that implements to calculate BMI (Body Mass Index) and calorie intake based on the user's height, weight, age, and sex.
"""
def __init__(self, height, weight, age, sex) -> None:
"""
Initialize the class with height, weight, ag... | 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")... | 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... | [] | """
This is a class as fitness tracker that implements to calculate BMI (Body Mass Index) and calorie intake based on the user's height, weight, age, and sex.
"""
| [
{
"method_name": "get_BMI",
"method_description": "def get_BMI(self):\n \"\"\"\n Calculate the BMI based on the height and weight.\n :return: BMI,which is the weight divide by the square of height, float.\n >>> fitnessTracker = FitnessTracker(1.8, 70, 20, \"male\")\n >>> f... | FitnessTracker | [
"FitnessTrackerTestGetBMI",
"FitnessTrackerTestConditionJudge",
"FitnessTrackerTestCaculateCalorieIntake",
"FitnessTrackerTestMain"
] | class FitnessTracker:
def __init__(self, height, weight, age, sex) -> None:
"""
Initialize the class with height, weight, age, and sex, and calculate the BMI standard based on sex, and male is 20-25, female is 19-24.
"""
self.height = height
self.weight = weight
self... | [
"self.BMI_std",
"self.age",
"self.height",
"self.sex",
"self.weight"
] |
ClassEval_41 | class GomokuGame:
"""
This class is an implementation of a Gomoku game, supporting for making moves, checking for a winner, and checking if there are five consecutive symbols on the game board.
"""
def __init__(self, board_size):
"""
Initializes the game with a given board size.
... | 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... | 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... | [] | """
This class is an implementation of a Gomoku game, supporting for making moves, checking for a winner, and checking if there are five consecutive symbols on the game board.
"""
| [
{
"method_name": "make_move",
"method_description": "def make_move(self, row, col):\n \"\"\"\n Makes a move at the given row and column.\n If the move is valid, it places the current player's symbol on the board\n and changes the current player to the other player (if the current... | GomokuGame | [
"GomokuGameTestMakeMove",
"GomokuGameTestCheckWinner",
"GomokuGameTestCheckFiveInARow",
"GomokuGameTestMain"
] | class GomokuGame:
def __init__(self, board_size):
"""
Initializes the game with a given board size.
It initializes the board with empty spaces and sets the current player symble as 'X'.
"""
self.board_size = board_size
self.board = [[' ' for _ in range(board_size)] f... | [
"self.board",
"self.board_size",
"self.current_player"
] |
ClassEval_42 | class Hotel:
"""
This is a class as hotel management system, managing the booking, check-in, check-out, and availability of rooms in a hotel with different room types.
"""
def __init__(self, name, rooms):
"""
Initialize the three fields in Hotel System.
name is the hotel name.
... | 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... | 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... | [] | """
This is a class as hotel management system, managing the booking, check-in, check-out, and availability of rooms in a hotel with different room types.
"""
| [
{
"method_name": "book_room",
"method_description": "def book_room(self, room_type, room_number, name):\n \"\"\"\n Check if there are any rooms of the specified type available.\n if rooms are adequate, modify available_rooms and booked_rooms and finish booking, or fail to book otherwise... | Hotel | [
"HotelTestBookRoom",
"HotelTestCheckIn",
"HotelTestCheckOut",
"HotelTestAvailableRooms",
"HotelTestMain"
] | class Hotel:
def __init__(self, name, rooms):
"""
Initialize the three fields in Hotel System.
name is the hotel name.
available_rooms stores the remaining rooms in the hotel
booked_rooms stores the rooms that have been booked and the person's name who booked rooms.
... | [
"self.available_rooms",
"self.booked_rooms",
"self.name"
] |
ClassEval_43 | class HRManagementSystem:
"""
This is a class as personnel management system that implements functions such as adding, deleting, querying, and updating employees
"""
def __init__(self):
"""
Initialize the HRManagementSystem withan attribute employees, which is an empty dictionary.
... | 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... | 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,
... | [] | """
This is a class as personnel management system that implements functions such as adding, deleting, querying, and updating employees
"""
| [
{
"method_name": "add_employee",
"method_description": "def add_employee(self, employee_id, name, position, department, salary):\n \"\"\"\n Add a new employee to the HRManagementSystem.\n :param employee_id: The employee's id, int.\n :param name: The employee's name, str.\n ... | HRManagementSystem | [
"HRManagementSystemTestAddEmployee",
"HRManagementSystemTestRemoveEmployee",
"HRManagementSystemTestUpdateEmployee",
"HRManagementSystemTestGetEmployee",
"HRManagementSystemTestListEmployees",
"HRManagementSystemTestMain"
] | class HRManagementSystem:
def __init__(self):
"""
Initialize the HRManagementSystem withan attribute employees, which is an empty dictionary.
"""
self.employees = {}
| [
"self.employees"
] |
ClassEval_44 | import re
import string
import gensim
from bs4 import BeautifulSoup
class HtmlUtil:
"""
This is a class as util for html, supporting for formatting and extracting code from HTML text, including cleaning up the text and converting certain elements into specific marks.
"""
def __init__(self):
""... | 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'... | 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.... | [
"import re",
"import string",
"import gensim",
"from bs4 import BeautifulSoup"
] | """
This is a class as util for html, supporting for formatting and extracting code from HTML text, including cleaning up the text and converting certain elements into specific marks.
"""
| [
{
"method_name": "__format_line_feed",
"method_description": "def __format_line_feed(text):\n \"\"\"\n Replace consecutive line breaks with a single line break\n :param text: string with consecutive line breaks\n :return:string, replaced text with single line break\n \"\"\... | HtmlUtil | [
"HtmlUtilTestFormatLineFeed",
"HtmlUtilTestFormatLineHtmlText",
"HtmlUtilTestExtractCodeFromHtmlText",
"HtmlUtilTest"
] | class HtmlUtil:
def __init__(self):
"""
Initialize a series of labels
"""
self.SPACE_MARK = '-SPACE-'
self.JSON_MARK = '-JSON-'
self.MARKUP_LANGUAGE_MARK = '-MARKUP_LANGUAGE-'
self.URL_MARK = '-URL-'
self.NUMBER_MARK = '-NUMBER-'
self.TRACE_MA... | [
"self.CODE_MARK",
"self.COMMAND_MARK",
"self.COMMENT_MARK",
"self.JSON_MARK",
"self.MARKUP_LANGUAGE_MARK",
"self.NUMBER_MARK",
"self.SPACE_MARK",
"self.TRACE_MARK",
"self.URL_MARK"
] |
ClassEval_45 | from PIL import Image, ImageEnhance
class ImageProcessor:
"""
This is a class to process image, including loading, saving, resizing, rotating, and adjusting the brightness of images.
"""
def __init__(self):
"""
Initialize self.image
"""
self.image = None
def load_i... | import unittest
import os
class ImageProcessorTestLoadImage(unittest.TestCase):
def setUp(self):
self.processor = ImageProcessor()
self.image_path = os.path.join(os.path.dirname(__file__), "test.png")
image = Image.new("RGB", (100, 100), (255, 255, 255))
image.save(self.image_path)... | from PIL import Image, ImageEnhance, ImageChops
class ImageProcessor:
def __init__(self):
self.image = None
def load_image(self, image_path):
self.image = Image.open(image_path)
def save_image(self, save_path):
if self.image:
self.image.save(save_path)
def resize... | [
"from PIL import Image, ImageEnhance, ImageChops"
] | """
This is a class to process image, including loading, saving, resizing, rotating, and adjusting the brightness of images.
"""
| [
{
"method_name": "load_image",
"method_description": "def load_image(self, image_path):\n \"\"\"\n Use Image util in PIL to open a image\n :param image_path: str, path of image that is to be\n >>> processor.load_image('test.jpg')\n >>> processor.image\n <PIL.JpegIma... | ImageProcessor | [
"ImageProcessorTestLoadImage",
"ImageProcessorTestSaveImage",
"ImageProcessorTestResizeImage",
"ImageProcessorTestRotateImage",
"ImageProcessorTestAdjustBrightness",
"ImageProcessorTestMain"
] | class ImageProcessor:
def __init__(self):
"""
Initialize self.image
"""
self.image = None
| [
"self.image"
] |
ClassEval_46 | class Interpolation:
"""
This is a class that implements the Linear interpolation operation of one-dimensional and two-dimensional data
"""
def __init__(self):
pass
@staticmethod
def interpolate_1d(x, y, x_interp):
"""
Linear interpolation of one-dimensional data
... | 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... | 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] ... | [] | """
This is a class that implements the Linear interpolation operation of one-dimensional and two-dimensional data
"""
| [
{
"method_name": "interpolate_1d",
"method_description": "def interpolate_1d(x, y, x_interp):\n \"\"\"\n Linear interpolation of one-dimensional data\n :param x: The x-coordinate of the data point, list.\n :param y: The y-coordinate of the data point, list.\n :param x_inte... | Interpolation | [
"InterpolationTestInterpolate1d",
"InterpolationTestInterpolate2d",
"InterpolationTestMain"
] | class Interpolation:
def __init__(self):
pass
| [] |
ClassEval_47 | class IPAddress:
"""
This is a class to process IP Address, including validating, getting the octets and obtaining the binary representation of a valid IP address.
"""
def __init__(self, ip_address):
"""
Initialize the IP address to the specified address
:param ip_address:string... | 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... | 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:
... | [] | """
This is a class to process IP Address, including validating, getting the octets and obtaining the binary representation of a valid IP address.
"""
| [
{
"method_name": "is_valid",
"method_description": "def is_valid(self):\n \"\"\"\n Judge whether the IP address is valid, that is, whether the IP address is composed of four Decimal digits separated by '.'. Each digit is greater than or equal to 0 and less than or equal to 255\n :return... | IPAddress | [
"IPAddressTestIsValid",
"IPAddressTestGetOctets",
"IPAddressTestGetBinary",
"IPAddressTest"
] | class IPAddress:
def __init__(self, ip_address):
"""
Initialize the IP address to the specified address
:param ip_address:string
"""
self.ip_address = ip_address
| [
"self.ip_address"
] |
ClassEval_48 | import socket
import netifaces
class IpUtil:
"""
This is a class as tool for ip that can be used to obtain the local IP address, validate its validity, and also provides the functionality to retrieve the corresponding hostname.
"""
@staticmethod
def is_valid_ipv4(ip_address):
"""
... | 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... | 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... | [
"import socket"
] | """
This is a class as tool for ip that can be used to obtain the local IP address, validate its validity, and also provides the functionality to retrieve the corresponding hostname.
"""
| [
{
"method_name": "is_valid_ipv4",
"method_description": "def is_valid_ipv4(ip_address):\n \"\"\"\n Check if the given IP address is a valid IPv4 address.\n :param ip_address: string, the IP address to check\n :return: bool, True if the IP address is valid, False otherwise\n ... | IpUtil | [
"IpUtilTestIsValidIpv4",
"IpUtilTestIsValidIpv6",
"IpUtilTestGetHostname",
"IpUtilTest"
] | class IpUtil:
| [] |
ClassEval_49 | class JobMarketplace:
"""
This is a class that provides functionalities to publish positions, remove positions, submit resumes, withdraw resumes, search for positions, and obtain candidate information.
"""
def __init__(self):
self.job_listings = []
self.resumes = []
def post_job(se... | 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 ... | 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... | [] | """
This is a class that provides functionalities to publish positions, remove positions, submit resumes, withdraw resumes, search for positions, and obtain candidate information.
"""
| [
{
"method_name": "post_job",
"method_description": "def post_job(self, job_title, company, requirements):\n \"\"\"\n This function is used to publish positions,and add the position information to the job_listings list.\n :param job_title: The title of the position,str.\n :param c... | JobMarketplace | [
"JobMarketplaceTestPostJob",
"JobMarketplaceTestRemoveJob",
"JobMarketplaceTestSubmitResume",
"JobMarketplaceTestWithdrawResume",
"JobMarketplaceTestSearchJobs",
"JobMarketplaceTestGetJobApplicants",
"JobMarketplaceTestMatchesRequirements",
"JobMarketplaceTestMain"
] | class JobMarketplace:
def __init__(self):
self.job_listings = []
self.resumes = []
| [
"self.job_listings",
"self.resumes"
] |
ClassEval_50 | import json
import os
class JSONProcessor:
"""
This is a class to process JSON file, including reading and writing JSON files, as well as processing JSON data by removing a specified key from the JSON object.
"""
def read_json(self, file_path):
"""
Read a JSON file and return the data.... | import os
import stat
import json
import unittest
class JSONProcessorTestReadJson(unittest.TestCase):
def setUp(self):
self.processor = JSONProcessor()
self.test_data = {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
self.file_path = "te... | import json
import os
class JSONProcessor:
def read_json(self, file_path):
if not os.path.exists(file_path):
return 0
try:
with open(file_path, 'r') as file:
data = json.load(file)
return data
except:
return -1
def write_... | [
"import json",
"import os"
] | """
This is a class to process JSON file, including reading and writing JSON files, as well as processing JSON data by removing a specified key from the JSON object.
"""
| [
{
"method_name": "read_json",
"method_description": "def read_json(self, file_path):\n \"\"\"\n Read a JSON file and return the data.\n :param file_path: str, the path of the JSON file.\n :return: dict, the data from the JSON file if read successfully, or return -1 if an error oc... | JSONProcessor | [
"JSONProcessorTestReadJson",
"JSONProcessorTestWriteJson",
"JSONProcessorTestProcessJsonExistingKey",
"JSONProcessorTestMain"
] | class JSONProcessor:
| [] |
ClassEval_51 | import numpy as np
class KappaCalculator:
"""
This is a class as KappaCalculator, supporting to calculate Cohen's and Fleiss' kappa coefficient.
"""
@staticmethod
def kappa(testData, k):
"""
Calculate the cohens kappa value of a k-dimensional matrix
:param testData: The k-... | import unittest
class KappaCalculatorTestKappa(unittest.TestCase):
def test_kappa_1(self):
self.assertEqual(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.19469026... | 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)
... | [
"import numpy as np"
] | """
This is a class as KappaCalculator, supporting to calculate Cohen's and Fleiss' kappa coefficient.
"""
| [
{
"method_name": "kappa",
"method_description": "def kappa(testData, k):\n \"\"\"\n Calculate the cohens kappa value of a k-dimensional matrix\n :param testData: The k-dimensional matrix that needs to calculate the cohens kappa value\n :param k: int, Matrix dimension\n :re... | KappaCalculator | [
"KappaCalculatorTestKappa",
"KappaCalculatorTestFleissKappa",
"KappaCalculatorTest"
] | class KappaCalculator:
| [] |
ClassEval_52 | import nltk
from nltk.stem import WordNetLemmatizer
from nltk import pos_tag, word_tokenize
import string
nltk.download('averaged_perceptron_tagger')
nltk.download('punkt')
nltk.download('wordnet')
class Lemmatization:
"""
This is a class about Lemmatization, which utilizes the nltk library to perform lemmat... | import unittest
class LemmatizationTestLemmatizeSentence(unittest.TestCase):
def test_lemmatize_sentence_1(self):
lemmatization = Lemmatization()
result = lemmatization.lemmatize_sentence("I am running in a race.")
expected = ['I', 'be', 'run', 'in', 'a', 'race']
self.assertEqual(re... | import nltk
from nltk.stem import WordNetLemmatizer
from nltk import pos_tag, word_tokenize
import string
nltk.download('averaged_perceptron_tagger')
nltk.download('punkt')
nltk.download('wordnet')
class Lemmatization:
def __init__(self):
self.lemmatizer = WordNetLemmatizer()
def lemmatize_sentence(... | [
"import nltk",
"from nltk.stem import WordNetLemmatizer",
"from nltk import pos_tag, word_tokenize",
"import string"
] | """
This is a class about Lemmatization, which utilizes the nltk library to perform lemmatization and part-of-speech tagging on sentences, as well as remove punctuation.
"""
| [
{
"method_name": "lemmatize_sentence",
"method_description": "def lemmatize_sentence(self, sentence):\n \"\"\"\n Remove punctuations of the sentence and tokenizes the input sentence, mark the part of speech tag of each word,\n lemmatizes the words with different parameters based on thei... | Lemmatization | [
"LemmatizationTestLemmatizeSentence",
"LemmatizationTestGetPosTag",
"LemmatizationTestRemovePunctuation",
"LemmatizationTestMain"
] | class Lemmatization:
def __init__(self):
"""
creates a WordNetLemmatizer object and stores it in the self.lemmatizer member variable.
"""
self.lemmatizer = WordNetLemmatizer()
| [
"self.lemmatizer"
] |
ClassEval_53 | import re
import string
class LongestWord:
"""
This is a class allows to add words to a list and find the longest word in a given sentence by comparing the words with the ones in the word list.
"""
def __init__(self):
"""
Initialize a list of word.
"""
self.word_list = ... | 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... | 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... | [
"import re",
"import string"
] | """
This is a class allows to add words to a list and find the longest word in a given sentence by comparing the words with the ones in the word list.
"""
| [
{
"method_name": "add_word",
"method_description": "def add_word(self, word):\n \"\"\"\n append the input word into self.word_list\n :param word: str, input word\n \"\"\"",
"test_class": "LongestWordTestAddWord",
"test_code": "class LongestWordTestAddWord(unittest.TestCas... | LongestWord | [
"LongestWordTestAddWord",
"LongestWordTestFindLongestWord"
] | class LongestWord:
def __init__(self):
"""
Initialize a list of word.
"""
self.word_list = []
| [
"self.word_list"
] |
ClassEval_54 | import random
class MahjongConnect:
"""
MahjongConnect is a class representing a game board for Mahjong Connect with features like creating the board, checking valid moves, finding paths, removing icons, and checking if the game is over.
"""
def __init__(self, BOARD_SIZE, ICONS):
"""
i... | import unittest
class MahjongConnectTestCreateBoard(unittest.TestCase):
def test_create_board_1(self):
mc = MahjongConnect([4, 4], ['a', 'b', 'c'])
self.assertEqual(mc.BOARD_SIZE, [4, 4])
self.assertEqual(mc.ICONS, ['a', 'b', 'c'])
for row in mc.board:
for icon in row:
... | import random
class MahjongConnect:
def __init__(self, BOARD_SIZE, ICONS):
self.BOARD_SIZE = BOARD_SIZE
self.ICONS = ICONS
self.board = self.create_board()
def create_board(self):
board = [[random.choice(self.ICONS) for _ in range(self.BOARD_SIZE[1])] for _ in range(self.BOARD... | [
"import random"
] | """
MahjongConnect is a class representing a game board for Mahjong Connect with features like creating the board, checking valid moves, finding paths, removing icons, and checking if the game is over.
"""
| [
{
"method_name": "create_board",
"method_description": "def create_board(self):\n \"\"\"\n create the game board with the given board size and icons\n :return: 2-dimensional list, the game board\n >>> mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n >>> mc.create_board()\n ... | MahjongConnect | [
"MahjongConnectTestCreateBoard",
"MahjongConnectTestIsValidMove",
"MahjongConnectTestHasPath",
"MahjongConnectTestRemoveIcons",
"MahjongConnectTestIsGameOver",
"MahjongConnectTest"
] | class MahjongConnect:
def __init__(self, BOARD_SIZE, ICONS):
"""
initialize the board size and the icon list, create the game board
:param BOARD_SIZE: list of two integer numbers, representing the number of rows and columns of the game board
:param ICONS: list of string, representin... | [
"self.BOARD_SIZE",
"self.ICONS",
"self.board"
] |
ClassEval_55 | class Manacher:
"""
his is a class that implements a manacher algorithm to find the Longest palindromic substring in a given string.
"""
def __init__(self, input_string) -> None:
"""
Initializes the Manacher class with the given input_string.
:param input_string: The input_strin... | 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... | 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
... | [] | """
his is a class that implements a manacher algorithm to find the Longest palindromic substring in a given string.
"""
| [
{
"method_name": "palindromic_length",
"method_description": "def palindromic_length(self, center, diff, string):\n \"\"\"\n Recursively calculates the length of the palindromic substring based on a given center, difference value, and input string.\n :param center: The center of the pal... | Manacher | [
"ManacherTestPalindromicLength",
"ManacherTestPalindromicString",
"ManacherTestMain"
] | class Manacher:
def __init__(self, input_string) -> None:
"""
Initializes the Manacher class with the given input_string.
:param input_string: The input_string to be searched, str.
"""
self.input_string = input_string
| [
"self.input_string"
] |
ClassEval_56 | class MetricsCalculator:
"""
The class calculates precision, recall, F1 score, and accuracy based on predicted and true labels.
"""
def __init__(self):
"""
Initialize the number of all four samples to 0
"""
self.true_positives = 0
self.false_positives = 0
... | 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... | 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... | [] | """
The class calculates precision, recall, F1 score, and accuracy based on predicted and true labels.
"""
| [
{
"method_name": "update",
"method_description": "def update(self, predicted_labels, true_labels):\n \"\"\"\n Update the number of all four samples(true_positives, false_positives, false_negatives, true_negatives)\n :param predicted_labels: list, predicted results\n :param true_l... | MetricsCalculator | [
"MetricsCalculatorTestUpdate",
"MetricsCalculatorTestPrecision",
"MetricsCalculatorTestRecall",
"MetricsCalculatorTestF1Score",
"MetricsCalculatorTestAccuracy",
"MetricsCalculatorTest"
] | class MetricsCalculator:
def __init__(self):
"""
Initialize the number of all four samples to 0
"""
self.true_positives = 0
self.false_positives = 0
self.false_negatives = 0
self.true_negatives = 0
| [
"self.false_negatives",
"self.false_positives",
"self.true_negatives",
"self.true_positives"
] |
ClassEval_57 | import numpy as np
class MetricsCalculator2:
"""
The class provides to calculate Mean Reciprocal Rank (MRR) and Mean Average Precision (MAP) based on input data, where MRR measures the ranking quality and MAP measures the average precision.
"""
def __init__(self):
pass
@staticmethod
... | 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... | 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:
... | [
"import numpy as np"
] | """
The class provides to calculate Mean Reciprocal Rank (MRR) and Mean Average Precision (MAP) based on input data, where MRR measures the ranking quality and MAP measures the average precision.
"""
| [
{
"method_name": "mrr",
"method_description": "def mrr(data):\n \"\"\"\n compute the MRR of the input data. MRR is a widely used evaluation index. It is the mean of reciprocal rank.\n :param data: the data must be a tuple, list 0,1,eg.([1,0,...],5). In each tuple (actual result,ground ... | MetricsCalculator2 | [
"MetricsCalculator2TestMrr",
"MetricsCalculator2TestMap",
"MetricsCalculator2Test"
] | class MetricsCalculator2:
def __init__(self):
pass
| [] |
ClassEval_58 | import random
class MinesweeperGame:
"""
This is a class that implements mine sweeping games including minesweeping and winning judgment.
"""
def __init__(self, n, k) -> None:
"""
Initializes the MinesweeperGame class with the size of the board and the number of mines.
:param n... | import unittest
class MinesweeperGameTestGenerateMineSweeperMap(unittest.TestCase):
def test_generate_mine_sweeper_map(self):
minesweeper_game = MinesweeperGame(3, 2)
length = len(minesweeper_game.minesweeper_map)
mine_num = 0
for row in minesweeper_game.minesweeper_map:
... | import random
class MinesweeperGame:
def __init__(self, n, k) -> None:
self.n = n
self.k = k
self.minesweeper_map = self.generate_mine_sweeper_map()
self.player_map = self.generate_playerMap()
self.score = 0
def generate_mine_sweeper_map(self):
arr = [[0 for row... | [
"import random"
] | """
This is a class that implements mine sweeping games including minesweeping and winning judgment.
"""
| [
{
"method_name": "generate_mine_sweeper_map",
"method_description": "def generate_mine_sweeper_map(self):\n \"\"\"\n Generates a minesweeper map with the given size of the board and the number of mines,the given parameter n is the size of the board,the size of the board is n*n,the parameter k ... | MinesweeperGame | [
"MinesweeperGameTestGenerateMineSweeperMap",
"MinesweeperGameTestGeneratePlayerMap",
"MinesweeperGameTestCheckWon",
"MinesweeperGameTestSweep",
"MinesweeperGameTestMain"
] | class MinesweeperGame:
def __init__(self, n, k) -> None:
"""
Initializes the MinesweeperGame class with the size of the board and the number of mines.
:param n: The size of the board, int.
:param k: The number of mines, int.
"""
self.n = n
self.k = k
... | [
"self.k",
"self.minesweeper_map",
"self.n",
"self.player_map",
"self.score"
] |
ClassEval_59 | from datetime import datetime
import numpy as np
class MovieBookingSystem:
"""
this is a class as movie booking system, which allows to add movies, book tickets and check the available movies within a given time range.
"""
def __init__(self):
"""
Initialize movies contains the informa... | 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(... | 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... | [
"from datetime import datetime",
"import numpy as np"
] | """
this is a class as movie booking system, which allows to add movies, book tickets and check the available movies within a given time range.
"""
| [
{
"method_name": "add_movie",
"method_description": "def add_movie(self, name, price, start_time, end_time, n):\n \"\"\"\n Add a new movie into self.movies\n :param name: str, movie name\n :param price: float, price for one ticket\n :param start_time: str\n :param e... | MovieBookingSystem | [
"MovieBookingSystemTestAddMovie",
"MovieBookingSystemTestBookTicket",
"MovieBookingSystemTestAvailableMovies",
"MovieBookingSystemTestMain"
] | class MovieBookingSystem:
def __init__(self):
"""
Initialize movies contains the information about movies
>>> system.movies
[{'name': 'Batman', 'price': 49.9, 'start_time': datetime.datetime(1900, 1, 1, 17, 5), 'end_time': datetime.datetime(1900, 1, 1, 19, 25),
'seats': arra... | [
"self.movies"
] |
ClassEval_60 | import sqlite3
class MovieTicketDB:
"""
This is a class for movie database operations, which allows for inserting movie information, searching for movie information by name, and deleting movie information by name.
"""
def __init__(self, db_name):
"""
Initializes the MovieTicketDB objec... | import unittest
import os
class MovieTicketDBTestInsertTicket(unittest.TestCase):
def setUp(self):
self.db_name = 'test_database.db'
self.db = MovieTicketDB(self.db_name)
def tearDown(self):
self.db.connection.close()
os.remove(self.db_name)
def test_insert_ticket_1(self)... | import sqlite3
class MovieTicketDB:
def __init__(self, db_name):
self.connection = sqlite3.connect(db_name)
self.cursor = self.connection.cursor()
self.create_table()
def create_table(self):
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS tickets (
... | [
"import sqlite3"
] | """
This is a class for movie database operations, which allows for inserting movie information, searching for movie information by name, and deleting movie information by name.
"""
| [
{
"method_name": "create_table",
"method_description": "def create_table(self):\n \"\"\"\n Creates a \"tickets\" table in the database if it does not exist already.Fields include ID of type int, movie name of type str, theater name of type str, seat number of type str, and customer name of typ... | MovieTicketDB | [
"MovieTicketDBTestInsertTicket",
"MovieTicketDBTestSearchTicketsByCustomer",
"MovieTicketDBTestDeleteTicket",
"MovieTicketDBTest"
] | class MovieTicketDB:
def __init__(self, db_name):
"""
Initializes the MovieTicketDB object with the specified database name.
:param db_name: str, the name of the SQLite database.
"""
self.connection = sqlite3.connect(db_name)
self.cursor = self.connection.cursor()
... | [
"self.connection",
"self.cursor"
] |
ClassEval_61 | class MusicPlayer:
"""
This is a class as a music player that provides to play, stop, add songs, remove songs, set volume, shuffle, and switch to the next or previous song.
"""
def __init__(self):
"""
Initializes the music player with an empty playlist, no current song, and a default vo... | import unittest
class MusicPlayerTestAddSong(unittest.TestCase):
def test_add_song(self):
musicPlayer = MusicPlayer()
musicPlayer.add_song("song1")
self.assertEqual(musicPlayer.playlist, ["song1"])
def test_add_song2(self):
musicPlayer = MusicPlayer()
musicPlayer.add_s... | class MusicPlayer:
def __init__(self):
self.playlist = []
self.current_song = None
self.volume = 50
def add_song(self, song):
self.playlist.append(song)
def remove_song(self, song):
if song in self.playlist:
self.playlist.remove(song)
if self... | [
"import random"
] | """
This is a class as a music player that provides to play, stop, add songs, remove songs, set volume, shuffle, and switch to the next or previous song.
"""
| [
{
"method_name": "add_song",
"method_description": "def add_song(self, song):\n \"\"\"\n Adds a song to the playlist.\n :param song: The song to add to the playlist, str.\n >>> musicPlayer = MusicPlayer()\n >>> musicPlayer.add_song(\"song1\")\n >>> musicPlayer.playl... | MusicPlayer | [
"MusicPlayerTestAddSong",
"MusicPlayerTestRemoveSong",
"MusicPlayerTestPlay",
"MusicPlayerTestStop",
"MusicPlayerTestSwitchSong",
"MusicPlayerTestPreviousSong",
"MusicPlayerTestSetVolume",
"MusicPlayerTestShuffle",
"MusicPlayerTestMain"
] | class MusicPlayer:
def __init__(self):
"""
Initializes the music player with an empty playlist, no current song, and a default volume of 50.
"""
self.playlist = []
self.current_song = None
self.volume = 50
| [
"self.current_song",
"self.playlist",
"self.volume"
] |
ClassEval_62 | class NLPDataProcessor:
"""
The class processes NLP data by removing stop words from a list of strings using a pre-defined stop word list.
"""
def construct_stop_word_list(self):
"""
Construct a stop word list including 'a', 'an', 'the'.
:return: a list of stop words
>>... | 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... | 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 ... | [] | """
The class processes NLP data by removing stop words from a list of strings using a pre-defined stop word list.
"""
| [
{
"method_name": "construct_stop_word_list",
"method_description": "def construct_stop_word_list(self):\n \"\"\"\n Construct a stop word list including 'a', 'an', 'the'.\n :return: a list of stop words\n >>> NLPDataProcessor.construct_stop_word_list()\n ['a', 'an', 'the']\... | NLPDataProcessor | [
"NLPDataProcessorTestConstruct",
"NLPDataProcessorTestRemove",
"NLPDataProcessorTestProcess"
] | class NLPDataProcessor:
| [] |
ClassEval_63 | import re
from collections import Counter
class NLPDataProcessor2:
"""
The class processes NLP data by extracting words from a list of strings, calculating the frequency of each word, and returning the top 5 most frequent words.
"""
def process_data(self, string_list):
"""
keep only E... | import unittest
class NLPDataProcessorTestProcessData(unittest.TestCase):
def setUp(self):
self.processor = NLPDataProcessor2()
def test_process_data(self):
string_list = ["Hello World!", "This is a test."]
expected_output = [['hello', 'world'], ['this', 'is', 'a', 'test']]
se... | from collections import Counter
import re
class NLPDataProcessor2:
def process_data(self, string_list):
words_list = []
for string in string_list:
# Remove non-English letters and convert to lowercase
processed_string = re.sub(r'[^a-zA-Z\s]', '', string.lower())
... | [
"from collections import Counter",
"import re"
] | """
The class processes NLP data by extracting words from a list of strings, calculating the frequency of each word, and returning the top 5 most frequent words.
"""
| [
{
"method_name": "process_data",
"method_description": "def process_data(self, string_list):\n \"\"\"\n keep only English letters and spaces in the string, then convert the string to lower case, and then split the string into a list of words.\n :param string_list: a list of strings\n ... | NLPDataProcessor2 | [
"NLPDataProcessorTestProcessData",
"NLPDataProcessorTestCalculate",
"NLPDataProcessorTestProcess"
] | class NLPDataProcessor2:
| [] |
ClassEval_64 | class NumberConverter:
"""
The class allows to convert decimal to binary, octal and hexadecimal repectively and contrarily
"""
@staticmethod
def decimal_to_binary(decimal_num):
"""
Convert a number from decimal format to binary format.
:param decimal_num: int, decimal numbe... | 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... | 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... | [] | """
The class allows to convert decimal to binary, octal and hexadecimal repectively and contrarily
"""
| [
{
"method_name": "decimal_to_binary",
"method_description": "def decimal_to_binary(decimal_num):\n \"\"\"\n Convert a number from decimal format to binary format.\n :param decimal_num: int, decimal number\n :return: str, the binary representation of an integer.\n >>> Numbe... | NumberConverter | [
"NumberConverterTestDecimalToBinary",
"NumberConverterTestBinaryToDecimal",
"NumberConvertTestDecimalToOctal",
"NumberConvertTestOctalToDecimal",
"NumberConvertTestDecimalToHex",
"NumberConvertTestHexToDecimal",
"NumberConvertTestMain"
] | class NumberConverter:
| [] |
ClassEval_65 | class NumberWordFormatter:
"""
This is a class that provides to convert numbers into their corresponding English word representation, including handling the conversion of both the integer and decimal parts, and incorporating appropriate connectors and units.
"""
def __init__(self):
"""
... | 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... | 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",
... | [] | """
This is a class that provides to convert numbers into their corresponding English word representation, including handling the conversion of both the integer and decimal parts, and incorporating appropriate connectors and units.
"""
| [
{
"method_name": "format",
"method_description": "def format(self, x):\n \"\"\"\n Converts a number into words format\n :param x: int or float, the number to be converted into words format\n :return: str, the number in words format\n >>> formatter = NumberWordFormatter()\n... | NumberWordFormatter | [
"NumberWordFormatterTestFormat",
"NumberWordFormatterTestFormatString",
"NumberWordFormatterTestTransTwo",
"NumberWordFormatterTestTransThree",
"NumberWordFormatterTestParseMore",
"NumberWordFormatterTest"
] | class NumberWordFormatter:
def __init__(self):
"""
Initialize NumberWordFormatter object.
"""
self.NUMBER = ["", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE"]
self.NUMBER_TEEN = ["TEN", "ELEVEN", "TWELVE", "THIRTEEN", "FOURTEEN", "FIFTEEN", "SIXTEEN... | [
"self.NUMBER",
"self.NUMBER_MORE",
"self.NUMBER_SUFFIX",
"self.NUMBER_TEEN",
"self.NUMBER_TEN"
] |
ClassEval_66 | class NumericEntityUnescaper:
"""
This is a class that provides functionality to replace numeric entities with their corresponding characters in a given string.
"""
def __init__(self):
pass
def replace(self, string):
"""
Replaces numeric character references (HTML entities)... | import unittest
class NumericEntityUnescaperTestReplace(unittest.TestCase):
def test_replace_1(self):
unescaper = NumericEntityUnescaper()
res = unescaper.replace("ABC")
self.assertEqual(res, "ABC")
def test_replace_2(self):
unescaper = NumericEntityUnescaper()
... | 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
... | [] | """
This is a class that provides functionality to replace numeric entities with their corresponding characters in a given string.
"""
| [
{
"method_name": "replace",
"method_description": "def replace(self, string):\n \"\"\"\n Replaces numeric character references (HTML entities) in the input string with their corresponding Unicode characters.\n :param string: str, the input string containing numeric character references.... | NumericEntityUnescaper | [
"NumericEntityUnescaperTestReplace",
"NumericEntityUnescaperTestIsHexChar",
"unescaperTest"
] | class NumericEntityUnescaper:
def __init__(self):
pass
| [] |
ClassEval_67 | class Order:
"""
The class manages restaurant orders by allowing the addition of dishes, calculation of the total cost, and checkout.
"""
def __init__(self):
"""
Initialize the order management system
self.menu stores the dishes of resturant inventory
menu = [{"dish": d... | 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": ... | 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):
... | [] | """
The class manages restaurant orders by allowing the addition of dishes, calculation of the total cost, and checkout.
"""
| [
{
"method_name": "add_dish",
"method_description": "def add_dish(self, dish):\n \"\"\"\n Check the self.menu and add into self.selected_dish if the dish count is valid.\n And if the dish has successfully been added, change the count in self.menu.\n :param dish: dict, the informat... | Order | [
"OrderTestAddDish",
"OrderTestCalculateTotal",
"OrderTestCheckout",
"OrderTest"
] | class Order:
def __init__(self):
"""
Initialize the order management system
self.menu stores the dishes of resturant inventory
menu = [{"dish": dish name, "price": price, "count": count}, ...]
self.selected_dishes stores the dished selected by customer
selected_dish ... | [
"self.menu",
"self.sales",
"self.selected_dishes"
] |
ClassEval_68 | class PageUtil:
"""
PageUtil class is a versatile utility for handling pagination and search functionalities in an efficient and convenient manner.
"""
def __init__(self, data, page_size):
"""
Initialize the PageUtil object with the given data and page size.
:param data: list, t... | 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]
... | 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 class is a versatile utility for handling pagination and search functionalities in an efficient and convenient manner.
"""
| [
{
"method_name": "get_page",
"method_description": "def get_page(self, page_number):\n \"\"\"\n Retrieve a specific page of data.\n :param page_number: int, the page number to fetch\n :return: list, the data on the specified page\n >>> page_util = PageUtil([1, 2, 3, 4], 1)... | PageUtil | [
"PageUtilTestGetPage",
"PageUtilTestGetPageInfo",
"PageUtilTestSearch",
"PageUtilTest"
] | class PageUtil:
def __init__(self, data, page_size):
"""
Initialize the PageUtil object with the given data and page size.
:param data: list, the data to be paginated
:param page_size: int, the number of items per page
"""
self.data = data
self.page_size = pa... | [
"self.data",
"self.page_size",
"self.total_items",
"self.total_pages"
] |
ClassEval_69 | import PyPDF2
class PDFHandler:
"""
The class allows merging multiple PDF files into one and extracting text from PDFs using PyPDF2 library.
"""
def __init__(self, filepaths):
"""
takes a list of file paths filepaths as a parameter.
It creates a list named readers using PyPDF2,... | import os
import unittest
from PyPDF2 import PdfFileReader
from reportlab.pdfgen import canvas
class TestPDFHandler(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.test_files = ["test1.pdf", "test2.pdf"]
cls.test_text = ["This is a test1.", "This is a test2."]
for i in range(... | import PyPDF2
class PDFHandler:
def __init__(self, filepaths):
self.filepaths = filepaths
# PdfFileReader is deprecated and was removed in PyPDF2 3.0.0. Use PdfReader instead.
self.readers = [PyPDF2.PdfReader(fp) for fp in filepaths]
def merge_pdfs(self, output_filepath):
pdf_... | [
"import PyPDF2"
] | """
The class allows merging multiple PDF files into one and extracting text from PDFs using PyPDF2 library.
"""
| [
{
"method_name": "merge_pdfs",
"method_description": "def merge_pdfs(self, output_filepath):\n \"\"\"\n Read files in self.readers which stores handles to multiple PDF files.\n Merge them to one pdf and update the page number, then save in disk.\n :param output_filepath: str, oup... | PDFHandler | [
"TestPDFHandler",
"PDFHandlerTestMergePdfs",
"PDFHandlerTestExtractTextFromPdfs",
"PDFHandlerTestMain"
] | class PDFHandler:
def __init__(self, filepaths):
"""
takes a list of file paths filepaths as a parameter.
It creates a list named readers using PyPDF2, where each reader opens a file from the given paths.
"""
self.filepaths = filepaths
self.readers = [PyPDF2.PdfFileR... | [
"self.filepaths",
"self.readers"
] |
ClassEval_70 | class PersonRequest:
"""
This class validates input personal information data and sets invalid fields to None based to specific rules.
"""
def __init__(self, name: str, sex: str, phoneNumber: str):
"""
Initialize PersonRequest object with the provided information.
:param name: s... | 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... | 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:
... | [] | """
This class validates input personal information data and sets invalid fields to None based to specific rules.
"""
| [
{
"method_name": "_validate_name",
"method_description": "def _validate_name(self, name: str) -> str:\n \"\"\"\n Validate the name and return it. If name is empty or exceeds 33 characters in length, set to None.\n :param name: str, the name to validate\n :return: str, the validat... | PersonRequest | [
"PersonRequestTestValidateName",
"PersonRequestTestValidateSex",
"PersonRequestTestValidatePhoneNumber",
"PersonRequestTest"
] | class PersonRequest:
def __init__(self, name: str, sex: str, phoneNumber: str):
"""
Initialize PersonRequest object with the provided information.
:param name: str, the name of the person
:param sex: str, the sex of the person
:param phoneNumber: str, the phone number of the... | [
"self.name",
"self.phoneNumber",
"self.sex"
] |
ClassEval_71 | class PushBoxGame:
"""
This class implements a functionality of a sokoban game, where the player needs to move boxes to designated targets in order to win.
"""
def __init__(self, map):
"""
Initialize the push box game with the map and various attributes.
:param map: list[str], t... | 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):
... | 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... | [] | """
This class implements a functionality of a sokoban game, where the player needs to move boxes to designated targets in order to win.
"""
| [
{
"method_name": "init_game",
"method_description": "def init_game(self):\n \"\"\"\n Initialize the game by setting the positions of the player, targets, and boxes based on the map.\n >>> game = PushBoxGame([\"#####\", \"#O #\", \"# X #\", \"# G#\", \"#####\"]) \n >>> game.targ... | PushBoxGame | [
"PushBoxGameTestInitGame",
"PushBoxGameTestCheckWin",
"PushBoxGameTestMove"
] | class PushBoxGame:
def __init__(self, map):
"""
Initialize the push box game with the map and various attributes.
:param map: list[str], the map of the push box game, represented as a list of strings.
Each character on the map represents a different element, including the follo... | [
"self.boxes",
"self.is_game_over",
"self.map",
"self.player_col",
"self.player_row",
"self.target_count",
"self.targets"
] |
ClassEval_72 | import re
class RegexUtils:
"""
The class provides to match, find all occurrences, split, and substitute text using regular expressions. It also includes predefined patterns, validating phone numbers and extracting email addresses.
"""
def match(self, pattern, text):
"""
Check if the ... | import unittest
class RegexUtilsTestMatch(unittest.TestCase):
def test_match_1(self):
ru = RegexUtils()
res = ru.match(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890")
self.assertEqual(res, True)
def test_match_2(self):
ru = RegexUtils()
res = ru.match(r'\b\d{3}-\d{3}-\d{4}\b... | import re
class RegexUtils:
def match(self, pattern, text):
ans = re.match(pattern, text)
if ans:
return True
else:
return False
def findall(self, pattern, text):
return re.findall(pattern, text)
def split(self, pattern, text):
return re.s... | [
"import re"
] | """
The class provides to match, find all occurrences, split, and substitute text using regular expressions. It also includes predefined patterns, validating phone numbers and extracting email addresses.
"""
| [
{
"method_name": "match",
"method_description": "def match(self, pattern, text):\n \"\"\"\n Check if the text matches the regular expression\n :param pattern: string, Regular expression pattern\n :param text: string, Text to match\n :return: True or False, representing whe... | RegexUtils | [
"RegexUtilsTestMatch",
"RegexUtilsTestFindall",
"RegexUtilsTestSplit",
"RegexUtilsTestSub",
"RegexUtilsTestGenerateEmailPattern",
"RegexUtilsTestGeneratePhoneNumberPattern",
"RegexUtilsTestGenerateSplitSentencesPattern",
"RegexUtilsTestSplitSentences",
"RegexUtilsTestValidatePhoneNumber",
"RegexUt... | class RegexUtils:
| [] |
ClassEval_73 | class RPGCharacter:
"""
The class represents a role-playing game character, which allows to attack other characters, heal, gain experience, level up, and check if the character is alive.
"""
def __init__(self, name, hp, attack_power, defense, level=1):
"""
Initialize an RPG character ob... | 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):
... | 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... | [] | """
The class represents a role-playing game character, which allows to attack other characters, heal, gain experience, level up, and check if the character is alive.
"""
| [
{
"method_name": "attack",
"method_description": "def attack(self, other_character):\n \"\"\"\n Attack another character. The damage caused needs to offset the defense value.\n :param other_character: str, The character being attacked.\n >>> player_1 = RPGCharacter('player 1', 10... | RPGCharacter | [
"RPGCharacterTestAttack",
"RPGCharacterTestHeal",
"RPGCharacterTestGainExp",
"RPGCharacterTestLevelUp",
"RPGCharacterTestIsAlive",
"RPGCharacterTestMain"
] | class RPGCharacter:
def __init__(self, name, hp, attack_power, defense, level=1):
"""
Initialize an RPG character object.
:param name: strm, the name of the character.
:param hp: int, The health points of the character.
:param attack_power: int, the attack power of the chara... | [
"self.attack_power",
"self.defense",
"self.exp",
"self.hp",
"self.level",
"self.name"
] |
ClassEval_74 | class Server:
"""
This is a class as a server, which handles a white list, message sending and receiving, and information display.
"""
def __init__(self):
"""
Initialize the whitelist as an empty list, and initialize the sending and receiving information as an empty dictionary
... | 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)
... | 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
... | [] | """
This is a class as a server, which handles a white list, message sending and receiving, and information display.
"""
| [
{
"method_name": "add_white_list",
"method_description": "def add_white_list(self, addr):\n \"\"\"\n Add an address to the whitelist and do nothing if it already exists\n :param addr: int, address to be added\n :return: new whitelist, return False if the address already exists\n ... | Server | [
"ServerTestAddWhiteList",
"ServerTestDelWhiteList",
"ServerTestRecv",
"ServerTestSend",
"ServerTestShow",
"ServerTest"
] | class Server:
def __init__(self):
"""
Initialize the whitelist as an empty list, and initialize the sending and receiving information as an empty dictionary
"""
self.white_list = []
self.send_struct = {}
self.receive_struct = {}
| [
"self.receive_struct",
"self.send_struct",
"self.white_list"
] |
ClassEval_75 | class ShoppingCart:
"""
The class manages items, their prices, quantities, and allows to for add, removie, view items, and calculate the total price.
"""
def __init__(self):
"""
Initialize the items representing the shopping list as an empty dictionary
"""
self.items = {... | 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 ... | 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... | [] | """
The class manages items, their prices, quantities, and allows to for add, removie, view items, and calculate the total price.
"""
| [
{
"method_name": "add_item",
"method_description": "def add_item(self, item, price, quantity=1):\n \"\"\"\n Add item information to the shopping list items, including price and quantity. The default quantity is 1\n :param item: string, Item to be added\n :param price: float, The ... | ShoppingCart | [
"ShoppingCartTestAddItem",
"ShoppingCartTestRemoveItem",
"ShoppingCartTestViewItems",
"ShoppingCartTestTotalPrice",
"ShoppingCartTest"
] | class ShoppingCart:
def __init__(self):
"""
Initialize the items representing the shopping list as an empty dictionary
"""
self.items = {}
| [
"self.items"
] |
ClassEval_76 | class SignInSystem:
"""
This is a class as sigin in system, including adding users, signing in/out, checking sign-in status, and retrieving signed-in/not signed-in users.
"""
def __init__(self):
"""
Initialize the sign-in system.
"""
self.users = {}
def add_user(sel... | 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... | 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:
... | [] | """
This is a class as sigin in system, including adding users, signing in/out, checking sign-in status, and retrieving signed-in/not signed-in users.
"""
| [
{
"method_name": "add_user",
"method_description": "def add_user(self, username):\n \"\"\"\n Add a user to the sign-in system if the user wasn't in the self.users.\n And the initial state is False.\n :param username: str, the username to be added.\n :return: bool, True if ... | SignInSystem | [
"SignInSystemTestAddUser",
"SignInSystemTestSignIn",
"SignInSystemTestCheckSignIn",
"SignInSystemTestAllSignedIn",
"SignInSystemTestAllNotSignedIn",
"SignInSystemTestMain"
] | class SignInSystem:
def __init__(self):
"""
Initialize the sign-in system.
"""
self.users = {}
| [
"self.users"
] |
ClassEval_77 | import random
class Snake:
"""
The class is a snake game, with allows snake to move and eat food, and also enables to reset, and generat a random food position.
"""
def __init__(self, SCREEN_WIDTH, SCREEN_HEIGHT, BLOCK_SIZE, food_position):
"""
Initialize the length of the snake, scree... | import unittest
class SnakeTestMove(unittest.TestCase):
def test_move_1(self):
snake = Snake(100, 100, 1, (51, 51))
snake.move((1, 1))
self.assertEqual(snake.length, 2)
self.assertEqual(snake.positions[0], (51, 51))
self.assertEqual(snake.positions[1], (50, 50))
sel... | import random
class Snake:
def __init__(self, SCREEN_WIDTH, SCREEN_HEIGHT, BLOCK_SIZE, food_position):
self.length = 1
self.SCREEN_WIDTH = SCREEN_WIDTH
self.SCREEN_HEIGHT = SCREEN_HEIGHT
self.BLOCK_SIZE = BLOCK_SIZE
self.positions = [((SCREEN_WIDTH / 2), (SCREEN_HEIGHT / 2)... | [
"import random"
] | """
The class is a snake game, with allows snake to move and eat food, and also enables to reset, and generat a random food position.
"""
| [
{
"method_name": "move",
"method_description": "def move(self, direction):\n \"\"\"\n Move the snake in the specified direction. If the new position of the snake's head is equal to the position of the food, then eat the food; If the position of the snake's head is equal to the position of its ... | Snake | [
"SnakeTestMove",
"SnakeTestRandomFoodPosition",
"SnakeTestReset",
"SnakeTestEatFood",
"SnakeTest"
] | class Snake:
def __init__(self, SCREEN_WIDTH, SCREEN_HEIGHT, BLOCK_SIZE, food_position):
"""
Initialize the length of the snake, screen width, screen height, block size, snake head position, score, and food position.
:param SCREEN_WIDTH: int
:param SCREEN_HEIGHT: int
:param ... | [
"self.BLOCK_SIZE",
"self.SCREEN_HEIGHT",
"self.SCREEN_WIDTH",
"self.food_position",
"self.length",
"self.positions",
"self.score"
] |
ClassEval_78 | import re
class SplitSentence:
"""
The class allows to split sentences, count words in a sentence, and process a text file to find the maximum word count.
"""
def split_sentences(self, sentences_string):
"""
Split a string into a list of sentences. Sentences end with . or ? and with a... | 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... | 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.... | [
"import re"
] | """
The class allows to split sentences, count words in a sentence, and process a text file to find the maximum word count.
"""
| [
{
"method_name": "split_sentences",
"method_description": "def split_sentences(self, sentences_string):\n \"\"\"\n Split a string into a list of sentences. Sentences end with . or ? and with a space after that. Please note that Mr. also end with . but are not sentences.\n :param sentenc... | SplitSentence | [
"SplitSentenceTestSplitSentences",
"SplitSentenceTestCountWords",
"SplitSentenceTestProcessTextFile",
"SplitSentenceTest"
] | class SplitSentence:
| [] |
ClassEval_79 | class SQLGenerator:
"""
This class generates SQL statements for common operations on a table, such as SELECT, INSERT, UPDATE, and DELETE.
"""
def __init__(self, table_name):
"""
Initialize the table name.
:param table_name: str
"""
self.table_name = table_name
... | 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 = ... | 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... | [] | """
This class generates SQL statements for common operations on a table, such as SELECT, INSERT, UPDATE, and DELETE.
"""
| [
{
"method_name": "select",
"method_description": "def select(self, fields=None, condition=None):\n \"\"\"\n Generates a SELECT SQL statement based on the specified fields and conditions.\n :param fields: list, optional. Default is None. The list of fields to be queried.\n :param ... | SQLGenerator | [
"SQLGeneratorTestSelect",
"SQLGeneratorTestInsert",
"SQLGeneratorTestUpdate",
"SQLGeneratorTestDelete",
"SQLGeneratorTestSelectFemaleUnderAge",
"SQLGeneratorTestSelectByAgeRange",
"SQLGeneratorTestMain"
] | class SQLGenerator:
def __init__(self, table_name):
"""
Initialize the table name.
:param table_name: str
"""
self.table_name = table_name
| [
"self.table_name"
] |
ClassEval_80 | class SQLQueryBuilder:
"""
This class provides to build SQL queries, including SELECT, INSERT, UPDATE, and DELETE statements.
"""
@staticmethod
def select(table, columns='*', where=None):
"""
Generate the SELECT SQL statement from the given parameters.
:param table: str, t... | 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(... | 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... | [] | """
This class provides to build SQL queries, including SELECT, INSERT, UPDATE, and DELETE statements.
"""
| [
{
"method_name": "select",
"method_description": "def select(table, columns='*', where=None):\n \"\"\"\n Generate the SELECT SQL statement from the given parameters.\n :param table: str, the query table in database.\n :param columns: list of str, ['col1', 'col2'].\n :param... | SQLQueryBuilder | [
"SQLQueryBuilderTestSelect",
"SQLQueryBuilderTestInsert",
"SQLQueryBuilderTestDetele",
"SQLQueryBuilderTestUpdate",
"SQLQueryBuilderTestMain"
] | class SQLQueryBuilder:
| [] |
ClassEval_81 | import math
class Statistics3:
"""
This is a class that implements methods for calculating indicators such as median, mode, correlation matrix, and Z-score in statistics.
"""
@staticmethod
def median(data):
"""
calculates the median of the given list.
:param data: the given... | 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]), ... | 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):... | [
"import math"
] | """
This is a class that implements methods for calculating indicators such as median, mode, correlation matrix, and Z-score in statistics.
"""
| [
{
"method_name": "median",
"method_description": "def median(data):\n \"\"\"\n calculates the median of the given list.\n :param data: the given list, list.\n :return: the median of the given list, float.\n >>> statistics3 = Statistics3()\n >>> statistics3.median([1... | Statistics3 | [
"Statistics3TestMedian",
"Statistics3TestMode",
"Statistics3TestCorrelation",
"Statistics3TestMean",
"Statistics3TestCorrelationMatrix",
"Statistics3TestStandardDeviation",
"Statistics3TestZScore",
"Statistics3TestMain"
] | class Statistics3:
| [] |
ClassEval_82 | class StockPortfolioTracker:
"""
This is a class as StockPortfolioTracker that allows to add stocks, remove stocks, buy stocks, sell stocks, calculate the total value of the portfolio, and obtain a summary of the portfolio.
"""
def __init__(self, cash_balance):
"""
Initialize the StockP... | 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... | 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... | [] | """
This is a class as StockPortfolioTracker that allows to add stocks, remove stocks, buy stocks, sell stocks, calculate the total value of the portfolio, and obtain a summary of the portfolio.
"""
| [
{
"method_name": "add_stock",
"method_description": "def add_stock(self, stock):\n \"\"\"\n Add a stock to the portfolio.\n :param stock: a dictionary with keys \"name\", \"price\", and \"quantity\"\n >>> tracker = StockPortfolioTracker(10000.0)\n >>> tracker.add_stock({\"... | StockPortfolioTracker | [
"StockPortfolioTrackerTestAddStock",
"StockPortfolioTrackerTestRemoveStock",
"StockPortfolioTrackerTestBuyStock",
"StockPortfolioTrackerTestSellStock",
"StockPortfolioTrackerTestCalculatePortfolioValue",
"StockPortfolioTrackerTestGetPortfolioSummary",
"StockPortfolioTrackerTestGetStockValue",
"StockPo... | class StockPortfolioTracker:
def __init__(self, cash_balance):
"""
Initialize the StockPortfolioTracker class with a cash balance and an empty portfolio.
"""
self.portfolio = []
self.cash_balance = cash_balance
| [
"self.cash_balance",
"self.portfolio"
] |
ClassEval_83 | import sqlite3
class StudentDatabaseProcessor:
"""
This is a class with database operation, including inserting student information, searching for student information by name, and deleting student information by name.
"""
def __init__(self, database_name):
"""
Initializes the StudentDa... | import unittest
class StudentDatabaseProcessorTestInsertStudent(unittest.TestCase):
def setUp(self):
self.processor = StudentDatabaseProcessor("test_database.db")
self.processor.create_student_table()
def tearDown(self):
conn = sqlite3.connect("test_database.db")
conn.execute(... | import sqlite3
class StudentDatabaseProcessor:
def __init__(self, database_name):
self.database_name = database_name
def create_student_table(self):
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
create_table_query = """
CREATE TABLE IF NOT EXISTS ... | [
"import sqlite3"
] | """
This is a class with database operation, including inserting student information, searching for student information by name, and deleting student information by name.
"""
| [
{
"method_name": "create_student_table",
"method_description": "def create_student_table(self):\n \"\"\"\n Creates a \"students\" table in the database if it does not exist already.Fields include ID of type int, name of type str, age of type int, gender of type str, and grade of type int\n ... | StudentDatabaseProcessor | [
"StudentDatabaseProcessorTestInsertStudent",
"StudentDatabaseProcessorTestSearchStudentByName",
"StudentDatabaseProcessorTestDeleteStudentByName",
"StudentDatabaseProcessorTest"
] | class StudentDatabaseProcessor:
def __init__(self, database_name):
"""
Initializes the StudentDatabaseProcessor object with the specified database name.
:param database_name: str, the name of the SQLite database.
"""
self.database_name = database_name
| [
"self.database_name"
] |
ClassEval_84 | import json
class TextFileProcessor:
"""
The class handles reading, writing, and processing text files. It can read the file as JSON, read the raw text, write content to the file, and process the file by removing non-alphabetic characters.
"""
def __init__(self, file_path):
"""
Initial... | import unittest
import json
from unittest.mock import MagicMock
import os
class TextFileProcessorTestReadFileAsJson(unittest.TestCase):
def setUp(self):
self.files = ['test_1.txt', 'test_2.txt', 'test_3.txt', 'test_4.txt', 'test_5.txt']
self.contents = ['{\n "name": "test",\n "age": 12\n}', ... | import json
class TextFileProcessor:
def __init__(self, file_path):
self.file_path = file_path
def read_file_as_json(self):
with open(self.file_path, 'r') as file:
data = json.load(file)
return data
def read_file(self):
with open(self.file_path, 'r') as file:... | [
"import json"
] | """
The class handles reading, writing, and processing text files. It can read the file as JSON, read the raw text, write content to the file, and process the file by removing non-alphabetic characters.
"""
| [
{
"method_name": "read_file_as_json",
"method_description": "def read_file_as_json(self):\n \"\"\"\n Read the self.file_path file as json format.\n if the file content doesn't obey json format, the code will raise error.\n :return data: dict if the file is stored as json format, ... | TextFileProcessor | [
"TextFileProcessorTestReadFileAsJson",
"TextFileProcessorTestReadFile",
"TextFileProcessorTestWriteFile",
"TextFileProcessorTestProcessFile",
"TextFileProcessorTestMain"
] | class TextFileProcessor:
def __init__(self, file_path):
"""
Initialize the file path.
:param file_path: str
"""
self.file_path = file_path
| [
"self.file_path"
] |
ClassEval_85 | import time
class Thermostat:
"""
The class manages temperature control, including setting and retrieving the target temperature, adjusting the mode, and simulating temperature operation.
"""
def __init__(self, current_temperature, target_temperature, mode):
"""
initialize instances of... | 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... | 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... | [
"import time"
] | """
The class manages temperature control, including setting and retrieving the target temperature, adjusting the mode, and simulating temperature operation.
"""
| [
{
"method_name": "get_target_temperature",
"method_description": "def get_target_temperature(self):\n \"\"\"\n Get the target temperature of an instance of the Thermostat class.\n :return self.current_temperature: int\n >>> thermostat.get_target_temperature()\n 37.5\n ... | Thermostat | [
"ThermostatTestGetTargetTemperature",
"ThermostatTestSetTargetTemperature",
"ThermostatTestGetMode",
"ThermostatTestSetMode",
"ThermostatTestAutoSetMode",
"ThermostatTestAutoCheckConflict",
"ThermostatTestSimulateOperation",
"ThermostatTestMain"
] | class Thermostat:
def __init__(self, current_temperature, target_temperature, mode):
"""
initialize instances of the Thermostat class, including the current temperature, target temperature, and operating mode.
:param current_temperature: float
:param target_temperature: float
... | [
"self.current_temperature",
"self.mode",
"self.target_temperature"
] |
ClassEval_86 | class TicTacToe:
"""
The class represents a game of Tic-Tac-Toe and its functions include making a move on the board, checking for a winner, and determining if the board is full.
"""
def __init__(self, N=3):
"""
Initialize a 3x3 game board with all empty spaces and current symble player... | import unittest
class TicTacToeTestMakeMove(unittest.TestCase):
def test_make_move_1(self):
ttt = TicTacToe()
self.assertEqual(ttt.current_player, 'X')
self.assertTrue(ttt.make_move(0, 0))
self.assertEqual(ttt.current_player, 'O')
# move invalid
def test_make_move_2(self):
... | class TicTacToe:
def __init__(self, N=3):
self.board = [[' ' for _ in range(N)] for _ in range(3)]
self.current_player = 'X'
def make_move(self, row, col):
if self.board[row][col] == ' ':
self.board[row][col] = self.current_player
self.current_player = 'O' if sel... | [] | """
The class represents a game of Tic-Tac-Toe and its functions include making a move on the board, checking for a winner, and determining if the board is full.
"""
| [
{
"method_name": "make_move",
"method_description": "def make_move(self, row, col):\n \"\"\"\n Place the current player's mark at the specified position on the board and switch the mark.\n :param row: int, the row index of the position\n :param col: int, the column index of the p... | TicTacToe | [
"TicTacToeTestMakeMove",
"TicTacToeTestCheckWinner",
"TicTacToeTestIsBoardFull",
"TicTacToeTestMain"
] | class TicTacToe:
def __init__(self, N=3):
"""
Initialize a 3x3 game board with all empty spaces and current symble player, default is 'X'.
"""
self.board = [[' ' for _ in range(N)] for _ in range(3)]
self.current_player = 'X'
| [
"self.board",
"self.current_player"
] |
ClassEval_87 | import datetime
import time
class TimeUtils:
"""
This is a time util class, including getting the current time and date, adding seconds to a datetime, converting between strings and datetime objects, calculating the time difference in minutes, and formatting a datetime object.
"""
def __init__(self):... | import unittest
class TimeUtilsTestGetCurrentTime(unittest.TestCase):
def test_get_current_time_1(self):
timeutils = TimeUtils()
self.assertEqual(timeutils.get_current_time(), timeutils.datetime.strftime("%H:%M:%S"))
def test_get_current_time_2(self):
timeutils = TimeUtils()
s... | import datetime
import time
class TimeUtils:
def __init__(self):
self.datetime = datetime.datetime.now()
def get_current_time(self):
format = "%H:%M:%S"
return self.datetime.strftime(format)
def get_current_date(self):
format = "%Y-%m-%d"
return self.datetime.strf... | [
"import datetime",
"import time"
] | """
This is a time util class, including getting the current time and date, adding seconds to a datetime, converting between strings and datetime objects, calculating the time difference in minutes, and formatting a datetime object.
"""
| [
{
"method_name": "get_current_time",
"method_description": "def get_current_time(self):\n \"\"\"\n Return the current time in the format of '%H:%M:%S'\n :return: string\n >>> timeutils = TimeUtils()\n >>> timeutils.get_current_time()\n \"19:19:22\"\n \"\"\"",... | TimeUtils | [
"TimeUtilsTestGetCurrentTime",
"TimeUtilsTestGetCurrentDate",
"TimeUtilsTestAddSeconds",
"TimeUtilsTestStringToDatetime",
"TimeUtilsTestDatetimeToString",
"TimeUtilsTestGetMinutes",
"TimeUtilsTestGetFormatTime",
"TimeUtilsTest"
] | class TimeUtils:
def __init__(self):
"""
Get the current datetime
"""
self.datetime = datetime.datetime.now()
| [
"self.datetime"
] |
ClassEval_88 | from math import pi, fabs
class TriCalculator:
"""
The class allows to calculate trigonometric values, including cosine, sine, and tangent, using Taylor series approximations.
"""
def __init__(self):
pass
def cos(self, x):
"""
Calculate the cos value of the x-degree angle... | 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)
... | 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
... | [
"from math import pi, fabs"
] | """
The class allows to calculate trigonometric values, including cosine, sine, and tangent, using Taylor series approximations.
"""
| [
{
"method_name": "cos",
"method_description": "def cos(self, x):\n \"\"\"\n Calculate the cos value of the x-degree angle\n :param x:float\n :return:float\n >>> tricalculator = TriCalculator()\n >>> tricalculator.cos(60)\n 0.5\n \"\"\"",
"test_clas... | TriCalculator | [
"TriCalculatorTestCos",
"TriCalculatorTestFactorial",
"TriCalculatorTestTaylor",
"TriCalculatorTestSin",
"TriCalculatorTestTan",
"TriCalculatorTest"
] | class TriCalculator:
def __init__(self):
pass
| [] |
ClassEval_89 | import random
class TwentyFourPointGame:
"""
This ia a game of twenty-four points, which provides to generate four numbers and check whether player's expression is equal to 24.
"""
def __init__(self) -> None:
self.nums = []
def _generate_cards(self):
"""
Generate random n... | import unittest
class TwentyFourPointGameTestGetMyCards(unittest.TestCase):
def test_get_my_cards_1(self):
game = TwentyFourPointGame()
cards = game.get_my_cards()
self.assertEqual(len(cards), 4)
for card in cards:
self.assertIn(card, [1, 2, 3, 4, 5, 6, 7, 8, 9])
d... | import random
class TwentyFourPointGame:
def __init__(self) -> None:
self.nums = []
def _generate_cards(self):
for i in range(4):
self.nums.append(random.randint(1, 9))
assert len(self.nums) == 4
def get_my_cards(self):
self.nums = []
self._generate_ca... | [
"import random"
] | """
This ia a game of twenty-four points, which provides to generate four numbers and check whether player's expression is equal to 24.
"""
| [
{
"method_name": "_generate_cards",
"method_description": "def _generate_cards(self):\n \"\"\"\n Generate random numbers between 1 and 9 for the cards.\n \"\"\"",
"test_class": "TwentyFourPointGameTestGetMyCards",
"test_code": "class TwentyFourPointGameTestGetMyCards(unittest.Te... | TwentyFourPointGame | [
"TwentyFourPointGameTestGetMyCards",
"TwentyFourPointGameTestAnswer",
"TwentyFourPointGameTestEvaluateExpression",
"TwentyFourPointGameTest"
] | class TwentyFourPointGame:
def __init__(self) -> None:
self.nums = []
| [
"self.nums"
] |
ClassEval_90 | class URLHandler:
"""
The class supports to handle URLs, including extracting the scheme, host, path, query parameters, and fragment.
"""
def __init__(self, url):
"""
Initialize URLHandler's URL
"""
self.url = url
def get_scheme(self):
"""
get the sc... | 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... | 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 !=... | [] | """
The class supports to handle URLs, including extracting the scheme, host, path, query parameters, and fragment.
"""
| [
{
"method_name": "get_scheme",
"method_description": "def get_scheme(self):\n \"\"\"\n get the scheme of the URL\n :return: string, If successful, return the scheme of the URL\n >>> urlhandler = URLHandler(\"https://www.baidu.com/s?wd=aaa&rsv_spt=1#page\")\n >>> urlhandler... | URLHandler | [
"URLHandlerTestGetScheme",
"URLHandlerTestGetHost",
"URLHandlerTestGetPath",
"URLHandlerTestGetQueryParams",
"URLHandlerTestGetFragment",
"URLHandlerTest"
] | class URLHandler:
def __init__(self, url):
"""
Initialize URLHandler's URL
"""
self.url = url
| [
"self.url"
] |
ClassEval_91 | import urllib.parse
class UrlPath:
"""
The class is a utility for encapsulating and manipulating the path component of a URL, including adding nodes, parsing path strings, and building path strings with optional encoding.
"""
def __init__(self):
"""
Initializes the UrlPath object with... | 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')
... | 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... | [
"import urllib.parse"
] | """
The class is a utility for encapsulating and manipulating the path component of a URL, including adding nodes, parsing path strings, and building path strings with optional encoding.
"""
| [
{
"method_name": "add",
"method_description": "def add(self, segment):\n \"\"\"\n Adds a segment to the list of segments in the UrlPath.\n :param segment: str, the segment to add.\n >>> url_path = UrlPath()\n >>> url_path.add('foo')\n >>> url_path.add('bar')\n\n ... | UrlPath | [
"UrlPathTestAdd",
"UrlPathTestParse",
"UrlPathTestFixPath",
"UrlPathTest"
] | class UrlPath:
def __init__(self):
"""
Initializes the UrlPath object with an empty list of segments and a flag indicating the presence of an end tag.
"""
self.segments = []
self.with_end_tag = False
| [
"self.segments",
"self.with_end_tag"
] |
ClassEval_92 | class UserLoginDB:
"""
This is a database management class for user login verification, providing functions for inserting user information, searching user information, deleting user information, and validating user login.
"""
def __init__(self, db_name):
"""
Initializes the UserLoginDB ... | import unittest
import os
from tempfile import gettempdir
class UserLoginDBTestInsertUser(unittest.TestCase):
def setUp(self):
self.db_path = os.path.join(gettempdir(), 'test_db.db')
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
create_table_query = """
... | import sqlite3
class UserLoginDB:
def __init__(self, db_name):
self.connection = sqlite3.connect(db_name)
self.cursor = self.connection.cursor()
def insert_user(self, username, password):
self.cursor.execute('''
INSERT INTO users (username, password)
VALUES (?,... | [
"import sqlite3"
] | """
This is a database management class for user login verification, providing functions for inserting user information, searching user information, deleting user information, and validating user login.
"""
| [
{
"method_name": "insert_user",
"method_description": "def insert_user(self, username, password):\n \"\"\"\n Inserts a new user into the \"users\" table.\n :param username: str, the username of the user.\n :param password: str, the password of the user.\n :return: None\n ... | UserLoginDB | [
"UserLoginDBTestInsertUser",
"UserLoginDBTestSearchUserByUsername",
"UserLoginDBTestDeleteUserByUsername",
"UserLoginDBTestValidateUserLogin",
"UserLoginDBTest"
] | class UserLoginDB:
def __init__(self, db_name):
"""
Initializes the UserLoginDB object with the specified database name.
:param db_name: str, the name of the SQLite database.
"""
self.connection = sqlite3.connect(db_name)
self.cursor = self.connection.cursor()
| [
"self.connection",
"self.cursor"
] |
ClassEval_93 | import numpy as np
from gensim import matutils
from numpy import dot, array
class VectorUtil:
"""
The class provides vector operations, including calculating similarity, cosine similarities, average similarity, and IDF weights.
"""
@staticmethod
def similarity(vector_1, vector_2):
"""
... | 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... | 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... | [
"import numpy as np",
"from gensim import matutils",
"from numpy import dot, array"
] | """
The class provides vector operations, including calculating similarity, cosine similarities, average similarity, and IDF weights.
"""
| [
{
"method_name": "similarity",
"method_description": "def similarity(vector_1, vector_2):\n \"\"\"\n Compute the cosine similarity between one vector and another vector.\n :param vector_1: numpy.ndarray, Vector from which similarities are to be computed, expected shape (dim,).\n ... | VectorUtil | [
"VectorUtilTestSimilarity",
"VectorUtilTestCosineSimilarities",
"VectorUtilTestNSimilarity",
"VectorUtilTestComputeIdfWeightDict",
"VectorUtilTest"
] | class VectorUtil:
| [] |
ClassEval_94 | class VendingMachine:
"""
This is a class to simulate a vending machine, including adding products, inserting coins, purchasing products, viewing balance, replenishing product inventory, and displaying product information.
"""
def __init__(self):
"""
Initializes the vending machine's in... | 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):
... | 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)... | [] | """
This is a class to simulate a vending machine, including adding products, inserting coins, purchasing products, viewing balance, replenishing product inventory, and displaying product information.
"""
| [
{
"method_name": "add_item",
"method_description": "def add_item(self, item_name, price, quantity):\n \"\"\"\n Adds a product to the vending machine's inventory.\n :param item_name: The name of the product to be added, str.\n :param price: The price of the product to be added, fl... | VendingMachine | [
"VendingMachineTestAddItem",
"VendingMachineTestInsertCoin",
"VendingMachineTestPurchaseItem",
"VendingMachineTestRestockItem",
"VendingMachineTestDisplayItems",
"VendingMachineTestMain"
] | class VendingMachine:
def __init__(self):
"""
Initializes the vending machine's inventory and balance.
"""
self.inventory = {}
self.balance = 0
| [
"self.balance",
"self.inventory"
] |
ClassEval_95 | class Warehouse:
"""
The class manages inventory and orders, including adding products, updating product quantities, retrieving product quantities, creating orders, changing order statuses, and tracking orders.
"""
def __init__(self):
"""
Initialize two fields.
self.inventory is... | 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... | 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}
... | [] | """
The class manages inventory and orders, including adding products, updating product quantities, retrieving product quantities, creating orders, changing order statuses, and tracking orders.
"""
| [
{
"method_name": "add_product",
"method_description": "def add_product(self, product_id, name, quantity):\n \"\"\"\n Add product to inventory and plus the quantity if it has existed in inventory.\n Or just add new product to dict otherwise.\n :param product_id: int\n :para... | Warehouse | [
"WarehouseTestAddProduct",
"WarehouseTestUpdateProductQuantity",
"WarehouseTestGetProductQuantity",
"WarehouseTestCreateOrder",
"WarehouseTestChangeOrderStatus",
"WarehouseTestTrackOrder",
"WarehouseTestMain"
] | class Warehouse:
def __init__(self):
"""
Initialize two fields.
self.inventory is a dict that stores the products.
self.inventory = {Product ID: Product}
self.orders is a dict that stores the products in a order.
self.orders = {Order ID: Order}
"""
se... | [
"self.inventory",
"self.orders"
] |
ClassEval_96 | class WeatherSystem:
"""
This is a class representing a weather system that provides functionality to query weather information for a specific city and convert temperature units between Celsius and Fahrenheit.
"""
def __init__(self, city) -> None:
"""
Initialize the weather system with ... | 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'
... | 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:... | [] | """
This is a class representing a weather system that provides functionality to query weather information for a specific city and convert temperature units between Celsius and Fahrenheit.
"""
| [
{
"method_name": "query",
"method_description": "def query(self, weather_list, tmp_units = 'celsius'):\n \"\"\"\n Query the weather system for the weather and temperature of the city,and convert the temperature units based on the input parameter.\n :param weather_list: a dictionary of w... | WeatherSystem | [
"WeatherSystemTestQuery",
"WeatherSystemTestSetCity",
"WeatherSystemTestCelsiusToFahrenheit",
"WeatherSystemTestFahrenheitToCelsius",
"WeatherSystemTestMain"
] | class WeatherSystem:
def __init__(self, city) -> None:
"""
Initialize the weather system with a city name.
"""
self.temperature = None
self.weather = None
self.city = city
self.weather_list = {}
| [
"self.city",
"self.temperature",
"self.weather",
"self.weather_list"
] |
ClassEval_97 | class Words2Numbers:
"""
The class provides a text-to-number conversion utility, allowing conversion of written numbers (in words) to their numerical representation.
"""
def __init__(self):
"""
Initialize the word lists and dictionaries required for conversion
"""
self.... | 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"), ... | 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"... | [] | """
The class provides a text-to-number conversion utility, allowing conversion of written numbers (in words) to their numerical representation.
"""
| [
{
"method_name": "text2int",
"method_description": "def text2int(self, textnum):\n \"\"\"\n Convert the word string to the corresponding integer string\n :param textnum: string, the word string to be converted\n :return: string, the final converted integer string\n >>> w2n... | Words2Numbers | [
"Words2NumbersTestText2Int",
"Words2NumbersTestIsValidInput",
" Words2NumbersTestMain"
] | class Words2Numbers:
def __init__(self):
"""
Initialize the word lists and dictionaries required for conversion
"""
self.numwords = {}
self.units = [
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
"nine", "ten", "eleven", "twe... | [
"self.numwords",
"self.ordinal_endings",
"self.ordinal_words",
"self.scales",
"self.tens",
"self.units"
] |
ClassEval_98 | import xml.etree.ElementTree as ET
class XMLProcessor:
"""
This is a class as XML files handler, including reading, writing, processing as well as finding elements in a XML file.
"""
def __init__(self, file_name):
"""
Initialize the XMLProcessor object with the given file name.
... | import unittest
import os
class XMLProcessorTestReadXml(unittest.TestCase):
def test_read_xml_1(self):
with open('test.xml', 'w') as f:
f.write('<root>\n <item>apple</item>\n <item>banana</item>\n <item>orange</item>\n</root>')
self.xml_file = 'test.xml'
self.processor... | import xml.etree.ElementTree as ET
class XMLProcessor:
def __init__(self, file_name):
self.file_name = file_name
self.root = None
def read_xml(self):
try:
tree = ET.parse(self.file_name)
self.root = tree.getroot()
return self.root
except:
... | [
"import xml.etree.ElementTree as ET"
] | """
This is a class as XML files handler, including reading, writing, processing as well as finding elements in a XML file.
"""
| [
{
"method_name": "read_xml",
"method_description": "def read_xml(self):\n \"\"\"\n Reads the XML file and returns the root element.\n :return: Element, the root element of the XML file.\n >>> xml_processor = XMLProcessor('test.xml')\n >>> root_element = xml_processor.read_... | XMLProcessor | [
"XMLProcessorTestReadXml",
"XMLProcessorTestWriteXml",
"XMLProcessorTestProcessXmlData",
"XMLProcessorTestFindElement",
"XMLProcessorTest"
] | class XMLProcessor:
def __init__(self, file_name):
"""
Initialize the XMLProcessor object with the given file name.
:param file_name:string, the name of the XML file to be processed.
"""
self.file_name = file_name
self.root = None
| [
"self.file_name",
"self.root"
] |
ClassEval_99 | import zipfile
class ZipFileProcessor:
"""
This is a compressed file processing class that provides the ability to read and decompress compressed files
"""
def __init__(self, file_name):
"""
Initialize file name
:param file_name:string
"""
self.file_name = file... | import unittest
import os
class ZipFileProcessorTestReadZipFile(unittest.TestCase):
def test_read_zip_file_1(self):
test_folder = 'test_folder'
os.makedirs(test_folder, exist_ok=True)
example_file_path = os.path.join(test_folder, 'example.txt')
with open(example_file_path, 'w') as ... | import zipfile
class ZipFileProcessor:
def __init__(self, file_name):
self.file_name = file_name
def read_zip_file(self):
try:
zip_file = zipfile.ZipFile(self.file_name, 'r')
return zip_file
except:
return None
def extract_all(self, output_path... | [
"import zipfile"
] | """
This is a compressed file processing class that provides the ability to read and decompress compressed files
"""
| [
{
"method_name": "read_zip_file",
"method_description": "def read_zip_file(self):\n \"\"\"\n Get open file object\n :return:If successful, returns the open file object; otherwise, returns None\n >>> zfp = ZipFileProcessor(\"aaa.zip\")\n >>> file = zfp.read_zip_file()\n ... | ZipFileProcessor | [
"ZipFileProcessorTestReadZipFile",
"ZipFileProcessorTestExtractAll",
"ZipFileProcessorTestExtractFile",
"ZipFileProcessorTestCreateZipFile",
"ZipFileProcessorTest"
] | class ZipFileProcessor:
def __init__(self, file_name):
"""
Initialize file name
:param file_name:string
"""
self.file_name = file_name
| [
"self.file_name"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.