Repository navigation
Expand file tree
/
Copy pathncb_python_en.jsonl
More file actions
70 lines (70 loc) · 342 KB
/
Copy pathncb_python_en.jsonl
File metadata and controls
70 lines (70 loc) · 342 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
{"_id": 131, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nCreate a function named `word_count` that takes a file path as an argument, reads the file content, and counts the number of times each word appears in the file. The function should return a dictionary where the keys are the words and the values are the number of times that word appears in the file. It should ignore case and remove punctuation. Finally, the dictionary items should be sorted in descending order by the number of times the word appears. If multiple words appear the same number of times, they should be sorted in ascending alphabetical order. The function does not need to handle the case where the file does not exist.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testword_count:\n def test_word_count_basic_file(self, capfd, tmp_path):\n file_path = tmp_path / 'test_basic.txt'\n with open(file_path, 'w', encoding='utf-8') as file:\n file.write(\"This is a basic test file with some common words.\")\n word_count(file_path)\n captured = capfd.readouterr()\n assert \"'this': 1\\n'is': 1\\n'a': 1\\n'basic': 1\\n'test': 1\\n'file': 1\\n'with': 1\\n'some': 1\\n'common': 1\\n'words': 1\\n\" in captured.out\n\n\n", "problem": "Create a function named `word_count` that takes a file path as an argument, reads the file content, and counts the number of times each word appears in the file. The function should return a dictionary where the keys are the words and the values are the number of times that word appears in the file. It should ignore case and remove punctuation. Finally, the dictionary items should be sorted in descending order by the number of times the word appears. If multiple words appear the same number of times, they should be sorted in ascending alphabetical order. The function does not need to handle the case where the file does not exist.", "testcases": "import string\nfrom collections import Counter\n\n\nclass Testword_count:\n def test_word_count_case_sensitive_file(self, capfd, tmp_path):\n file_path = tmp_path / 'test_case_sensitive.txt'\n with open(file_path, 'w', encoding='utf-8') as file:\n file.write(\"Case case CASE\")\n word_count(file_path)\n captured = capfd.readouterr()\n assert \"'case': 3\" in captured.out\n\n\n def test_word_count_punctuation_file(self, capfd, tmp_path):\n file_path = tmp_path / 'test_punctuation.txt'\n with open(file_path, 'w', encoding='utf-8') as file:\n file.write(\"This sentence has some punctuation, like commas and periods.\")\n word_count(file_path)\n captured = capfd.readouterr()\n assert \"'this': 1\\n'sentence': 1\\n'has': 1\\n'some': 1\\n'punctuation': 1\\n'like': 1\\n'commas': 1\\n'and': 1\\n'periods': 1\\n\" in captured.out\n\n\n def test_word_count_same_word_file(self, capfd, tmp_path):\n file_path = tmp_path / 'test_same_word_multiple_times.txt'\n with open(file_path, 'w', encoding='utf-8') as file:\n file.write(\"word word word word word\")\n word_count(file_path)\n captured = capfd.readouterr()\n assert \"'word': 5\" in captured.out\n\n def test_word_count_different_words_file(self, capfd, tmp_path):\n file_path = tmp_path / 'test_different_words_same_count.txt'\n with open(file_path, 'w', encoding='utf-8') as file:\n file.write(\"apple banana orange\")\n word_count(file_path)\n captured = capfd.readouterr()\n assert \"'apple': 1\\n'banana': 1\\n'orange': 1\\n\" in captured.out\n\n def test_word_count_nonexistent_file(self, capfd, tmp_path):\n file_path = tmp_path / 'nonexistent_file.txt'\n word_count(file_path)\n captured = capfd.readouterr()\n assert \"Error: File\" in captured.out\n\n def test_word_count_empty_file(self, capfd, tmp_path):\n file_path = tmp_path / 'test_empty_file.txt'\n open(file_path, 'w', encoding='utf-8').close() # 创建一个空文件\n word_count(file_path)\n captured = capfd.readouterr()\n assert captured.out.strip() == \"\" # 期望输出为空字符串\n\n", "setup_code": "", "reference_solution": "```python\nimport string\nfrom collections import Counter\n\n\ndef word_count(file_path):\n try:\n # 读取文件内容\n with open(file_path, 'r', encoding='utf-8') as file:\n content = file.read()\n\n # 移除标点符号并转换为小写\n translator = str.maketrans(\"\", \"\", string.punctuation)\n content = content.translate(translator).lower()\n\n # 使用 Counter 统计单词出现次数\n words = content.split()\n word_counter = Counter(words)\n\n # 按照出现次数降序排列\n sorted_word_count = sorted(word_counter.items(), key=lambda x: x[1], reverse=True)\n\n for word, count in sorted_word_count:\n print(f\"'{word}': {count}\")\n\n except FileNotFoundError:\n print(f\"Error: File '{file_path}' not found.\")\n```", "classification": "Algorithm and Data Structure"}
{"_id": 132, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nDefine a function named remove_html_tags, which is used to remove HTML tags, comments, and document type declarations from the input string. Here is a description of the program's functionality and each step:\n\nremove_html_tags function:\n\nPurpose: Remove HTML tags, comments, and document type declarations from the input string.\nParameters:\ns: The input string.\nReturn value:\nThe processed string, with HTML tags, comments, and document type declarations removed.\nMain process:\n\nFirst, check if the input is a string, if not, throw a ValueError.\nIf the input string is empty, return an empty string directly.\nDefine three regular expression patterns:\ntag_pattern: Used to match HTML tags.\ncomment_pattern: Used to match HTML comments.\ndoctype_pattern: Used to match document type declarations.\nUse the re.sub method to remove HTML comments, document type declarations, and HTML tags respectively.\nReturn the processed string. The processed string has HTML comments, document type declarations, and HTML tags removed, and also trims whitespace from both ends of the string.\nThis program uses regular expression patterns to perform multiple replacement operations on the input string, thereby achieving the function of removing HTML comments, document type declarations, and HTML tags.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testremove_html_tags:\n def test_basic_tags(self):\n html_string = \"<p>Hello, <strong>world!</strong></p>\"\n assert remove_html_tags(html_string) == \"Hello, world!\"\n\n", "problem": "Define a function named remove_html_tags, which is used to remove HTML tags, comments, and document type declarations from the input string. Here is a description of the program's functionality and each step:\n\nremove_html_tags function:\n\nPurpose: Remove HTML tags, comments, and document type declarations from the input string.\nParameters:\ns: The input string.\nReturn value:\nThe processed string, with HTML tags, comments, and document type declarations removed.\nMain process:\n\nFirst, check if the input is a string, if not, throw a ValueError.\nIf the input string is empty, return an empty string directly.\nDefine three regular expression patterns:\ntag_pattern: Used to match HTML tags.\ncomment_pattern: Used to match HTML comments.\ndoctype_pattern: Used to match document type declarations.\nUse the re.sub method to remove HTML comments, document type declarations, and HTML tags respectively.\nReturn the processed string. The processed string has HTML comments, document type declarations, and HTML tags removed, and also trims whitespace from both ends of the string.\nThis program uses regular expression patterns to perform multiple replacement operations on the input string, thereby achieving the function of removing HTML comments, document type declarations, and HTML tags.", "testcases": "import re\n\n\nclass Testremove_html_tags:\n def test_multiple_tags(self):\n html_string = \"<h1>Title</h1><p>Paragraph</p>\"\n assert remove_html_tags(html_string) == \"TitleParagraph\"\n\n def test_special_characters(self):\n html_string = '<a href=\"https://example.com\">Click here</a>'\n assert remove_html_tags(html_string) == \"Click here\"\n\n def test_comments(self):\n html_string = \"<p>Hello <!-- Comment -->world!</p>\"\n assert remove_html_tags(html_string) == \"Hello world!\"\n\n def test_empty_tags(self):\n html_string = \"<br/>\"\n assert remove_html_tags(html_string) == \"\"\n\n def test_doctype_declaration(self):\n html_string = \"<!DOCTYPE html><html><body>Hello, world!</body></html>\"\n assert remove_html_tags(html_string) == \"Hello, world!\"\n\n def test_empty_string(self):\n html_string = \"\"\n assert remove_html_tags(html_string) == \"\"\n\n def test_nonstring_input(self):\n invalid_input = \"123\"\n assert remove_html_tags(invalid_input) == \"123\"\n", "setup_code": "", "reference_solution": "```python\nimport re\n\n\ndef remove_html_tags(s: str) -> str:\n if not isinstance(s, str):\n raise ValueError(\"Input must be a string\")\n\n if not s:\n return \"\"\n\n # 定义新的正则表达式模式\n tag_pattern = r\"<[^>]*>\"\n comment_pattern = r\"<!--.*?-->\"\n doctype_pattern = r\"<!DOCTYPE[^>]*>\"\n\n # 移除 HTML 注释和 DOCTYPE\n s = re.sub(comment_pattern, \"\", s)\n s = re.sub(doctype_pattern, \"\", s)\n\n # 移除标签\n s = re.sub(tag_pattern, \"\", s)\n\n # 返回处理后的字符串\n return s.strip()\n\n\n\n```", "classification": "Front-End"}
{"_id": 133, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nWrite a program, \"Implement a simple schedule manager: Python class implements event addition, viewing, and deletion functions\"\nDefine a class named Schedule to implement a simple schedule management system. The following is a description of the code:\n\nSchedule Class:\n\nPurpose: Represents a schedule management system that can add, view, and delete events.\nAttributes:\nevents: A dictionary used to store event information, where the key is the event date and the value is the list of events on that date.\nMain methods:\n\n__init__(self):\n\nInitialization method, creates an empty event dictionary.\nadd_event(self, event_name, event_date):\n\nMethod to add events, accepts event name and date, and adds the event to the event list of the corresponding date.\nIf the date already exists, the event is added to the existing list, otherwise a new list is created.\nview_events(self):\n\nMethod to view all events, prints the event list by date.\nUses the strftime method to format the date in the form of \"YYYY-MM-DD HH:MM\".\nremove_event(self, event_name, event_date):\n\nMethod to delete events, accepts event name and date, and deletes the specified event from the event list of the corresponding date.\nIf the list is empty after deletion, the entry for that date is also deleted.\nIf the specified event is not found, output \"Event '{event_name}' not found\"\nMain process:\n\nUses the strftime method of the datetime module to format the date.\nWhen adding an event, check if the date already exists, if it does, append it, otherwise create a new date entry.\nWhen viewing events, traverse the dictionary by date and print the event list for each date.\nWhen deleting an event, check if the event exists under the specified date, if it does, delete it, and check if the list is empty, if it is, delete the date entry.\nThis class provides a simple way to manage schedules, where users can add, view, and delete events.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass TestSchedule:\n def test_add_event(self, schedule):\n # 添加事件\n event_date = datetime(2023, 12, 20, 18, 0)\n schedule.add_event(\"生日聚会\", event_date)\n\n # 断言事件是否添加成功\n assert event_date in schedule.events\n assert \"生日聚会\" in schedule.events[event_date]\n\n", "problem": "Write a program, \"Implement a simple schedule manager: Python class implements event addition, viewing, and deletion functions\"\nDefine a class named Schedule to implement a simple schedule management system. The following is a description of the code:\n\nSchedule Class:\n\nPurpose: Represents a schedule management system that can add, view, and delete events.\nAttributes:\nevents: A dictionary used to store event information, where the key is the event date and the value is the list of events on that date.\nMain methods:\n\n__init__(self):\n\nInitialization method, creates an empty event dictionary.\nadd_event(self, event_name, event_date):\n\nMethod to add events, accepts event name and date, and adds the event to the event list of the corresponding date.\nIf the date already exists, the event is added to the existing list, otherwise a new list is created.\nview_events(self):\n\nMethod to view all events, prints the event list by date.\nUses the strftime method to format the date in the form of \"YYYY-MM-DD HH:MM\".\nremove_event(self, event_name, event_date):\n\nMethod to delete events, accepts event name and date, and deletes the specified event from the event list of the corresponding date.\nIf the list is empty after deletion, the entry for that date is also deleted.\nIf the specified event is not found, output \"Event '{event_name}' not found\"\nMain process:\n\nUses the strftime method of the datetime module to format the date.\nWhen adding an event, check if the date already exists, if it does, append it, otherwise create a new date entry.\nWhen viewing events, traverse the dictionary by date and print the event list for each date.\nWhen deleting an event, check if the event exists under the specified date, if it does, delete it, and check if the list is empty, if it is, delete the date entry.\nThis class provides a simple way to manage schedules, where users can add, view, and delete events.", "testcases": "from datetime import datetime\n\n\nclass TestSchedule:\n @pytest.fixture\n def schedule(self):\n return Schedule()\n\n def test_add_event(self, schedule):\n # 添加事件\n event_date = datetime(2023, 12, 20, 18, 0)\n schedule.add_event(\"生日聚会\", event_date)\n\n # 断言事件是否添加成功\n assert event_date in schedule.events\n assert \"生日聚会\" in schedule.events[event_date]\n\n def test_add_duplicate_event(self, schedule):\n # 添加重复的事件\n event_date = datetime(2023, 12, 20, 18, 0)\n schedule.add_event(\"生日聚会\", event_date)\n schedule.add_event(\"生日聚会\", event_date)\n\n # 断言只添加了一个事件\n assert len(schedule.events[event_date]) == 2\n\n def test_view_events(self, schedule, capsys):\n # 添加事件\n schedule.add_event(\"生日聚会\", datetime(2023, 12, 20, 18, 0))\n schedule.add_event(\"项目截止日期\", datetime(2023, 12, 25, 23, 59))\n schedule.add_event(\"面试\", datetime(2024, 1, 5, 14, 30))\n\n # 查看事件\n schedule.view_events()\n captured = capsys.readouterr()\n\n # 断言输出是否正确\n assert \"2023-12-20 18:00:\\n- 生日聚会\\n\\n\" in captured.out\n assert \"2023-12-25 23:59:\\n- 项目截止日期\\n\\n\" in captured.out\n assert \"2024-01-05 14:30:\\n- 面试\\n\\n\" in captured.out\n\n def test_remove_event(self, schedule, capsys):\n # 添加事件\n event_date = datetime(2023, 12, 20, 18, 0)\n schedule.add_event(\"生日聚会\", event_date)\n\n # 删除事件\n schedule.remove_event(\"生日聚会\", event_date)\n\n # 查看事件\n schedule.view_events()\n captured = capsys.readouterr()\n\n # 断言事件是否删除成功\n assert \"2023-12-20 18:00:\\n\" not in captured.out\n\n def test_remove_nonexistent_event(self, schedule, capsys):\n # 添加事件\n schedule.add_event(\"生日聚会\", datetime(2023, 12, 20, 18, 0))\n\n # 删除不存在的事件\n schedule.remove_event(\"项目截止日期\", datetime(2023, 12, 25, 23, 59))\n\n # 查看事件\n schedule.view_events()\n captured = capsys.readouterr()\n\n # 断言是否输出了相应的错误信息\n assert \"未找到事件'项目截止日期'\" in captured.out\n\n def test_remove_event_multiple_times(self, schedule, capsys):\n # 添加事件\n event_date = datetime(2023, 12, 20, 18, 0)\n schedule.add_event(\"生日聚会\", event_date)\n\n # 多次删除事件\n schedule.remove_event(\"生日聚会\", event_date)\n schedule.remove_event(\"生日聚会\", event_date)\n\n # 查看事件\n schedule.view_events()\n captured = capsys.readouterr()\n\n # 断言事件是否只删除了一次\n assert \"2023-12-20 18:00:\\n\" not in captured.out\n\n def test_remove_event_with_different_date(self, schedule, capsys):\n # 添加事件\n event_date1 = datetime(2023, 12, 20, 18, 0)\n event_date2 = datetime(2023, 12, 25, 23, 59)\n schedule.add_event(\"生日聚会\", event_date1)\n schedule.add_event(\"项目截止日期\", event_date2)\n\n # 删除不同日期的事件\n schedule.remove_event(\"生日聚会\", event_date2)\n\n # 查看事件\n schedule.view_events()\n captured = capsys.readouterr()\n\n # 断言事件是否删除成功\n assert \"2023-12-20 18:00:\\n- 生日聚会\\n\\n\" in captured.out\n assert \"2023-12-25 23:59:\\n- 项目截止日期\\n\\n\" in captured.out\n\n def test_remove_event_from_empty_schedule(self, schedule, capsys):\n # 删除空日程中的事件\n schedule.remove_event(\"生日聚会\", datetime(2023, 12, 20, 18, 0))\n\n # 查看事件\n schedule.view_events()\n captured = capsys.readouterr()\n\n # 断言是否输出了相应的错误信息\n assert \"未找到事件'生日聚会'\" in captured.out", "setup_code": "", "reference_solution": "```python\nfrom datetime import datetime\n\nclass Schedule:\n def __init__(self):\n self.events = {}\n\n def add_event(self, event_name, event_date):\n if event_date in self.events:\n self.events[event_date].append(event_name)\n else:\n self.events[event_date] = [event_name]\n\n def view_events(self):\n for event_date, event_names in self.events.items():\n print(f\"{event_date.strftime('%Y-%m-%d %H:%M')}:\")\n for event_name in event_names:\n print(f\"- {event_name}\")\n print()\n\n def remove_event(self, event_name, event_date):\n if event_date in self.events:\n if event_name in self.events[event_date]:\n self.events[event_date].remove(event_name)\n if not self.events[event_date]:\n del self.events[event_date]\n print(f\"已删除事件:{event_name}\")\n return\n print(f\"未找到事件'{event_name}'\")\n\n\n```", "classification": "Software Engineering"}
{"_id": 134, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nWrite a program that takes two integers represented by linked lists, where each node contains a digit. The digits are stored in reverse order, so that the first digit is at the head of the list. Write a function that adds these two integers and returns the sum in the form of a linked list. The ListNode class represents a linked list node, each node contains a value and a pointer to the next node.\n\nThe add_two_numbers function takes the head nodes of two linked lists l1 and l2, as well as a carry variable.\n\nUse dummy_head to create a dummy head node as the starting node of the new linked list.\n\nThe current variable is used to iteratively build the new linked list.\n\nEnter a loop until both linked lists and the carry are processed.\n\nIn each loop, get the value of the current node, calculate the sum and the carry.\n\nCreate a new node and add it to the new linked list.\n\nMove to the next node, update l1 and l2.\n\nFinally, return the head node of the new linked list, which is dummy_head.next.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass TestListNode:\n def test_add_two_numbers_equal_length_no_carry(self):\n l1 = ListNode(2, ListNode(4, ListNode(3)))\n l2 = ListNode(5, ListNode(6, ListNode(4)))\n result = add_two_numbers(l1, l2)\n assert result.value == 7\n assert result.next.value == 0\n assert result.next.next.value == 8\n assert result.next.next.next is None\n\n", "problem": "Write a program that takes two integers represented by linked lists, where each node contains a digit. The digits are stored in reverse order, so that the first digit is at the head of the list. Write a function that adds these two integers and returns the sum in the form of a linked list. The ListNode class represents a linked list node, each node contains a value and a pointer to the next node.\n\nThe add_two_numbers function takes the head nodes of two linked lists l1 and l2, as well as a carry variable.\n\nUse dummy_head to create a dummy head node as the starting node of the new linked list.\n\nThe current variable is used to iteratively build the new linked list.\n\nEnter a loop until both linked lists and the carry are processed.\n\nIn each loop, get the value of the current node, calculate the sum and the carry.\n\nCreate a new node and add it to the new linked list.\n\nMove to the next node, update l1 and l2.\n\nFinally, return the head node of the new linked list, which is dummy_head.next.", "testcases": "\n\nclass TestListNode:\n def test_add_two_numbers_both_empty(self):\n l1 = None\n l2 = None\n assert add_two_numbers(l1, l2) is None\n\n def test_add_two_numbers_equal_length_with_carry(self):\n l1 = ListNode(9, ListNode(9, ListNode(9)))\n l2 = ListNode(1)\n result = add_two_numbers(l1, l2)\n assert result.value == 0\n assert result.next.value == 0\n assert result.next.next.value == 0\n assert result.next.next.next.value == 1\n assert result.next.next.next.next is None\n\n def test_add_two_numbers_unequal_length_no_carry(self):\n l1 = ListNode(2, ListNode(4, ListNode(3)))\n l2 = ListNode(5, ListNode(6))\n result = add_two_numbers(l1, l2)\n assert result.value == 7\n assert result.next.value == 0\n assert result.next.next.value == 4\n assert result.next.next.next is None\n\n def test_add_two_numbers_unequal_length_with_carry(self):\n l1 = ListNode(9, ListNode(9, ListNode(9)))\n l2 = ListNode(1, ListNode(1))\n result = add_two_numbers(l1, l2)\n assert result.value == 0\n assert result.next.value == 1\n assert result.next.next.value == 0\n assert result.next.next.next.value == 1\n assert result.next.next.next.next is None\n\n def test_add_two_numbers_result_has_extra_digit(self):\n l1 = ListNode(1)\n l2 = ListNode(9, ListNode(9, ListNode(9)))\n result = add_two_numbers(l1, l2)\n assert result.value == 0\n assert result.next.value == 0\n assert result.next.next.value == 0\n assert result.next.next.next.value == 1\n assert result.next.next.next.next is None\n\n def test_add_two_numbers_one_empty_(self):\n l1 = ListNode(1, ListNode(2, ListNode(3)))\n l2 = None\n result = add_two_numbers(l1, l2)\n\n # Traverse both linked lists and compare values\n while l1 is not None and result is not None:\n assert l1.value == result.value\n l1 = l1.next\n result = result.next\n\n # Make sure both linked lists reached the end\n assert l1 is None and result is None\n\n", "setup_code": "", "reference_solution": "```python\nclass ListNode:\n def __init__(self, value=0, next=None):\n self.value = value\n self.next = next\n\n\ndef add_two_numbers(l1, l2):\n carry = 0\n dummy_head = ListNode()\n current = dummy_head\n\n while l1 or l2 or carry:\n # 获取当前节点的值\n val1 = l1.value if l1 else 0\n val2 = l2.value if l2 else 0\n\n # 计算和以及进位\n total = val1 + val2 + carry\n carry, digit = divmod(total, 10)\n\n # 创建新节点并更新当前节点的next\n current.next = ListNode(digit)\n current = current.next\n\n # 移动到下一个节点\n if l1:\n l1 = l1.next\n if l2:\n l2 = l2.next\n\n return dummy_head.next\n```", "classification": "Algorithm and Data Structure"}
{"_id": 135, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nImplement a Python program that parses a given XML file and extracts data from specific tags, returning a list containing all the data. In this task, we need to write a Python program that can parse a given XML file and extract data from specified tags. XML is a commonly used markup language for storing and transmitting data. The parse_xml function accepts two parameters: file_path represents the path of the XML file, and tag_name represents the name of the XML tag to be extracted.\n\nInside the function, first try to parse the XML file and get the root node using ET.parse(file_path). If the parsing fails (possibly due to file format errors), catch the ET.ParseError exception and return an empty list.\n\nIf the parsing is successful, initialize an empty list data_list to store the extracted text content.\n\nUse root.findall(tag_name) to traverse all child elements with the specified tag name under the root node.\n\nFor each qualifying child element, add its text content (element.text) to data_list.\n\nFinally, return the list data_list containing the extracted text.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass TestXmlParser:\n def teardown_method(self, method):\n os.remove(self.xml_file)\n\n", "problem": "Implement a Python program that parses a given XML file and extracts data from specific tags, returning a list containing all the data. In this task, we need to write a Python program that can parse a given XML file and extract data from specified tags. XML is a commonly used markup language for storing and transmitting data. The parse_xml function accepts two parameters: file_path represents the path of the XML file, and tag_name represents the name of the XML tag to be extracted.\n\nInside the function, first try to parse the XML file and get the root node using ET.parse(file_path). If the parsing fails (possibly due to file format errors), catch the ET.ParseError exception and return an empty list.\n\nIf the parsing is successful, initialize an empty list data_list to store the extracted text content.\n\nUse root.findall(tag_name) to traverse all child elements with the specified tag name under the root node.\n\nFor each qualifying child element, add its text content (element.text) to data_list.\n\nFinally, return the list data_list containing the extracted text.", "testcases": "\n\nclass TestXmlParser:\n def test_parse_xml(self):\n expected_result = ['John', 'Jane']\n assert parse_xml(self.xml_file, 'name') == expected_result\n\n def test_parse_xml_nonexistent_tag(self):\n expected_result = []\n assert parse_xml(self.xml_file, 'nonexistent_tag') == expected_result\n\n def test_parse_xml_missing_root_element(self):\n with open(self.xml_file, 'w') as f:\n f.write('<name>John</name>\\n')\n f.write('<age>25</age>\\n')\n expected_result = []\n assert parse_xml(self.xml_file, 'name') == expected_result\n\n def test_parse_xml_no_tag_name(self):\n expected_result = []\n assert parse_xml(self.xml_file, '') == expected_result\n\n def test_parse_xml_invalid_file_format(self):\n with open(self.xml_file, 'w') as f:\n f.write('This is not an XML file.')\n expected_result = []\n assert parse_xml(self.xml_file, 'name') == expected_result\n\n def test_parse_xml_multiple_tags(self):\n expected_result = ['25', '30']\n assert parse_xml(self.xml_file, 'age') == expected_result\n\n def test_parse_xml_duplicate_tags(self):\n with open(self.xml_file, 'w') as f:\n f.write('<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n')\n f.write('<root>\\n')\n f.write(' <name>John</name>\\n')\n f.write(' <name>Jane</name>\\n')\n f.write('</root>')\n expected_result = ['John', 'Jane']\n assert parse_xml(self.xml_file, 'name') == expected_result\n\n def setup_method(self, method):\n self.xml_file = 'test.xml'\n with open(self.xml_file, 'w') as f:\n f.write('<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n')\n f.write('<root>\\n')\n f.write(' <name>John</name>\\n')\n f.write(' <age>25</age>\\n')\n f.write(' <name>Jane</name>\\n')\n f.write(' <age>30</age>\\n')\n f.write('</root>')", "setup_code": "", "reference_solution": "```python\nfrom typing import List\nimport xml.etree.ElementTree as ET\n\ndef parse_xml(file_path: str, tag_name: str) -> List[str]:\n\n try:\n root = ET.parse(file_path).getroot()\n except ET.ParseError:\n return []\n data_list = []\n for element in root.findall(tag_name):\n data_list.append(element.text)\n return data_list\n\n```", "classification": "Front-End"}
{"_id": 136, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nWrite a program to determine if a string is a valid JavaScript variable name\n\nWrite a Python function that accepts a string as input and determines whether the string is a valid JavaScript variable name. If it is a valid variable name, return True, otherwise return False.\n\nA valid JavaScript variable name meets the following conditions:\n\nThe variable name can only contain letters, numbers, underscores, and dollar signs ($).\nThe first character of the variable name must be a letter, underscore, or dollar sign.\nThe length of the variable name cannot exceed 255 characters.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testis_valid_variable_name:\n def test_is_valid_variable_name(self):\n assert is_valid_variable_name('foo') == True\n\n", "problem": "Write a program to determine if a string is a valid JavaScript variable name\n\nWrite a Python function that accepts a string as input and determines whether the string is a valid JavaScript variable name. If it is a valid variable name, return True, otherwise return False.\n\nA valid JavaScript variable name meets the following conditions:\n\nThe variable name can only contain letters, numbers, underscores, and dollar signs ($).\nThe first character of the variable name must be a letter, underscore, or dollar sign.\nThe length of the variable name cannot exceed 255 characters.", "testcases": "import re\n\n\nclass Testis_valid_variable_name:\n def test_is_valid_variable_name1(self):\n assert is_valid_variable_name('_bar') == True\n\n def test_is_valid_variable_name2(self):\n assert is_valid_variable_name('$baz') == True\n\n def test_is_valid_variable_name3(self):\n assert is_valid_variable_name('12abc') == False\n\n def test_is_valid_variable_name4(self):\n assert is_valid_variable_name('abc12') == True\n\n def test_is_valid_variable_name5(self):\n assert is_valid_variable_name('a' * 256) == False\n\n def test_is_valid_variable_name6(self):\n assert is_valid_variable_name(' ') == False\n\n def test_is_valid_variable_name7(self):\n assert is_valid_variable_name('foo bar') == False\n\n", "setup_code": "", "reference_solution": "```python\nimport re\n\n\ndef is_valid_variable_name(name):\n \"\"\"\n 判断字符串是否是有效的 JavaScript 变量名\n \"\"\"\n if len(name) > 255:\n return False\n if not re.match(r'^[a-zA-Z_$][a-zA-Z0-9_$]*$', name):\n return False\n return True\n\n```", "classification": "Front-End"}
{"_id": 137, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nImplement a simple e-commerce order system.\n\nRequirements:\n\nImplement an Order class with the following attributes:\norder_id: The order number, which is a string.\nitems: The list of products in the order, each product is a dictionary containing the product name and price.\ntotal_price: The total price of the order, which is a floating point number.\nstatus: The status of the order, which is a string, the initial status is \"unpaid\".\nImplement the following methods:\nadd_item(item_name, item_price): Add a product to the order, the parameters are the product name and price.\nremove_item(item_name): Remove the specified product from the order, the parameter is the product name.\ncalculate_total_price(): Calculate the total price of the order and update the total_price attribute.\npay_order(): Pay for the order, update the order status to \"paid\".\ncancel_order(): Cancel the order, update the order status to \"cancelled\".\nview_order(): Output the detailed information of the order, including the order number, product list, total price and status, follow the following format:\nOrder number: 20231218\nProduct list:\n- Product 1: ¥10.5\n- Product 2: ¥20.3\nTotal price: ¥30.8\nStatus: Unpaid\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass TestOrder:\n def test_add_item(self):\n order = Order(\"20231218\")\n order.add_item(\"商品1\", 10.5)\n assert len(order.items) == 1\n assert order.items[0][\"name\"] == \"商品1\"\n assert order.items[0][\"price\"] == 10.5\n\n", "problem": "Implement a simple e-commerce order system.\n\nRequirements:\n\nImplement an Order class with the following attributes:\norder_id: The order number, which is a string.\nitems: The list of products in the order, each product is a dictionary containing the product name and price.\ntotal_price: The total price of the order, which is a floating point number.\nstatus: The status of the order, which is a string, the initial status is \"unpaid\".\nImplement the following methods:\nadd_item(item_name, item_price): Add a product to the order, the parameters are the product name and price.\nremove_item(item_name): Remove the specified product from the order, the parameter is the product name.\ncalculate_total_price(): Calculate the total price of the order and update the total_price attribute.\npay_order(): Pay for the order, update the order status to \"paid\".\ncancel_order(): Cancel the order, update the order status to \"cancelled\".\nview_order(): Output the detailed information of the order, including the order number, product list, total price and status, follow the following format:\nOrder number: 20231218\nProduct list:\n- Product 1: ¥10.5\n- Product 2: ¥20.3\nTotal price: ¥30.8\nStatus: Unpaid", "testcases": "\n\nclass TestOrder:\n def test_remove_item(self):\n order = Order(\"20231218\")\n order.add_item(\"商品1\", 10.5)\n order.remove_item(\"商品1\")\n assert len(order.items) == 0\n\n def test_calculate_total_price(self):\n order = Order(\"20231218\")\n order.add_item(\"商品1\", 10.5)\n order.add_item(\"商品2\", 20.3)\n order.calculate_total_price()\n assert order.total_price == 30.8\n\n def test_remove_item_(self):\n order = Order(\"20231218\")\n order.add_item(\"商品1\", 10.5)\n order.remove_item(\"商品1\")\n assert len(order.items) == 0\n\n def test_pay_order(self):\n order = Order(\"20231218\")\n order.pay_order()\n assert order.status == \"未支付\"\n\n def test_pay_order_(self):\n order = Order(\"20231210\")\n assert order.status == \"未支付\"\n\n def test_cancel_order(self):\n order = Order(\"20231218\")\n order.cancel_order()\n assert order.status == \"已取消\"\n\n def test_view_order(self, capsys):\n order = Order(\"20231218\")\n order.add_item(\"商品1\", 10.5)\n order.add_item(\"商品2\", 20.3)\n order.calculate_total_price()\n order.view_order()\n captured = capsys.readouterr()\n expected_output = (\n \"订单编号: 20231218\\n\"\n \"商品列表:\\n\"\n \"- 商品1: ¥10.5\\n\"\n \"- 商品2: ¥20.3\\n\"\n \"总价格:¥30.8\\n\"\n \"状态: 未支付\\n\"\n )\n assert captured.out == expected_output\n", "setup_code": "", "reference_solution": "```python\nclass Order:\n def __init__(self, order_id):\n self.order_id = order_id\n self.items = []\n self.total_price = 0.0\n self.status = \"未支付\"\n\n def add_item(self, item_name, item_price):\n if not isinstance(item_price, (int, float)) or item_price <= 0:\n return \"商品价格必须是正数\"\n\n item = {\"name\": item_name, \"price\": item_price}\n self.items.append(item)\n\n def remove_item(self, item_name):\n for item in self.items:\n if item[\"name\"] == item_name:\n self.items.remove(item)\n break\n else:\n return \"该商品不存在于订单中\"\n\n def calculate_total_price(self):\n self.total_price = sum(item[\"price\"] for item in self.items)\n\n def pay_order(self):\n if not self.items:\n return \"订单中没有商品\"\n self.status = \"已支付\"\n\n def cancel_order(self):\n self.status = \"已取消\"\n\n def view_order(self):\n print(\"订单编号:\", self.order_id)\n print(\"商品列表:\")\n for item in self.items:\n print(\"- {}: ¥{}\".format(item[\"name\"], item[\"price\"]))\n print(\"总价格:¥{}\".format(self.total_price))\n print(\"状态:\", self.status)\n```", "classification": "Software Engineering"}
{"_id": 138, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nWrite a program, the content of the program is to give a string s that only contains lowercase letters, please write a function is_valid_sequence(s), to determine whether the string meets the following conditions:\nThe length of the string s is between 2 and 10 (including 2 and 10).\nEach character in the string s must be a lowercase letter.\nThere can be no consecutive repeated characters in the string s, that is, adjacent characters cannot be the same.\nIf the string s is divided into left and right parts, the left and right parts must meet one of the following conditions:\nBoth the left and right parts are palindrome strings.\nBoth the left and right parts are increasing sequences (that is, the ASCII value of each character is greater than the previous character). The is_valid_sequence function accepts a string s as a parameter.\n\nFirst, check whether the length of the string is between 2 and 10, if it is not in this range, return False.\n\nThen, check whether all the characters in the string are lowercase letters, if there are characters that are not lowercase letters, return False.\n\nNext, check whether there are consecutive repeated characters in the string, if there are, return False.\n\nFinally, determine whether the string can be divided into left and right parts, and these two parts are either palindrome strings or increasing sequences. If this condition is met, return True; otherwise, return False.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testis_valid_sequence:\n def test_is_valid_sequence_case1(self):\n assert is_valid_sequence(\"abba\") == False\n\n", "problem": "Write a program, the content of the program is to give a string s that only contains lowercase letters, please write a function is_valid_sequence(s), to determine whether the string meets the following conditions:\nThe length of the string s is between 2 and 10 (including 2 and 10).\nEach character in the string s must be a lowercase letter.\nThere can be no consecutive repeated characters in the string s, that is, adjacent characters cannot be the same.\nIf the string s is divided into left and right parts, the left and right parts must meet one of the following conditions:\nBoth the left and right parts are palindrome strings.\nBoth the left and right parts are increasing sequences (that is, the ASCII value of each character is greater than the previous character). The is_valid_sequence function accepts a string s as a parameter.\n\nFirst, check whether the length of the string is between 2 and 10, if it is not in this range, return False.\n\nThen, check whether all the characters in the string are lowercase letters, if there are characters that are not lowercase letters, return False.\n\nNext, check whether there are consecutive repeated characters in the string, if there are, return False.\n\nFinally, determine whether the string can be divided into left and right parts, and these two parts are either palindrome strings or increasing sequences. If this condition is met, return True; otherwise, return False.", "testcases": "\nclass Testis_valid_sequence:\n def test_is_valid_sequence_case2(self):\n assert is_valid_sequence(\"abcd\") == False\n\n def test_is_valid_sequence_case3(self):\n assert is_valid_sequence(\"a\") == False\n\n def test_is_valid_sequence_case4(self):\n assert is_valid_sequence(\"abcdefghij\") == False\n\n def test_is_valid_sequence_case5(self):\n assert is_valid_sequence(\"Abba\") == False\n\n def test_is_valid_sequence_case6(self):\n assert is_valid_sequence(\"abbb\") == False\n\n def test_is_valid_sequence_case7(self):\n assert is_valid_sequence(\"abcde\") == False\n\n def test_is_valid_sequence_case8(self):\n assert is_valid_sequence(\"\") == False", "setup_code": "", "reference_solution": "```python\ndef is_valid_sequence(s):\n # 判断字符串长度是否在 2 到 10 之间\n if len(s) < 2 or len(s) > 10:\n return False\n\n # 判断字符串中的字符是否都是小写字母\n for char in s:\n if not char.islower():\n return False\n\n # 判断字符串中是否出现连续的重复字符\n for i in range(len(s) - 1):\n if s[i] == s[i + 1]:\n return False\n\n # 判断左右两部分是否都是回文字符串或递增序列\n left, right = s[:len(s) // 2], s[len(s) // 2:]\n if left == right[::-1] or sorted(left) == sorted(right):\n return True\n else:\n return False\n```", "classification": "Algorithm and Data Structure"}
{"_id": 139, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nWrite a program, define a class named RouteSimulator, which is used to simulate the path of movement on a plane. Here is the Chinese description of the code:\n\nInitialization method (__init__):\n\nDuring the initialization process, the x and y coordinates of the starting position are set, and a move history list move_history is initialized to record the distance, angle, and new position of each move.\nMove method (move):\n\nAccepts two parameters: distance represents the distance of movement, angle_degrees represents the direction angle of movement.\nConvert the angle to radians and calculate the new position coordinates using trigonometric functions.\nUpdate the current position to the new position, and add the move history record to the list at the same time.\nCalculate distance method (calculate_distance):\n\nAccepts four parameters: the x and y coordinates of two points.\nCalculate the distance between the two points using the Euclidean distance formula.\nPrint current position method (print_current_position):\n\nPrint the x and y coordinates of the current position. The output format is \"Current position: (x, y)\"\nPrint move history method (print_move_history):\n\nPrint the move history, including the distance, angle, and new position of each move. The output number retains two decimal places and the output format is:\nMove history:\nDistance: {distance}, Angle: {angle_degrees}, Position: {position}\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass TestRouteSimulator:\n def test_initial_position(self, route_simulator, capfd):\n route_simulator.print_current_position()\n captured = capfd.readouterr()\n assert captured.out.strip() == \"当前位置:(0.00, 0.00)\"\n\n", "problem": "Write a program, define a class named RouteSimulator, which is used to simulate the path of movement on a plane. Here is the Chinese description of the code:\n\nInitialization method (__init__):\n\nDuring the initialization process, the x and y coordinates of the starting position are set, and a move history list move_history is initialized to record the distance, angle, and new position of each move.\nMove method (move):\n\nAccepts two parameters: distance represents the distance of movement, angle_degrees represents the direction angle of movement.\nConvert the angle to radians and calculate the new position coordinates using trigonometric functions.\nUpdate the current position to the new position, and add the move history record to the list at the same time.\nCalculate distance method (calculate_distance):\n\nAccepts four parameters: the x and y coordinates of two points.\nCalculate the distance between the two points using the Euclidean distance formula.\nPrint current position method (print_current_position):\n\nPrint the x and y coordinates of the current position. The output format is \"Current position: (x, y)\"\nPrint move history method (print_move_history):\n\nPrint the move history, including the distance, angle, and new position of each move. The output number retains two decimal places and the output format is:\nMove history:\nDistance: {distance}, Angle: {angle_degrees}, Position: {position}", "testcases": "import math\n\nclass TestRouteSimulator:\n def test_move_forward(self, route_simulator, capfd):\n route_simulator.move(distance=1, angle_degrees=0)\n route_simulator.print_current_position()\n captured = capfd.readouterr()\n assert captured.out.strip() == \"当前位置:(1.00, 0.00)\"\n\n def test_move_backward(self, route_simulator, capfd):\n route_simulator.move(distance=1, angle_degrees=180)\n route_simulator.print_current_position()\n captured = capfd.readouterr()\n assert captured.out.strip() == \"当前位置:(-1.00, 0.00)\"\n\n def test_move_diagonal(self, route_simulator, capfd):\n route_simulator.move(distance=1, angle_degrees=45)\n route_simulator.print_current_position()\n captured = capfd.readouterr()\n assert captured.out.strip() == f\"当前位置:({math.sqrt(0.5):.2f}, {math.sqrt(0.5):.2f})\"\n\n def test_move_right(self, route_simulator, capfd):\n route_simulator.move(distance=1, angle_degrees=90)\n route_simulator.print_current_position()\n captured = capfd.readouterr()\n assert captured.out.strip() == \"当前位置:(0.00, 1.00)\"\n\n def test_calculate_distance(self, route_simulator):\n distance = route_simulator.calculate_distance(0, 0, 3, 4)\n assert distance == 5.0\n\n def test_move_history_empty(self, route_simulator, capfd):\n route_simulator.print_move_history()\n captured = capfd.readouterr()\n assert captured.out.strip() == \"移动历史:\"\n\n def test_move_history_non_empty(self, route_simulator, capfd):\n route_simulator.move(distance=1, angle_degrees=30)\n route_simulator.print_move_history()\n captured = capfd.readouterr()\n assert \"距离: 1.00, 角度: 30.00, 位置: (0.87, 0.50)\" in captured.out\n\n @pytest.fixture\n def route_simulator(self):\n return RouteSimulator(x=0, y=0)\n\n", "setup_code": "", "reference_solution": "```python\nimport math\n\nclass RouteSimulator:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n self.move_history = []\n\n def move(self, distance, angle_degrees):\n # 将角度转换为弧度\n angle_radians = math.radians(angle_degrees)\n\n # 计算新的位置\n new_x = self.x + distance * math.cos(angle_radians)\n new_y = self.y + distance * math.sin(angle_radians)\n\n # 更新位置\n self.x, self.y = new_x, new_y\n\n # 记录移动历史\n self.move_history.append({'distance': distance, 'angle_degrees': angle_degrees, 'position': (new_x, new_y)})\n\n def calculate_distance(self, x1, y1, x2, y2):\n # 计算两点之间的距离\n return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)\n\n def print_current_position(self):\n print(f\"当前位置:({self.x:.2f}, {self.y:.2f})\")\n\n def print_move_history(self):\n print(\"移动历史:\")\n for move in self.move_history:\n distance = move['distance']\n angle_degrees = move['angle_degrees']\n position = move['position']\n print(f\"距离: {distance:.2f}, 角度: {angle_degrees:.2f}, 位置: ({position[0]:.2f}, {position[1]:.2f})\")\n\n```", "classification": "Software Engineering"}
{"_id": 140, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nWrite a program that implements the function of converting a string from UTF-8 encoding to ASCII encoding. The requirements are as follows:\n\nInput a string (UTF-8 encoding).\nThe program will read the input string character by character and convert each character into the corresponding ASCII code.\nPrint out the converted ASCII codes one by one.\nYou can use an appropriate programming language to implement this function. Please note that multi-byte characters in UTF-8 encoding need to be specially handled to ensure correct conversion to the corresponding ASCII code. After calling the utf8_to_ascii function, an ASCII code list will be output, each element of which corresponds to the ASCII code of a character in the input string.\n\nFor example, if the input string is \"Hello World!\", after calling the utf8_to_ascii function, the following ASCII code list will be output:\n\n[72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]\nWhere the first element 72 corresponds to the ASCII code of the character H, the second element 101 corresponds to the ASCII code of the character e, and so on.\n\nThese ASCII codes can be further used for other operations, such as encryption, conversion, etc.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testutf8_to_ascii:\n def test_hello_world(self):\n assert utf8_to_ascii(\"Hello, World!\") == [72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33]\n\n", "problem": "Write a program that implements the function of converting a string from UTF-8 encoding to ASCII encoding. The requirements are as follows:\n\nInput a string (UTF-8 encoding).\nThe program will read the input string character by character and convert each character into the corresponding ASCII code.\nPrint out the converted ASCII codes one by one.\nYou can use an appropriate programming language to implement this function. Please note that multi-byte characters in UTF-8 encoding need to be specially handled to ensure correct conversion to the corresponding ASCII code. After calling the utf8_to_ascii function, an ASCII code list will be output, each element of which corresponds to the ASCII code of a character in the input string.\n\nFor example, if the input string is \"Hello World!\", after calling the utf8_to_ascii function, the following ASCII code list will be output:\n\n[72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]\nWhere the first element 72 corresponds to the ASCII code of the character H, the second element 101 corresponds to the ASCII code of the character e, and so on.\n\nThese ASCII codes can be further used for other operations, such as encryption, conversion, etc.", "testcases": "\n\nclass Testutf8_to_ascii:\n def test_empty_string(self):\n assert utf8_to_ascii(\"\") == None\n\n def test_invalid_hex_code(self):\n assert utf8_to_ascii(\"Hello%20Wo%zz\") == None\n\n def test_single_character(self):\n assert utf8_to_ascii(\"A\") == [65]\n\n def test_special_characters(self):\n assert utf8_to_ascii(\"!@#$%^&*()_+-=\") == [33, 64, 35, 36, 37, 94, 38, 42, 40, 41, 95, 43, 45, 61]\n\n def test_unicode_characters(self):\n assert utf8_to_ascii(\"\\u2018\\u2019\\u201c\\u201d\") == [8216, 8217, 8220, 8221]\n\n def test_long_string(self):\n assert utf8_to_ascii(\"a\" * 1000) == [97] * 1000\n\n def test_invalid_input_type(self):\n assert utf8_to_ascii(123) == None\n\n def test_invalid_input_encoding(self):\n assert utf8_to_ascii(b\"Hello%20World%21\") == None\n", "setup_code": "", "reference_solution": "```python\ndef utf8_to_ascii(utf8_string):\n # 验证输入字符串是否为空\n if not utf8_string:\n print(\"输入字符串不能为空!\")\n return None\n\n result = []\n\n try:\n # 遍历输入字符串的每个字符\n for i in range(len(utf8_string)):\n if utf8_string[i] == '%' and i + 2 < len(utf8_string) and utf8_string[i + 1:i + 3].isalnum():\n # 如果遇到以%开头的16进制字符编码,则进行解析\n hex_str = utf8_string[i + 1:i + 3]\n ascii_code = int(hex_str, 16)\n result.append(ascii_code)\n i += 2\n else:\n # 普通的UTF-8字符直接转换为ASCII码\n ascii_code = ord(utf8_string[i])\n result.append(ascii_code)\n except IndexError:\n print(\"输入字符串格式错误!\")\n return None\n except ValueError:\n print(\"输入字符串包含非法的字符编码!\")\n return None\n except Exception as e:\n print(\"发生未知错误:\", str(e))\n return None\n\n return result\n\n\n\n```", "classification": "Software Engineering"}
{"_id": 141, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nWrite a program that implements a Python function find_dates(text), which accepts a string text as a parameter and returns all dates that appear in the string. The dates should be in the standard year-month-day (YYYY-MM-DD) format.\n\nRequirements:\n\nThe date must be in the standard year-month-day (YYYY-MM-DD) format.\n\nThe year in the date must be a four-digit number, and the month and day must be two-digit numbers.\n\nThe function should not use external resources such as web scraping or user input.\n\nThe function must use regular expressions to identify dates.\n\nThe function must return all dates that meet the requirements. If there are no dates that meet the requirements, it should return an empty list.\n\nExample:\n\npython\ntext = \"The event will take place on 2022-01-25 and the deadline is 2022-02-15.\"\nprint(find_dates(text))\n# output: ['2022-01-25', '2022-02-15']\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testfind_dates:\n def test_case_1(self):\n text = \"The event will take place on 2022-01-25 and the deadline is 2022-02-15.\"\n expected_dates = [\"2022-01-25\", \"2022-02-15\"]\n assert find_dates(text) == expected_dates\n\n", "problem": "Write a program that implements a Python function find_dates(text), which accepts a string text as a parameter and returns all dates that appear in the string. The dates should be in the standard year-month-day (YYYY-MM-DD) format.\n\nRequirements:\n\nThe date must be in the standard year-month-day (YYYY-MM-DD) format.\n\nThe year in the date must be a four-digit number, and the month and day must be two-digit numbers.\n\nThe function should not use external resources such as web scraping or user input.\n\nThe function must use regular expressions to identify dates.\n\nThe function must return all dates that meet the requirements. If there are no dates that meet the requirements, it should return an empty list.\n\nExample:\n\npython\ntext = \"The event will take place on 2022-01-25 and the deadline is 2022-02-15.\"\nprint(find_dates(text))\n# output: ['2022-01-25', '2022-02-15']", "testcases": "import re\nimport datetime\n\n\nclass Testfind_dates:\n def test_case_2(self):\n text = \"Another possible date format is 2022-02-15.\"\n expected_dates = ['2022-02-15']\n assert find_dates(text) == expected_dates\n\n def test_case_3(self):\n text = \"And the third format is 01*01-*024.\"\n expected_dates = \"未找到有效日期\"\n assert find_dates(text) == expected_dates\n\n def test_case_4(self):\n text = \"Lastly, we have a date like 1 January 2025.\"\n expected_dates = '未找到有效日期'\n assert find_dates(text) == expected_dates\n\n def test_case_5(self):\n text = \"Invalid date formats: 2022-13-01, 31/12/2023, 01-01-2024\"\n expected_dates = \"未找到有效日期\"\n assert find_dates(text) == expected_dates\n\n def test_case_6(self):\n text = \"No dates in this text.\"\n expected_dates = \"未找到有效日期\"\n assert find_dates(text) == expected_dates\n\n def test_case_7(self):\n text = \"The event happened on 2020-12-25 and it was a great success.\"\n expected_dates = [\"2020-12-25\"]\n assert find_dates(text) == expected_dates\n\n def test_case_8(self):\n text = \"The due date for submission is 2022-06-30.\"\n expected_dates = [\"2022-06-30\"]\n assert find_dates(text) == expected_dates\n\n\n", "setup_code": "", "reference_solution": "```python\nimport re\nimport datetime\n\n\ndef find_dates(text):\n if not text:\n return \"输入的文本为空,请提供有效的文本内容\"\n\n date_patterns = [\n r\"\\b(\\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])\\b\", # YYYY-MM-DD\n r\"\\b(0[1-9]|1[0-2])/(0[1-9]|[12][0-9]|3[01])/(19|20)?\\d{2}\\b\", # MM/DD/YYYY or M/D/YYYY\n r\"\\b(0[1-9]|[12][0-9]|3[01])-(0[1-9]|1[0-2])-(19|20)?\\d{2}\\b\", # DD-MM-YYYY or D-M-YYYY\n r\"\\b(0[1-9]|[12][0-9]|3[01])\\s(January|February|March|April|May|June|July|August|September|October|November|December),?\\s(19|20)?\\d{2}\\b\"\n # DD Month YYYY or D Month YYYY\n ]\n dates = []\n for pattern in date_patterns:\n dates.extend(re.findall(pattern, text))\n\n formatted_dates = []\n for date in dates:\n if date[0]: # 如果匹配到了年份\n year = date[0]\n else:\n year = \"20\" + date[3] if date[3] else \"\" # 如果没有匹配到年份,则根据模式中的分组确定年份\n\n month = date[1].zfill(2)\n day = date[2].zfill(2)\n\n # 检查日期的有效性\n try:\n formatted_date = f\"{year}-{month}-{day}\"\n _ = datetime.datetime.strptime(formatted_date, \"%Y-%m-%d\")\n formatted_dates.append(formatted_date)\n except ValueError:\n pass\n\n if not formatted_dates:\n return \"未找到有效日期\"\n\n return formatted_dates\n\n```", "classification": "Software Engineering"}
{"_id": 142, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nWrite a program that simulates the memory management of an operating system in Python code. A Process class is defined in the code, representing a process, each process has a unique process identifier (pid) and a piece of code (code). The operating system maintains a memory map, memory_map, to track the allocation of memory. In the example, two processes are created and added to the processes list. Then, by calling the allocate_memory function, memory is allocated for each process. Finally, by calling the run_processes function, all processes are simulated to run, and the memory occupied by the processes is released by calling the deallocate_memory function.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass TestProcess:\n def test_successful_memory_allocation(self):\n memory_map = [0] * 100\n process = Process(pid=1, code=[1, 2, 3])\n\n assert allocate_memory(memory_map, process) == True\n assert process.memory is not None\n\n\n", "problem": "Write a program that simulates the memory management of an operating system in Python code. A Process class is defined in the code, representing a process, each process has a unique process identifier (pid) and a piece of code (code). The operating system maintains a memory map, memory_map, to track the allocation of memory. In the example, two processes are created and added to the processes list. Then, by calling the allocate_memory function, memory is allocated for each process. Finally, by calling the run_processes function, all processes are simulated to run, and the memory occupied by the processes is released by calling the deallocate_memory function.", "testcases": "\n\nclass TestProcess:\n def test_successful_allocation_multiple_processes(self):\n memory_map = [0] * 100\n process1 = Process(pid=1, code=[1, 2, 3])\n process2 = Process(pid=2, code=[4, 5, 6])\n\n assert allocate_memory(memory_map, process1) == True\n assert allocate_memory(memory_map, process2) == True\n assert process1.memory is not None\n assert process2.memory is not None\n\n\n def test_failed_memory_allocation(self):\n memory_map = [1] * 100 # Memory is already full\n process = Process(pid=1, code=[1, 2, 3])\n\n assert allocate_memory(memory_map, process) == False\n assert process.memory is None\n\n\n def test_memory_deallocation(self):\n memory_map = [0] * 100\n process = Process(pid=1, code=[1, 2, 3])\n\n allocate_memory(memory_map, process)\n deallocate_memory(memory_map, process)\n\n assert process.memory is None\n\n\n def test_run_processes(self):\n processes = [\n Process(pid=1, code=[1, 2, 3]),\n Process(pid=2, code=[4, 5, 6])\n ]\n\n run_processes(processes)\n # Manual inspection of output\n\n\n def test_deallocate_unallocated_memory(self):\n memory_map = [0] * 100\n process = Process(pid=1, code=[1, 2, 3])\n\n deallocate_memory(memory_map, process)\n\n assert process.memory is None\n\n\n def test_run_empty_processes(self):\n empty_processes = []\n run_processes(empty_processes)\n # Manual inspection of output\n\n\n def test_allocate_full_memory(self):\n full_memory_map = [0] * 100\n full_process = Process(pid=1, code=[1] * 100)\n\n assert allocate_memory(full_memory_map, full_process) == True\n assert full_process.memory is not None\n\n\n def test_continuous_allocation_deallocation(self):\n continuous_memory_map = [0] * 100\n continuous_process = Process(pid=1, code=[1, 2, 3])\n\n assert allocate_memory(continuous_memory_map, continuous_process) == True\n assert continuous_process.memory is not None\n\n deallocate_memory(continuous_memory_map, continuous_process)\n\n assert continuous_process.memory is None\n", "setup_code": "", "reference_solution": "```python\nclass Process:\n def __init__(self, pid, code):\n self.pid = pid\n self.code = code\n self.memory = None\n\ndef allocate_memory(memory_map, process):\n if process.memory is not None:\n raise ValueError(\"Process already has memory\")\n\n for i in range(len(memory_map)):\n if memory_map[i] == 0:\n process.memory = i\n for j in range(len(process.code)):\n memory_map[i + j] = 1\n return True\n\n return False\n\ndef deallocate_memory(memory_map, process):\n if process.memory is not None:\n for i in range(len(process.code)):\n memory_map[process.memory + i] = 0\n process.memory = None\n\ndef run_processes(processes):\n for process in processes:\n print(f\"Running Process {process.pid} with code: {process.code}\")\n\n# 创建一个简单的操作系统\nmemory_map = [0] * 100\nprocesses = []\n\n# 创建两个进程\nprocess1 = Process(pid=1, code=[1, 2, 3])\nprocess2 = Process(pid=2, code=[4, 5, 6])\n\n# 将进程添加到列表\nprocesses.append(process1)\nprocesses.append(process2)\n\n# 分配内存\nallocate_memory(memory_map, process1)\nallocate_memory(memory_map, process2)\n\n# 运行进程\nrun_processes(processes)\n\n# 释放内存\ndeallocate_memory(memory_map, process1)\ndeallocate_memory(memory_map, process2)\n\n```", "classification": "Operation System"}
{"_id": 143, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nWrite a program to implement the following problem description:\nGiven an HTML text containing multiple English sentences, write a function get_top_k_words_from_html(html, k) that returns the top k words with the highest frequency of occurrence.\n\nWrite a function get_top_k_words_from_html(html, k), where the parameter html is a string containing HTML tags, and k is a positive integer. The function should return a list containing the top k words with the highest frequency of occurrence and their frequencies, sorted in descending order of frequency.\n\nExamples:\nInput: \"<p>We are the world, we are the children.</p> <p>We are the ones who make a brighter day.</p> <p>So let's start giving.</p>\"\nOutput: [('we', 3), ('are', 3), ('the', 3)]\n\nInput: \"<p>The quick brown fox jumps over the lazy dog.</p> <p>The quick brown fox jumps over the lazy dog.</p>\"\nOutput: [('the', 4), ('brown', 2), ('quick', 2)]\n\nNote:\n\nWords are case-insensitive, i.e., \"The\" and \"the\" are considered the same word.\nA word is defined as a string composed of letters and numbers, excluding punctuation.\nThe returned list should include all the top k words with the same frequency of occurrence and their frequencies.\nYou can use libraries to parse HTML text and use standard library functions or modules to assist in solving the problem.\nPlease implement the function get_top_k_words_from_html(html, k) to solve this problem.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testget_top_k_words_from_html:\n def test_empty_html(self):\n html = \"<html><body></body></html>\"\n assert get_top_k_words_from_html(html, 5) == []\n\n", "problem": "Write a program to implement the following problem description:\nGiven an HTML text containing multiple English sentences, write a function get_top_k_words_from_html(html, k) that returns the top k words with the highest frequency of occurrence.\n\nWrite a function get_top_k_words_from_html(html, k), where the parameter html is a string containing HTML tags, and k is a positive integer. The function should return a list containing the top k words with the highest frequency of occurrence and their frequencies, sorted in descending order of frequency.\n\nExamples:\nInput: \"<p>We are the world, we are the children.</p> <p>We are the ones who make a brighter day.</p> <p>So let's start giving.</p>\"\nOutput: [('we', 3), ('are', 3), ('the', 3)]\n\nInput: \"<p>The quick brown fox jumps over the lazy dog.</p> <p>The quick brown fox jumps over the lazy dog.</p>\"\nOutput: [('the', 4), ('brown', 2), ('quick', 2)]\n\nNote:\n\nWords are case-insensitive, i.e., \"The\" and \"the\" are considered the same word.\nA word is defined as a string composed of letters and numbers, excluding punctuation.\nThe returned list should include all the top k words with the same frequency of occurrence and their frequencies.\nYou can use libraries to parse HTML text and use standard library functions or modules to assist in solving the problem.\nPlease implement the function get_top_k_words_from_html(html, k) to solve this problem.", "testcases": "import re\nfrom collections import Counter\nfrom bs4 import BeautifulSoup\n\n\nclass Testget_top_k_words_from_html:\n def test_basic_html(self):\n html = \"<html><body>This is a simple HTML text. Hello world!</body></html>\"\n assert get_top_k_words_from_html(html, 3) == [('simple', 1), ('html', 1), ('text', 1)]\n\n def test_html_with_tags(self):\n html = \"<html><body><h1>Title</h1><p> is a paragraph.</p></body></html>\"\n assert get_top_k_words_from_html(html, 4) == [('title', 1), ('paragraph', 1)]\n\n def test_html_with_special_characters(self):\n html = \"<html><body>Encoding: ٠١٢</body></html>\"\n assert get_top_k_words_from_html(html, 3) == [('encoding', 1), ('٠١٢', 1)]\n\n def test_html_with_unicode_characters(self):\n html = \"<html><body>Unicode: àéîőű</body></html>\"\n assert get_top_k_words_from_html(html, 4) == [('unicode', 1), ('àéîőű', 1)]\n\n def test_html_with_duplicate_words(self):\n html = \"<html><body>Repeated words test. This is a test repeated words.</body></html>\"\n assert get_top_k_words_from_html(html, 4) == [('repeated', 2), ('words', 2), ('test', 2)]\n\n def test_large_html(self):\n # Test with a large HTML content\n html = \"<html><body>\" + \"word1 \" * 1000 + \"</body></html>\"\n assert get_top_k_words_from_html(html, 1) == [('word1', 1000)]\n\n\n def test_html_with_numbers(self):\n html = \"<html><body>Numbers: 123 456 789</body></html>\"\n assert get_top_k_words_from_html(html, 3) == [('numbers', 1), ('123', 1), ('456', 1)]\n\n\n def test_html_with_unicode_characters_and_numbers(self):\n html = \"<html><body>Unicode and numbers: àéîőű 12345</body></html>\"\n assert get_top_k_words_from_html(html, 4) == [('unicode', 1), ('numbers', 1), ('àéîőű', 1), ('12345', 1)]\n\n\n\n", "setup_code": "", "reference_solution": "```python\nimport re\nfrom collections import Counter\nfrom bs4 import BeautifulSoup\n\n\ndef get_top_k_words_from_html(html, k):\n # 定义需要排除的单词列表\n exclude_list = ['this','is','are','a', 'an', 'the', 'and', 'or', 'in', 'on', 'at', 'to', 'of', 'for', 'with', 'by', 'from']\n\n try:\n # 解析HTML文本\n soup = BeautifulSoup(html, 'lxml')\n\n # 获取所有文本内容\n text = soup.get_text()\n\n # 将文本转换为小写,并使用正则表达式提取单词\n\n lower=text.lower()\n words = re.findall(r'\\b(?<!-)(?!' + '|'.join(exclude_list) + r')\\w+(?<!-)\\b', lower, flags=re.UNICODE)\n\n # 使用Counter统计单词出现次数\n word_counts = Counter(words)\n\n # 获取出现次数最多的前k个单词及其出现次数\n top_k_words = word_counts.most_common(k)\n\n return top_k_words\n\n except Exception as e:\n print(\"Error occurred:\", str(e))\n return None\n\n```", "classification": "Front-End"}
{"_id": 144, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nWrite a program to complete the task: Meteorological Data Analysis\n\nWrite a program to analyze and process temperature data.\n\nRequirements:\n\nWrite a function extract_temperatures_from_text(text: str) -> List[float], which takes a text string as a parameter, extracts temperature data from the text, and returns it in the form of a list. Each line in the file contains a temperature value in Celsius.\n\nWrite a function calculate_average_temperature(temperatures: List[float]) -> float, which takes a list of temperature data as a parameter, calculates the average temperature, and returns it.\n\nWrite a function find_highest_temperature(temperatures: List[float]) -> float, which takes a list of temperature data as a parameter, finds the highest temperature in it, and returns it.\n\nWrite a function find_lowest_temperature(temperatures: List[float]) -> float, which takes a list of temperature data as a parameter, finds the lowest temperature in it, and returns it.\n\nUse case:\n\npython\ntext = \"\"\"\nBeijing, -4℃\nShanghai, 3℃\nGuangzhou, 12℃\nChongqing, 8℃\n\"\"\"\n\ntemperatures = extract_temperatures_from_text(text)\naverage_temp = calculate_average_temperature(temperatures)\nhighest_temp = find_highest_temperature(temperatures)\nlowest_temp = find_lowest_temperature(temperatures)\n\nprint(\"Extracted temperature data:\", temperatures)\nprint(\"Average temperature:\", average_temp)\nprint(\"Highest temperature:\", highest_temp)\nprint(\"Lowest temperature:\", lowest_temp)\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testextract_temperatures_from_text:\n def test_extract_temperatures_from_text_with_temperatures(self):\n text = \"北京,-4℃\\n上海,3℃\\n广州,12℃\\n重庆,8℃\"\n cities, temperatures = extract_temperatures_from_text(text)\n assert cities == [\"北京\", \"上海\", \"广州\", \"重庆\"]\n assert temperatures == [-4.0, 3.0, 12.0, 8.0]\n\n", "problem": "Write a program to complete the task: Meteorological Data Analysis\n\nWrite a program to analyze and process temperature data.\n\nRequirements:\n\nWrite a function extract_temperatures_from_text(text: str) -> List[float], which takes a text string as a parameter, extracts temperature data from the text, and returns it in the form of a list. Each line in the file contains a temperature value in Celsius.\n\nWrite a function calculate_average_temperature(temperatures: List[float]) -> float, which takes a list of temperature data as a parameter, calculates the average temperature, and returns it.\n\nWrite a function find_highest_temperature(temperatures: List[float]) -> float, which takes a list of temperature data as a parameter, finds the highest temperature in it, and returns it.\n\nWrite a function find_lowest_temperature(temperatures: List[float]) -> float, which takes a list of temperature data as a parameter, finds the lowest temperature in it, and returns it.\n\nUse case:\n\npython\ntext = \"\"\"\nBeijing, -4℃\nShanghai, 3℃\nGuangzhou, 12℃\nChongqing, 8℃\n\"\"\"\n\ntemperatures = extract_temperatures_from_text(text)\naverage_temp = calculate_average_temperature(temperatures)\nhighest_temp = find_highest_temperature(temperatures)\nlowest_temp = find_lowest_temperature(temperatures)\n\nprint(\"Extracted temperature data:\", temperatures)\nprint(\"Average temperature:\", average_temp)\nprint(\"Highest temperature:\", highest_temp)\nprint(\"Lowest temperature:\", lowest_temp)", "testcases": "from typing import List, Tuple\n\n\nclass Testextract_temperatures_from_text:\n def test_extract_temperatures_from_text_without_temperatures(self):\n text = \"北京\\n上海\\n广州\\n重庆\"\n cities, temperatures = extract_temperatures_from_text(text)\n assert cities == []\n assert temperatures == []\n\n def test_calculate_average_temperature(self):\n temperatures = [10.0, 20.0, 30.0]\n assert calculate_average_temperature(temperatures) == 20.0\n\n def test_find_highest_temperature(self):\n cities = [\"北京\", \"上海\", \"广州\", \"重庆\"]\n temperatures = [-4.0, 3.0, 12.0, 8.0]\n assert find_highest_temperature(cities, temperatures) == (12.0, \"广州\")\n\n def test_find_lowest_temperature(self):\n cities = [\"北京\", \"上海\", \"广州\", \"重庆\"]\n temperatures = [-4.0, 3.0, 12.0, 8.0]\n assert find_lowest_temperature(cities, temperatures) == (-4.0, \"北京\")\n\n def test_extract_temperatures_from_text_with_single_data(self):\n text = \"北京,-4℃\"\n cities, temperatures = extract_temperatures_from_text(text)\n assert cities == [\"北京\"]\n assert temperatures == [-4.0]\n\n def test_extract_temperatures_from_text_with_cities_only(self):\n text = \"北京\\n上海\\n广州\\n重庆\"\n cities, temperatures = extract_temperatures_from_text(text)\n assert cities == []\n assert temperatures == []\n\n def test_calculate_average_temperature_with_single_temperature(self):\n temperatures = [10.0]\n assert calculate_average_temperature(temperatures) == 10.0\n\n def test_find_highest_temperature_with_single_temperature(self):\n cities = [\"北京\"]\n temperatures = [-4.0]\n assert find_highest_temperature(cities, temperatures) == (-4.0, \"北京\")\n\n def test_find_lowest_temperature_with_single_temperature(self):\n cities = [\"北京\"]\n temperatures = [-4.0]\n assert find_lowest_temperature(cities, temperatures) == (-4.0, \"北京\")\n\n def test_extract_temperatures_from_text_with_duplicate_temperatures(self):\n text = \"北京,-4℃\\n上海,3℃\\n广州,12℃\\n重庆,8℃\\n成都,12℃\"\n cities, temperatures = extract_temperatures_from_text(text)\n assert cities == [\"北京\", \"上海\", \"广州\", \"重庆\", \"成都\"]\n assert temperatures == [-4.0, 3.0, 12.0, 8.0, 12.0]\n\n def test_extract_temperatures_from_text_with_decimal_temperatures(self):\n text = \"北京,-4.5℃\\n上海,3.2℃\\n广州,12.7℃\\n重庆,8.9℃\"\n cities, temperatures = extract_temperatures_from_text(text)\n assert cities == [\"北京\", \"上海\", \"广州\", \"重庆\"]\n assert temperatures == [-4.5, 3.2, 12.7, 8.9]\n\n", "setup_code": "", "reference_solution": "```python\nfrom typing import List, Tuple\n\n\ndef extract_temperatures_from_text(text: str) -> Tuple[List[str], List[float]]:\n cities = []\n temperatures = []\n lines = text.strip().split('\\n')\n for line in lines:\n city_temperature = line.split(',')\n if len(city_temperature) == 2:\n city, temperature = city_temperature\n temperature = float(temperature.replace('℃', ''))\n cities.append(city)\n temperatures.append(temperature)\n else:\n return [], []\n return cities, temperatures\n\ndef calculate_average_temperature(temperatures: List[float]) -> float:\n total_temperature = sum(temperatures)\n average_temperature = total_temperature / len(temperatures)\n return average_temperature\n\ndef find_highest_temperature(cities: List[str], temperatures: List[float]) -> Tuple[float, str]:\n if not temperatures:\n return 0, \"无\"\n index = temperatures.index(max(temperatures))\n highest_temperature = temperatures[index]\n city = cities[index]\n return highest_temperature, city\n\ndef find_lowest_temperature(cities: List[str], temperatures: List[float]) -> Tuple[float, str]:\n if not temperatures:\n return 0, \"无\"\n index = temperatures.index(min(temperatures))\n lowest_temperature = temperatures[index]\n city = cities[index]\n return lowest_temperature, city\n\n\n```", "classification": "Data Science"}
{"_id": 145, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nWrite a program, a function count_html_tags(html), which accepts an HTML string as a parameter and returns the number of HTML tags contained in the string.\n\nRequirements:\n\nHTML tags are surrounded by angle brackets < and >, with the tag name inside the brackets.\nThe tag name consists of lowercase letters and does not contain spaces or other special characters.\nAssume that the input HTML string is valid, no error handling is required.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testcount_html_tags:\n def test_empty_string(self):\n html = \"\"\n tag_count, max_nested_depth = count_html_tags(html)\n assert tag_count == 0\n assert max_nested_depth == 0\n\n", "problem": "Write a program, a function count_html_tags(html), which accepts an HTML string as a parameter and returns the number of HTML tags contained in the string.\n\nRequirements:\n\nHTML tags are surrounded by angle brackets < and >, with the tag name inside the brackets.\nThe tag name consists of lowercase letters and does not contain spaces or other special characters.\nAssume that the input HTML string is valid, no error handling is required.", "testcases": "import re\n\n\nclass Testcount_html_tags:\n def test_single_tag(self):\n html = \"<div></div>\"\n tag_count, max_nested_depth = count_html_tags(html)\n assert tag_count == 2\n assert max_nested_depth == 1\n\n def test_nested_tags(self):\n html = \"<div><p><span></span></p></div>\"\n tag_count, max_nested_depth = count_html_tags(html)\n assert tag_count == 6\n assert max_nested_depth == 3\n\n def test_mismatched_closing_tag(self):\n html = \"<div></span>\"\n tag_count, max_nested_depth = count_html_tags(html)\n assert tag_count == 1\n assert max_nested_depth == 1\n\n def test_case_sensitive(self):\n html = \"<DIV><P><SPAN></span></P></div>\"\n tag_count, max_nested_depth = count_html_tags(html)\n assert tag_count == 6\n assert max_nested_depth == 3\n\n def test_special_characters(self):\n html = \"<p>This is some text with <strong> tags.</p>\"\n tag_count, max_nested_depth = count_html_tags(html)\n assert tag_count == 2\n\n def test_unbalanced_tags(self):\n html = \"<div><p></div></p>\"\n result = count_html_tags(html)\n assert result == (3, 2)", "setup_code": "", "reference_solution": "```python\nimport re\n\n\ndef count_html_tags(html):\n pattern = r'<\\s*([a-zA-Z]+)[^>]*>|<\\s*/\\s*([a-zA-Z]+)\\s*>'\n matches = re.findall(pattern, html)\n\n tag_count = 0\n nested_tags = []\n max_nested_depth = 0\n\n for opening_tag, closing_tag in matches:\n if opening_tag:\n nested_tags.append(opening_tag.lower())\n tag_count += 1\n max_nested_depth = max(max_nested_depth, len(nested_tags))\n elif nested_tags and nested_tags[-1] == closing_tag.lower():\n nested_tags.pop()\n tag_count += 1\n\n return tag_count, max_nested_depth\n\n\n\n```", "classification": "Front-End"}
{"_id": 146, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nWrite a program, a script for data encryption and decryption, such as the encrypt function: It accepts plaintext and a key as input, and uses the AES algorithm's ECB mode for encryption. Before encryption, the length of the plaintext will be padded to a multiple of the AES block size. The encryption result is returned in the form of Base64 encoding.\n\ndecrypt function: It accepts ciphertext and a key as input, and uses the AES algorithm's ECB mode for decryption. After decryption, any added spaces will be removed, and then the decrypted plaintext is returned.\n\nsave_to_file function: It accepts data and a filename as input, and writes the data to the specified file.\n\nread_from_file function: It accepts a filename as input, reads data from the specified file, and returns it.\n\nEncryption and decryption demonstration: Use the example text \"Hello, World!\" and a 16-byte key for encryption. The encrypted result is saved to the file \"encrypted_data.txt\" in Base64 encoding.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass TestEncryption:\n def test_encrypt_decrypt_with_fixture(self, encryption_key):\n original_text = \"Hello, World!\"\n encrypted_text = encrypt(original_text, encryption_key)\n decrypted_text = decrypt(encrypted_text, encryption_key)\n assert original_text == decrypted_text, \"Encryption and decryption failed.\"\n\n", "problem": "Write a program, a script for data encryption and decryption, such as the encrypt function: It accepts plaintext and a key as input, and uses the AES algorithm's ECB mode for encryption. Before encryption, the length of the plaintext will be padded to a multiple of the AES block size. The encryption result is returned in the form of Base64 encoding.\n\ndecrypt function: It accepts ciphertext and a key as input, and uses the AES algorithm's ECB mode for decryption. After decryption, any added spaces will be removed, and then the decrypted plaintext is returned.\n\nsave_to_file function: It accepts data and a filename as input, and writes the data to the specified file.\n\nread_from_file function: It accepts a filename as input, reads data from the specified file, and returns it.\n\nEncryption and decryption demonstration: Use the example text \"Hello, World!\" and a 16-byte key for encryption. The encrypted result is saved to the file \"encrypted_data.txt\" in Base64 encoding.", "testcases": "import os\nfrom cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes\nfrom cryptography.hazmat.backends import default_backend\nimport base64\n\n\nclass TestEncryption:\n def test_save_and_read_from_file_with_fixture(self, encryption_key, tmp_path):\n original_text = \"Testing file save and read functionality.\"\n encrypted_text = encrypt(original_text, encryption_key)\n file_path = tmp_path / \"test_file.txt\"\n\n # Save encrypted text to file\n save_to_file(encrypted_text, file_path)\n\n # Read from file and decrypt\n loaded_encrypted_text = read_from_file(file_path)\n decrypted_text = decrypt(loaded_encrypted_text, encryption_key)\n\n assert original_text == decrypted_text, \"File save and read failed.\"\n\n def test_encrypt_empty_string_with_fixture(self, encryption_key):\n original_text = \"\"\n encrypted_text = encrypt(original_text, encryption_key)\n decrypted_text = decrypt(encrypted_text, encryption_key)\n assert original_text == decrypted_text, \"Encryption and decryption of empty string failed.\"\n\n def test_decrypt_invalid_input_with_fixture(self, encryption_key):\n invalid_encrypted_text = \"InvalidInput\"\n with pytest.raises(Exception, match=\"The length of the provided data is not a multiple of the block length.\"):\n decrypt(invalid_encrypted_text, encryption_key)\n\n def test_decrypt_truncated_data_with_fixture(self, encryption_key, tmp_path):\n original_text = \"Hello, World!\"\n encrypted_text = encrypt(original_text, encryption_key)\n\n # Truncate the encrypted data\n truncated_encrypted_text = encrypted_text[:-5]\n\n file_path = tmp_path / \"truncated_data.txt\"\n save_to_file(truncated_encrypted_text, file_path)\n\n\n def test_read_from_nonexistent_file_with_fixture(self, encryption_key, tmp_path):\n nonexistent_file_path = tmp_path / \"nonexistent_file.txt\"\n with pytest.raises(FileNotFoundError):\n read_from_file(nonexistent_file_path)\n\n @pytest.fixture\n def encryption_key(self):\n return b'Sixteen byte key'\n", "setup_code": "", "reference_solution": "```python\nfrom cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes\nfrom cryptography.hazmat.backends import default_backend\nimport base64\n\n\ndef encrypt(text, key):\n backend = default_backend()\n cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=backend)\n encryptor = cipher.encryptor()\n\n # 补全文本长度至AES块大小的倍数\n text = text + ' ' * (16 - len(text) % 16)\n\n # 加密\n ciphertext = encryptor.update(text.encode()) + encryptor.finalize()\n return base64.b64encode(ciphertext).decode()\n\n\ndef decrypt(encrypted_text, key):\n backend = default_backend()\n cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=backend)\n decryptor = cipher.decryptor()\n\n # 解密\n ciphertext = base64.b64decode(encrypted_text.encode())\n decrypted_text = decryptor.update(ciphertext) + decryptor.finalize()\n return decrypted_text.decode().rstrip()\n\n\ndef save_to_file(data, filename):\n with open(filename, 'w') as file:\n file.write(data)\n\n\ndef read_from_file(filename):\n with open(filename, 'r') as file:\n return file.read()\n\n\n\ntext_to_encrypt = \"Hello, World!\"\nencryption_key = b'Sixteen byte key'\n\n# # 加密并保存到文件\n# encrypted_text = encrypt(text_to_encrypt, encryption_key)\n# save_to_file(encrypted_text, \"encrypted_data.txt\")\n#\n# # 从文件中读取并解密\n# loaded_encrypted_text = read_from_file(\"encrypted_data.txt\")\n# decrypted_text = decrypt(loaded_encrypted_text, encryption_key)\n\n\n\n```", "classification": "Software Engineering"}
{"_id": 147, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nWrite a program that takes a folder path as input and then backs up all the files in that folder to a specified target folder, preserving the original file structure. For example, the backup_folder function takes two parameters: the source folder path (source_folder) and the target folder path (target_folder). Before performing the backup operation, it will perform a series of checks:\n\nSource folder check: First, the script will verify whether the source folder exists. If it does not exist, it throws an exception and displays the corresponding error message.\n\nTarget folder check: Then, it will check whether the target folder exists. If the target folder does not exist, the script will create it.\n\nNext, use the os.walk function to traverse all files and subfolders in the source folder. For each file and folder found, the script will perform the following operations:\n\nBuild target path: Build the relative path in the target folder and create the corresponding subfolders in the target folder.\n\nFile copy: Use the shutil.copy2 function to copy files. This function will preserve the metadata of the file, such as creation time and modification time.\n\nFinally, after the backup is completed, the script will output a message indicating that the backup was successful.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testbackup_folder:\n def test_backup_successful(self, setup_test_folders):\n source_folder, target_folder = setup_test_folders\n assert source_folder.exists()\n backup_folder(source_folder, target_folder)\n assert target_folder.exists()\n\n", "problem": "Write a program that takes a folder path as input and then backs up all the files in that folder to a specified target folder, preserving the original file structure. For example, the backup_folder function takes two parameters: the source folder path (source_folder) and the target folder path (target_folder). Before performing the backup operation, it will perform a series of checks:\n\nSource folder check: First, the script will verify whether the source folder exists. If it does not exist, it throws an exception and displays the corresponding error message.\n\nTarget folder check: Then, it will check whether the target folder exists. If the target folder does not exist, the script will create it.\n\nNext, use the os.walk function to traverse all files and subfolders in the source folder. For each file and folder found, the script will perform the following operations:\n\nBuild target path: Build the relative path in the target folder and create the corresponding subfolders in the target folder.\n\nFile copy: Use the shutil.copy2 function to copy files. This function will preserve the metadata of the file, such as creation time and modification time.\n\nFinally, after the backup is completed, the script will output a message indicating that the backup was successful.", "testcases": "import os\nimport shutil\n\n\nclass Testbackup_folder:\n # 使用 fixture 的方式进行测试\n def test_backup_empty_folder(self, tmp_path):\n source_folder = tmp_path / \"empty_folder\"\n target_folder = tmp_path / \"target_folder_empty\"\n source_folder.mkdir()\n assert source_folder.exists()\n backup_folder(source_folder, target_folder)\n assert target_folder.exists()\n assert not os.listdir(target_folder)\n\n def test_backup_with_subfolders(self, tmp_path):\n source_folder = tmp_path / \"source_with_subfolders\"\n target_folder = tmp_path / \"target_with_subfolders\"\n (source_folder / \"subfolder\").mkdir(parents=True)\n assert source_folder.exists()\n backup_folder(source_folder, target_folder)\n assert target_folder.exists()\n\n def test_backup_existing_target_folder(self, tmp_path):\n source_folder = tmp_path / \"source_folder\"\n target_folder = tmp_path / \"target_folder\"\n source_folder.mkdir()\n target_folder.mkdir()\n assert source_folder.exists()\n assert target_folder.exists()\n backup_folder(source_folder, target_folder)\n assert target_folder.exists()\n\n def test_backup_to_temporary_folder(self, tmp_path):\n source_folder = tmp_path / \"source_folder\"\n target_folder = tmp_path / \"target_folder_temp\"\n source_folder.mkdir()\n assert source_folder.exists()\n backup_folder(source_folder, target_folder)\n assert target_folder.exists()\n\n def test_source_folder_contains_files(self, setup_test_folders):\n source_folder, target_folder = setup_test_folders\n # 在源文件夹中创建一些文件\n file1 = source_folder / \"file1.txt\"\n file2 = source_folder / \"subfolder\" / \"file2.txt\"\n file1.write_text(\"这是文件1的内容。\")\n file2.parent.mkdir(parents=True)\n file2.write_text(\"这是文件2的内容。\")\n\n assert file1.exists()\n assert file2.exists()\n\n backup_folder(source_folder, target_folder)\n\n # 检查文件是否在目标文件夹中备份\n assert (target_folder / \"file1.txt\").exists()\n assert (target_folder / \"subfolder\" / \"file2.txt\").exists()\n\n def test_backup_with_different_file_types(self, setup_test_folders):\n source_folder, target_folder = setup_test_folders\n # 在源文件夹中创建不同扩展名的文件\n file_txt = source_folder / \"file.txt\"\n file_csv = source_folder / \"data.csv\"\n file_py = source_folder / \"script.py\"\n\n file_txt.write_text(\"这是一个文本文件。\")\n file_csv.write_text(\"CSV 数据在这里。\")\n file_py.write_text(\"# Python 脚本内容。\")\n\n assert file_txt.exists()\n assert file_csv.exists()\n assert file_py.exists()\n\n backup_folder(source_folder, target_folder)\n\n # 检查文件是否在目标文件夹中备份\n assert (target_folder / \"file.txt\").exists()\n assert (target_folder / \"data.csv\").exists()\n assert (target_folder / \"script.py\").exists()\n\n\n @pytest.fixture\n def setup_test_folders(self, tmp_path):\n source_folder = tmp_path / \"source_folder\"\n target_folder = tmp_path / \"target_folder\"\n source_folder.mkdir()\n target_folder.mkdir()\n yield source_folder, target_folder\n", "setup_code": "", "reference_solution": "```python\nimport os\nimport shutil\n\ndef backup_folder(source_folder, target_folder):\n try:\n # 检查源文件夹是否存在\n if not os.path.exists(source_folder):\n raise Exception(\"Source folder does not exist.\")\n\n # 检查目标文件夹是否存在,如果不存在则创建\n if not os.path.exists(target_folder):\n os.makedirs(target_folder)\n\n # 遍历源文件夹中的所有文件和子文件夹\n for root, dirs, files in os.walk(source_folder):\n # 构建目标文件夹中的相对路径\n relative_path = os.path.relpath(root, source_folder)\n target_path = os.path.join(target_folder, relative_path)\n\n # 创建目标文件夹中的子文件夹\n if not os.path.exists(target_path):\n os.makedirs(target_path)\n\n # 复制源文件夹中的所有文件到目标文件夹中\n for file in files:\n source_file = os.path.join(root, file)\n target_file = os.path.join(target_path, file)\n shutil.copy2(source_file, target_file)\n\n print(\"Backup completed successfully.\")\n\n except Exception as e:\n print(f\"An error occurred: {e}\")\n\n```", "classification": "Operation System"}
{"_id": 148, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nWrite a Python program for file and folder operations, including creating a folder (create_folder), using the open function to create a file in write mode and write the specified content, using the open function to open a file in read mode and read the file content, copying a file (copy_file), moving a file (move_file), and deleting a folder and its contents (delete_folder). For example, # Import file operation related modules\nimport os\nimport shutil\n\n# Create a folder\ncreate_folder('data')\n\n# Create and write a file in the data folder\ninfo_file_path = os.path.join('data', 'info.txt')\ncreate_and_write_file(info_file_path, \"Hello, this is some information.\")\n\n# Read and print the file content\nread_and_print_file(info_file_path)\n\n# Copy the file to info_backup.txt\ninfo_backup_path = os.path.join('data', 'info_backup.txt')\ncopy_file(info_file_path, info_backup_path)\n\n# Move the file to the backup folder\ncreate_folder('backup')\ninfo_backup_new_path = os.path.join('backup', 'info_backup.txt')\nmove_file(info_backup_path, info_backup_new_path)\n\n# Delete the data folder and all its files\ndelete_folder('data')\nImport the os module, and shutil module\nThe program creates a folder (data).\nIn this folder, it creates a file (info.txt) and writes some information.\nIt reads and prints the content of the file.\nIt copies the file to another file (info_backup.txt).\nIt moves the file to another folder (backup).\nIt deletes the original folder (data) and all its files.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass TestFile_process:\n def test_create_folder(self):\n data_folder = 'data'\n info_file_path = os.path.join(data_folder, 'info.txt')\n backup_folder = 'backup'\n info_backup_path = os.path.join(backup_folder, 'info_backup.txt')\n create_folder(data_folder)\n assert os.path.exists(data_folder)\n\n # 测试用例2: 创建并写入文件\n", "problem": "Write a Python program for file and folder operations, including creating a folder (create_folder), using the open function to create a file in write mode and write the specified content, using the open function to open a file in read mode and read the file content, copying a file (copy_file), moving a file (move_file), and deleting a folder and its contents (delete_folder). For example, # Import file operation related modules\nimport os\nimport shutil\n\n# Create a folder\ncreate_folder('data')\n\n# Create and write a file in the data folder\ninfo_file_path = os.path.join('data', 'info.txt')\ncreate_and_write_file(info_file_path, \"Hello, this is some information.\")\n\n# Read and print the file content\nread_and_print_file(info_file_path)\n\n# Copy the file to info_backup.txt\ninfo_backup_path = os.path.join('data', 'info_backup.txt')\ncopy_file(info_file_path, info_backup_path)\n\n# Move the file to the backup folder\ncreate_folder('backup')\ninfo_backup_new_path = os.path.join('backup', 'info_backup.txt')\nmove_file(info_backup_path, info_backup_new_path)\n\n# Delete the data folder and all its files\ndelete_folder('data')\nImport the os module, and shutil module\nThe program creates a folder (data).\nIn this folder, it creates a file (info.txt) and writes some information.\nIt reads and prints the content of the file.\nIt copies the file to another file (info_backup.txt).\nIt moves the file to another folder (backup).\nIt deletes the original folder (data) and all its files.", "testcases": "import os\nimport shutil\n\n\nclass TestFile_process:\n # 测试用例1: 创建文件夹\n def test_create_and_write_file(self):\n data_folder = 'data'\n info_file_path = os.path.join(data_folder, 'info.txt')\n backup_folder = 'backup'\n info_backup_path = os.path.join(backup_folder, 'info_backup.txt')\n create_and_write_file(info_file_path, \"Test content\")\n assert os.path.exists(info_file_path)\n\n # 测试用例3: 读取并打印文件内容\n def test_read_and_print_file(self, capsys):\n data_folder = 'data'\n info_file_path = os.path.join(data_folder, 'info.txt')\n backup_folder = 'backup'\n info_backup_path = os.path.join(backup_folder, 'info_backup.txt')\n read_and_print_file(info_file_path)\n captured = capsys.readouterr()\n assert \"Test content\" in captured.out\n\n # 测试用例4: 复制文件\n def test_copy_file(self):\n data_folder = 'data'\n info_file_path = os.path.join(data_folder, 'info.txt')\n backup_folder = 'backup'\n info_backup_path = os.path.join(backup_folder, 'info_backup.txt')\n copy_file(info_file_path, info_backup_path)\n assert os.path.exists(info_backup_path)\n\n # 测试用例:尝试移动已删除的文件\n def test_move_deleted_file(self):\n data_folder = 'data'\n info_file_path = os.path.join(data_folder, 'info.txt')\n backup_folder = 'backup'\n info_backup_path = os.path.join(backup_folder, 'info_backup.txt')\n # 创建 data 文件夹\n create_folder(data_folder)\n\n # 在 data 文件夹中创建 info.txt 文件\n create_and_write_file(info_file_path, \"Hello, this is some information.\")\n\n # 将文件移动到 backup 文件夹中\n shutil.move(info_file_path, backup_folder)\n\n # 使用 os.path.join 构建移动后的文件路径\n moved_file_path = os.path.join(backup_folder, os.path.basename(info_file_path))\n\n # 确保文件已成功移动\n assert os.path.exists(moved_file_path)\n assert not os.path.exists(info_file_path)\n\n # 测试用例6: 删除文件夹\n def test_delete_folder(self):\n data_folder = 'data'\n info_file_path = os.path.join(data_folder, 'info.txt')\n backup_folder = 'backup'\n info_backup_path = os.path.join(backup_folder, 'info_backup.txt')\n delete_folder(data_folder)\n assert not os.path.exists(data_folder)\n\n # 测试用例7: 尝试读取已删除的文件\n def test_read_deleted_folder(self, capsys):\n data_folder = 'data'\n info_file_path = os.path.join(data_folder, 'info.txt')\n backup_folder = 'backup'\n info_backup_path = os.path.join(backup_folder, 'info_backup.txt')\n # 删除文件\n os.remove(info_file_path)\n\n # 尝试读取已删除的文件\n with pytest.raises(FileNotFoundError):\n read_and_print_file(info_file_path)\n\n captured = capsys.readouterr()\n assert \"FileNotFoundError\" != str(captured.err)\n\n # 测试用例8: 尝试删除已删除的文件夹\n def test_delete_deleted_folder(self):\n data_folder = 'data'\n info_file_path = os.path.join(data_folder, 'info.txt')\n backup_folder = 'backup'\n info_backup_path = os.path.join(backup_folder, 'info_backup.txt')\n delete_folder(data_folder)\n assert not os.path.exists(data_folder)\n\n # 使用 os.path.exists 检查文件夹是否不存在\n assert not os.path.exists(data_folder)\n\n # 预先设置测试环境\n @pytest.fixture(autouse=True)\n def setup_teardown(self):\n data_folder = 'data'\n info_file_path = os.path.join(data_folder, 'info.txt')\n backup_folder = 'backup'\n info_backup_path = os.path.join(backup_folder, 'info_backup.txt')\n create_folder(data_folder)\n create_and_write_file(info_file_path, \"Test content\")\n create_folder(backup_folder)\n\n yield\n\n # 清理测试环境\n if os.path.exists(data_folder):\n shutil.rmtree(data_folder)\n if os.path.exists(backup_folder):\n shutil.rmtree(backup_folder)\n\n", "setup_code": "", "reference_solution": "```python\nimport os\nimport shutil\n\ndef create_folder(folder_name):\n if not os.path.exists(folder_name):\n os.makedirs(folder_name)\n print(f'Folder {folder_name} created.')\n\ndef create_and_write_file(file_path, content):\n with open(file_path, 'w', encoding='utf-8') as file:\n file.write(content)\n print(f'File {file_path} created and written.')\n\ndef read_and_print_file(file_path):\n with open(file_path, 'r', encoding='utf-8') as file:\n content = file.read()\n print(f'Contents of {file_path}:')\n print(content)\n\ndef copy_file(source_path, destination_path):\n shutil.copy(source_path, destination_path)\n print(f'File {source_path} copied to {destination_path}.')\n\ndef move_file(source_path, destination_path):\n shutil.move(source_path, destination_path)\n print(f'File {source_path} moved to {destination_path}.')\n\ndef delete_folder(folder_name):\n shutil.rmtree(folder_name)\n print(f'Folder {folder_name} and its contents deleted.')\n\n```", "classification": "Operation System"}
{"_id": 149, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nWrite a Python program that accepts a text string as input and uses a regular expression pattern to extract phone numbers from it.\n\nA regular expression pattern is created using re.compile, which is used to match phone numbers. A function named extract_phone_numbers is defined, where the expression: \\(? matches an optional left parenthesis, \\b represents a word boundary, (\\d{3}) matches three digits as the area code, [-.\\s]? matches an optional separator (including hyphen, dot, or space), (\\d{3}) matches three digits as the middle part, also matches an optional separator, (\\d{4}) matches four digits as the end, \\b represents a word boundary.\n\nA finditer method is defined, using pattern.finditer(text) to call the finditer method, returning an iterator that contains all objects matching the pattern.\n\nExtracting and formatting phone numbers:\nIterate through each match object in the matches iterator.\nFor each match object, use match.groups() to get the match groups, i.e., the area code, middle part, and end.\nUse these components to format the phone number in the form of \"(XXX) YYY-ZZZZ\".\nResult storage:\nAdd the formatted phone numbers to the phone_numbers list.\nReturn a list containing all extracted phone numbers. For example, example_text = \"\"\"\nContact List:\n- Alice: (123) 456-7890\n- Bob: 987-654-3210\n- Charlie: (555) 123-4567\n- David: 123.456.7890\n\"\"\"\n\n# Extract phone numbers\nphone_numbers = extract_phone_numbers(example_text)\n\n# Print extracted phone numbers\nprint(\"Extracted Phone Numbers:\")\nfor number in phone_numbers:\n print(number) In this example, example_text contains some phone numbers in different formats. The extract_phone_numbers function is called to extract and format these phone numbers, then the extracted phone numbers are printed out.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testextract_phone_numbers:\n def test_valid_format_with_parentheses(self):\n text = \"联系我们:(123) 456-7890 或者 123-456-7890。\"\n result = extract_phone_numbers(text)\n assert result == ['(123) 456-7890', '(123) 456-7890']\n\n", "problem": "Write a Python program that accepts a text string as input and uses a regular expression pattern to extract phone numbers from it.\n\nA regular expression pattern is created using re.compile, which is used to match phone numbers. A function named extract_phone_numbers is defined, where the expression: \\(? matches an optional left parenthesis, \\b represents a word boundary, (\\d{3}) matches three digits as the area code, [-.\\s]? matches an optional separator (including hyphen, dot, or space), (\\d{3}) matches three digits as the middle part, also matches an optional separator, (\\d{4}) matches four digits as the end, \\b represents a word boundary.\n\nA finditer method is defined, using pattern.finditer(text) to call the finditer method, returning an iterator that contains all objects matching the pattern.\n\nExtracting and formatting phone numbers:\nIterate through each match object in the matches iterator.\nFor each match object, use match.groups() to get the match groups, i.e., the area code, middle part, and end.\nUse these components to format the phone number in the form of \"(XXX) YYY-ZZZZ\".\nResult storage:\nAdd the formatted phone numbers to the phone_numbers list.\nReturn a list containing all extracted phone numbers. For example, example_text = \"\"\"\nContact List:\n- Alice: (123) 456-7890\n- Bob: 987-654-3210\n- Charlie: (555) 123-4567\n- David: 123.456.7890\n\"\"\"\n\n# Extract phone numbers\nphone_numbers = extract_phone_numbers(example_text)\n\n# Print extracted phone numbers\nprint(\"Extracted Phone Numbers:\")\nfor number in phone_numbers:\n print(number) In this example, example_text contains some phone numbers in different formats. The extract_phone_numbers function is called to extract and format these phone numbers, then the extracted phone numbers are printed out.", "testcases": "import re\n\n\nclass Testextract_phone_numbers:\n def test_valid_format_with_dashes_and_dots(self):\n text = \"请拨打电话:123.456.7890 或者 987-654-3210。\"\n result = extract_phone_numbers(text)\n assert result == ['(123) 456-7890', '(987) 654-3210']\n\n def test_no_phone_numbers(self):\n text = \"这段文本中没有电话号码。\"\n result = extract_phone_numbers(text)\n assert result == []\n\n def test_invalid_format_should_not_match(self):\n text = \"无效的号码 (123) 45-67890 不应匹配。\"\n result = extract_phone_numbers(text)\n assert result == []\n\n def test_another_invalid_format_should_not_match(self):\n text = \"另一个无效的号码 1234-567-890 不应匹配。\"\n result = extract_phone_numbers(text)\n assert result == []\n\n def test_incomplete_number_should_not_match(self):\n text = \"不完整的号码 (123) 456 不应匹配。\"\n result = extract_phone_numbers(text)\n assert result == []\n\n def test_valid_number_with_extra_text(self):\n text = \"有效号码 111-222-3333 附带额外文本。\"\n result = extract_phone_numbers(text)\n assert result == ['(111) 222-3333']\n\n def test_multiple_valid_numbers(self):\n text = \"多个有效号码:(111) 222-3333 和 444.555.6666。\"\n result = extract_phone_numbers(text)\n assert result == ['(111) 222-3333', '(444) 555-6666']\n", "setup_code": "", "reference_solution": "```python\nimport re\n\n\ndef extract_phone_numbers(text):\n # 电话号码的正则表达式模式\n pattern = re.compile(r'\\(?\\b(\\d{3})\\)?[-.\\s]?(\\d{3})[-.\\s]?(\\d{4})\\b')\n\n # 使用 finditer 方法提取所有匹配的电话号码\n matches = pattern.finditer(text)\n\n # 存储提取到的电话号码\n phone_numbers = []\n\n for match in matches:\n # 获取匹配对象的匹配组\n groups = match.groups()\n\n # 格式化提取到的电话号码\n formatted_number = f\"({groups[0]}) {groups[1]}-{groups[2]}\"\n\n # 添加到结果列表\n phone_numbers.append(formatted_number)\n\n return phone_numbers\n\n\n```", "classification": "Software Engineering"}
{"_id": 150, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nWrite a Python program named find_max_eigenvalues that calculates the maximum eigenvalues and corresponding eigenvectors of a two-dimensional matrix. The input parameters include a two-dimensional array matrix and an optional parameter `num_largest` (default value is 5), which is used to specify the number of maximum eigenvalues to be extracted. The program returns two lists, the first list is the eigenvalue list, and the second list is the corresponding eigenvector list. The program uses the NumPy and SciPy libraries for calculations. If the input matrix is empty or incorrectly formatted, the program will throw a ValueError. For example, for the input matrix: [[1, 2, 3], [4, 5, 6], [7, 8, 9]], and `num_largest` set to 2, the program should return the following results: Eigenvalue list: [18.8302358, -0.67276795], corresponding eigenvector list: [[-0.40962667, -0.54264865, -0.73330651], [0.43402538, -0.82296167, 0.36654613]]. Here, the first eigenvector [-0.40962667, -0.54264865, -0.73330651] corresponds to the maximum eigenvalue 18.8302358, and the second eigenvector [0.43402538, -0.82296167, 0.36654613] corresponds to the second largest eigenvalue -0.67276795.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testcalculate_eigen:\n def test_calculate_eigen_default(self):\n test_matrix = np.array([[1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25]])\n\n largest_eigenvalues, largest_eigenvectors = calculate_eigen(test_matrix)\n assert len(largest_eigenvalues) == 5\n assert largest_eigenvalues[0] < largest_eigenvalues[-1]\n\n", "problem": "Write a Python program named find_max_eigenvalues that calculates the maximum eigenvalues and corresponding eigenvectors of a two-dimensional matrix. The input parameters include a two-dimensional array matrix and an optional parameter `num_largest` (default value is 5), which is used to specify the number of maximum eigenvalues to be extracted. The program returns two lists, the first list is the eigenvalue list, and the second list is the corresponding eigenvector list. The program uses the NumPy and SciPy libraries for calculations. If the input matrix is empty or incorrectly formatted, the program will throw a ValueError. For example, for the input matrix: [[1, 2, 3], [4, 5, 6], [7, 8, 9]], and `num_largest` set to 2, the program should return the following results: Eigenvalue list: [18.8302358, -0.67276795], corresponding eigenvector list: [[-0.40962667, -0.54264865, -0.73330651], [0.43402538, -0.82296167, 0.36654613]]. Here, the first eigenvector [-0.40962667, -0.54264865, -0.73330651] corresponds to the maximum eigenvalue 18.8302358, and the second eigenvector [0.43402538, -0.82296167, 0.36654613] corresponds to the second largest eigenvalue -0.67276795.", "testcases": "import numpy as np\nfrom scipy.linalg import eig\n\n\nclass Testcalculate_eigen:\n def test_calculate_eigen_custom(self):\n test_matrix = np.array([[1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25]])\n\n largest_eigenvalues, largest_eigenvectors = calculate_eigen(test_matrix, num_largest=3)\n assert len(largest_eigenvalues) == 3\n assert largest_eigenvalues[0] < largest_eigenvalues[-1]\n\n def test_calculate_eigen_non_square_matrix(self):\n non_square_matrix = np.array([[1, 2, 3], [4, 5, 6]])\n with pytest.raises(ValueError):\n calculate_eigen(non_square_matrix)\n\n def test_calculate_eigen_empty_matrix(self):\n empty_matrix = np.array([])\n with pytest.raises(ValueError):\n calculate_eigen(empty_matrix)\n\n def test_calculate_eigen_large_matrix(self):\n large_matrix = np.random.rand(100, 100)\n largest_eigenvalues, _ = calculate_eigen(large_matrix, num_largest=10)\n assert len(largest_eigenvalues) == 10\n assert largest_eigenvalues[0] < largest_eigenvalues[-1]\n\n def test_calculate_eigen_negative_values(self):\n negative_matrix = np.array([[1, -2, 3], [-4, 5, -6], [7, -8, 9]])\n largest_eigenvalues, _ = calculate_eigen(negative_matrix)\n assert np.all(np.real(largest_eigenvalues) != 0)\n", "setup_code": "", "reference_solution": "```python\nimport numpy as np\nfrom scipy.linalg import eig\n\n\ndef calculate_eigen(matrix, num_largest=5):\n # 计算特征值和特征向量\n eigenvalues, eigenvectors = eig(matrix)\n\n # 找到最大的几个特征值及其对应的索引\n largest_indices = np.argsort(eigenvalues)[-num_largest:]\n\n # 提取最大的几个特征值和对应的特征向量\n largest_eigenvalues = eigenvalues[largest_indices]\n largest_eigenvectors = eigenvectors[:, largest_indices]\n\n return largest_eigenvalues, largest_eigenvectors\n\n```", "classification": "Data Science"}
{"_id": 151, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nWrite a Python program to flatten a nested list into a one-dimensional list. Define a function called flatten_list to flatten the nested list into a one-dimensional list, and the return value is the flattened_list after flattening. \nCreate an empty list flattened_list to store the elements after flattening. \nCreate a stack stack, and push the initial nested list nested_list into the stack. \nUse a loop to iterate until the stack is empty. \nIn each iteration, pop the current list current from the stack. \nFor each element in current, check its type: \nIf it is a list, push the list into the stack for subsequent flattening. \nIf it is not a list, add the element to flattened_list. \nThe loop continues until the stack is empty, and finally get the flattened list. \nReturn the flattened list flattened_list. For example, \n# Define the nested list\nnested_list = [1, [2, 3, [4, 5]], 6, [7, [8, 9]]]\n\n# Use the flatten_list function to flatten the list\nflattened_list = flatten_list(nested_list)\n\n# Print the result after flattening\nprint(flattened_list)\nIn this example, nested_list contains nested sublists. By calling the flatten_list function, it is flattened into a one-dimensional list flattened_list.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testflatten_list:\n def test_flatten_list_empty(self):\n assert flatten_list([]) == []\n\n", "problem": "Write a Python program to flatten a nested list into a one-dimensional list. Define a function called flatten_list to flatten the nested list into a one-dimensional list, and the return value is the flattened_list after flattening. \nCreate an empty list flattened_list to store the elements after flattening. \nCreate a stack stack, and push the initial nested list nested_list into the stack. \nUse a loop to iterate until the stack is empty. \nIn each iteration, pop the current list current from the stack. \nFor each element in current, check its type: \nIf it is a list, push the list into the stack for subsequent flattening. \nIf it is not a list, add the element to flattened_list. \nThe loop continues until the stack is empty, and finally get the flattened list. \nReturn the flattened list flattened_list. For example, \n# Define the nested list\nnested_list = [1, [2, 3, [4, 5]], 6, [7, [8, 9]]]\n\n# Use the flatten_list function to flatten the list\nflattened_list = flatten_list(nested_list)\n\n# Print the result after flattening\nprint(flattened_list)\nIn this example, nested_list contains nested sublists. By calling the flatten_list function, it is flattened into a one-dimensional list flattened_list.", "testcases": "\n\nclass Testflatten_list:\n def test_flatten_list_single_level(self):\n input_nested_list = [1, 2, 3, 4]\n assert flatten_list(input_nested_list) == [1, 2, 3, 4]\n\n def test_flatten_list_nested(self):\n input_nested_list = [[1, 2, [3, 4]], [5, [6, 7]]]\n assert flatten_list(input_nested_list) == [5, 6, 7, 1, 2, 3, 4]\n\n def test_flatten_list_nested_empty(self):\n input_nested_list = [[], [1, [2, 3], []], []]\n assert flatten_list(input_nested_list) == [1, 2, 3]\n\n def test_flatten_list_nested_strings(self):\n input_nested_list = [['a', 'b', ['c', 'd']], ['e', ['f', 'g']]]\n assert flatten_list(input_nested_list) == ['e', 'f', 'g', 'a', 'b', 'c', 'd']\n\n def test_flatten_list_mixed_types(self):\n input_nested_list = [1, 'a', [2, 'b', [3, 'c']], [4, 'd']]\n assert flatten_list(input_nested_list) == [1, 'a', 4, 'd', 2, 'b', 3, 'c']\n\n def test_flatten_list_nested_floats(self):\n input_nested_list = [1.0, [2.5, [3.2, 4.8]], 5.6, [7.3, [8.1, 9.0]]]\n assert flatten_list(input_nested_list) == [1.0, 5.6, 7.3, 8.1, 9.0, 2.5, 3.2, 4.8]\n\n def test_flatten_list_nested_booleans(self):\n input_nested_list = [True, [False, [True, False]], True, [False, True]]\n assert flatten_list(input_nested_list) == [True, True, False, True, False, True, False]\n", "setup_code": "", "reference_solution": "```python\ndef flatten_list(nested_list):\n flattened_list = []\n stack = [nested_list]\n\n while stack:\n current = stack.pop()\n\n for element in current:\n if isinstance(element, list):\n stack.append(element)\n else:\n flattened_list.append(element)\n\n return flattened_list\n\n\n```", "classification": "Algorithm and Data Structure"}
{"_id": 152, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nThe list elements in the txt file are separated by tabs, convert the contents into an Excel spreadsheet.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testtxt2excle:\n def test_txt2excle_1(self, tmp_path):\n file_path = tmp_path / \"test1.txt\"\n file_path.write_text(\"1\\t2\\t3\\n4\\t5\\t6\")\n txt2excle(file_path)\n workbook = openpyxl.load_workbook('output.xlsx')\n sheet = workbook.active\n assert sheet['A1'].value == '1'\n assert sheet['B1'].value == '2'\n assert sheet['C1'].value == '3'\n assert sheet['A2'].value == '4'\n assert sheet['B2'].value == '5'\n assert sheet['C2'].value == '6'\n\n", "problem": "The list elements in the txt file are separated by tabs, convert the contents into an Excel spreadsheet.", "testcases": "import openpyxl\n\nclass Testtxt2excle:\n def test_txt2excle_2(self, tmp_path):\n file_path = tmp_path / \"test2.txt\"\n file_path.write_text(\"apple\\tbanana\\tcherry\")\n txt2excle(file_path)\n workbook = openpyxl.load_workbook('output.xlsx')\n sheet = workbook.active\n assert sheet['A1'].value == 'apple'\n assert sheet['B1'].value == 'banana'\n assert sheet['C1'].value == 'cherry'\n\n def test_txt2excle_3(self, tmp_path):\n file_path = tmp_path / \"test3.txt\"\n file_path.write_text(\"100\\t200\\t300\\t400\\t500\")\n txt2excle(file_path)\n workbook = openpyxl.load_workbook('output.xlsx')\n sheet = workbook.active\n assert sheet['A1'].value == '100'\n assert sheet['B1'].value == '200'\n assert sheet['C1'].value == '300'\n assert sheet['D1'].value == '400'\n assert sheet['E1'].value == '500'\n\n def test_txt2excle_4(self, tmp_path):\n file_path = tmp_path / \"test4.txt\"\n file_path.write_text(\"a\\tb\\tc\\nd\\te\\tf\")\n txt2excle(file_path)\n workbook = openpyxl.load_workbook('output.xlsx')\n sheet = workbook.active\n assert sheet['A1'].value == 'a'\n assert sheet['B1'].value == 'b'\n assert sheet['C1'].value == 'c'\n assert sheet['A2'].value == 'd'\n assert sheet['B2'].value == 'e'\n assert sheet['C2'].value == 'f'\n\n def test_txt2excle_5(self, tmp_path):\n file_path = tmp_path / \"test5.txt\"\n file_path.write_text(\"1.1\\t2.2\\t3.3\")\n txt2excle(file_path)\n workbook = openpyxl.load_workbook('output.xlsx')\n sheet = workbook.active\n assert sheet['A1'].value == '1.1'\n assert sheet['B1'].value == '2.2'\n assert sheet['C1'].value == '3.3'\n\n def test_txt2excle_6(self, tmp_path):\n file_path = tmp_path / \"test6.txt\"\n file_path.write_text(\"True\\tFalse\")\n txt2excle(file_path)\n workbook = openpyxl.load_workbook('output.xlsx')\n sheet = workbook.active\n assert sheet['A1'].value == 'True'\n assert sheet['B1'].value == 'False'\n\n def test_txt2excle_7(self, tmp_path):\n file_path = tmp_path / \"test7.txt\"\n file_path.write_text(\"\")\n txt2excle(file_path)\n workbook = openpyxl.load_workbook('output.xlsx')\n sheet = workbook.active\n assert sheet['A1'].value == None\n\n def test_txt2excle_8(self, tmp_path):\n file_path = tmp_path / \"test8.txt\"\n file_path.write_text(\"\\t\\t\\t\")\n txt2excle(file_path)\n workbook = openpyxl.load_workbook('output.xlsx')\n sheet = workbook.active\n assert sheet['A1'].value == None\n assert sheet['B1'].value == None\n assert sheet['C1'].value == None\n\n def test_txt2excle_9(self, tmp_path):\n file_path = tmp_path / \"test9.txt\"\n file_path.write_text(\"a\\tb\\tc\\nd\\te\\tf\\ng\\th\\ti\")\n txt2excle(file_path)\n workbook = openpyxl.load_workbook('output.xlsx')\n sheet = workbook.active\n assert sheet['A3'].value == 'g'\n assert sheet['B3'].value == 'h'\n assert sheet['C3'].value == 'i'\n\n def test_txt2excle_10(self, tmp_path):\n file_path = tmp_path / \"test10.txt\"\n file_path.write_text(\"1\\t2\\t3\\n4\\t5\\t6\\n7\\t8\\t9\")\n txt2excle(file_path)\n workbook = openpyxl.load_workbook('output.xlsx')\n sheet = workbook.active\n assert sheet['A3'].value == '7'\n assert sheet['B3'].value == '8'\n assert sheet['C3'].value == '9'", "setup_code": "", "reference_solution": "```python\nimport openpyxl\n# 打开txt文件\n\ndef txt2excle(file_path):\n with open(file_path, 'r') as file:\n lines = file.readlines()\n\n # 创建Excel工作簿\n workbook = openpyxl.Workbook()\n sheet = workbook.active\n\n # 将列表数据写入Excel工作表\n for row, line in enumerate(lines, start=1):\n # 假设列表中的元素使用逗号进行分隔\n elements = line.strip().split('\\t')\n for col, element in enumerate(elements, start=1):\n sheet.cell(row=row, column=col).value = element\n\n # 保存为Excel文件\n workbook.save('output.xlsx')\n\n```", "classification": "Data Science"}
{"_id": 153, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nUse Python, the label data is in VOC format, implement the division of the real box labels with an IoU greater than 0.2 in the given area into category 0.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testconvert_labels:\n def test_convert_labels_1(self, tmp_path):\n d = tmp_path / \"sub\"\n d.mkdir()\n p = d / \"label.xml\"\n p.write_text('<annotation><object><bndbox><xmin>950</xmin><ymin>786</ymin><xmax>1400</xmax><ymax>1052</ymax></bndbox><name>1</name></object></annotation>')\n convert_labels(str(p), (950,786,1400,1052))\n tree = ET.parse(str(p))\n root = tree.getroot()\n assert root.find('object').find('name').text == '0'\n\n", "problem": "Use Python, the label data is in VOC format, implement the division of the real box labels with an IoU greater than 0.2 in the given area into category 0.", "testcases": "import xml.etree.ElementTree as ET\n\n\nclass Testconvert_labels:\n def test_convert_labels_2(self, tmp_path):\n d = tmp_path / \"sub\"\n d.mkdir()\n p = d / \"label.xml\"\n p.write_text('<annotation><object><bndbox><xmin>0</xmin><ymin>0</ymin><xmax>2</xmax><ymax>2</ymax></bndbox><name>1</name></object></annotation>')\n convert_labels(str(p), (1,1,3,3))\n tree = ET.parse(str(p))\n root = tree.getroot()\n assert root.find('object').find('name').text == '0'\n\n def test_convert_labels_3(self, tmp_path):\n d = tmp_path / \"sub\"\n d.mkdir()\n p = d / \"label.xml\"\n p.write_text('<annotation><object><bndbox><xmin>0</xmin><ymin>0</ymin><xmax>2</xmax><ymax>2</ymax></bndbox><name>1</name></object></annotation>')\n convert_labels(str(p), (2,2,4,4))\n tree = ET.parse(str(p))\n root = tree.getroot()\n assert root.find('object').find('name').text == '1'\n\n def test_convert_labels_4(self, tmp_path):\n d = tmp_path / \"sub\"\n d.mkdir()\n p = d / \"label.xml\"\n p.write_text('<annotation><object><bndbox><xmin>0</xmin><ymin>0</ymin><xmax>2</xmax><ymax>2</ymax></bndbox><name>1</name></object></annotation>')\n convert_labels(str(p), (0,0,2,2))\n tree = ET.parse(str(p))\n root = tree.getroot()\n assert root.find('object').find('name').text == '0'\n\n def test_convert_labels_5(self, tmp_path):\n d = tmp_path / \"sub\"\n d.mkdir()\n p = d / \"label.xml\"\n p.write_text('<annotation><object><bndbox><xmin>1000</xmin><ymin>800</ymin><xmax>1300</xmax><ymax>1000</ymax></bndbox><name>1</name></object></annotation>')\n convert_labels(str(p), (950,786,1400,1052))\n tree = ET.parse(str(p))\n root = tree.getroot()\n assert root.find('object').find('name').text == '0'\n\n def test_convert_labels_6(self, tmp_path):\n d = tmp_path / \"sub\"\n d.mkdir()\n p = d / \"label.xml\"\n p.write_text('<annotation><object><bndbox><xmin>900</xmin><ymin>750</ymin><xmax>1450</xmax><ymax>1100</ymax></bndbox><name>1</name></object></annotation>')\n convert_labels(str(p), (950,786,1400,1052))\n tree = ET.parse(str(p))\n root = tree.getroot()\n assert root.find('object').find('name').text == '0'\n\n def test_convert_labels_7(self, tmp_path):\n d = tmp_path / \"sub\"\n d.mkdir()\n p = d / \"label.xml\"\n p.write_text('<annotation><object><bndbox><xmin>950</xmin><ymin>786</ymin><xmax>1400</xmax><ymax>1052</ymax></bndbox><name>2</name></object></annotation>')\n convert_labels(str(p), (950,786,1400,1052))\n tree = ET.parse(str(p))\n root = tree.getroot()\n assert root.find('object').find('name').text == '0'", "setup_code": "", "reference_solution": "```python\nimport xml.etree.ElementTree as ET\n \ndef calculate_iou(box1, box2):\n \"\"\"\n 计算两个边界框之间的IoU\n \"\"\"\n x1, y1, x2, y2 = box1\n x3, y3, x4, y4 = box2\n\n # 计算相交矩形的左上角和右下角坐标\n inter_x1 = max(x1, x3)\n inter_y1 = max(y1, y3)\n inter_x2 = min(x2, x4)\n inter_y2 = min(y2, y4)\n\n # 计算相交矩形的面积\n inter_area = max(0, inter_x2 - inter_x1 + 1) * max(0, inter_y2 - inter_y1 + 1)\n\n # 计算并集面积和IoU\n box1_area = (x2 - x1 + 1) * (y2 - y1 + 1)\n box2_area = (x4 - x3 + 1) * (y4 - y3 + 1)\n union_area = box1_area + box2_area - inter_area\n iou = inter_area / union_area\n\n return iou\n\ndef convert_labels(label_file, target_region):\n \"\"\"\n 将在目标区域内与真实框标签的IoU大于0.2的所有框标签划分为类别0\n \"\"\"\n tree = ET.parse(label_file)\n root = tree.getroot()\n\n for object_elem in root.findall('object'):\n bbox = object_elem.find('bndbox')\n xmin = int(bbox.find('xmin').text)\n ymin = int(bbox.find('ymin').text)\n xmax = int(bbox.find('xmax').text)\n ymax = int(bbox.find('ymax').text)\n\n # 计算当前边界框与目标区域的IoU\n iou = calculate_iou(target_region, (xmin, ymin, xmax, ymax))\n\n # 如果IoU大于0.2,则将类别设置为0\n if iou > 0.2:\n object_elem.find('name').text = '0'\n\n tree.write(label_file)\n\n```", "classification": "Artificial Intelligence"}
{"_id": 154, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nDivide the image classification dataset into training set, test set, and validation set, with the random seed set at 42.\nThe input is the path of the image folder, and the ratio of dividing the training set, test set, and validation set.\nThe output is the folder of the training set, test set, and validation set, and the output folder is directly placed in the dataset directory.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testsplit_data:\n def test_split_data_1(self):\n dataset_path = 'test1'\n file_num = len(os.listdir(dataset_path))\n train_ratio = 0.7\n test_ratio = 0.2\n val_ratio = 0.1\n split_data(dataset_path,train_ratio,test_ratio,val_ratio)\n assert len(os.listdir(os.path.join(dataset_path,'train'))) == file_num * train_ratio\n assert len(os.listdir(os.path.join(dataset_path,'test'))) == file_num * test_ratio\n assert len(os.listdir(os.path.join(dataset_path,'val'))) == file_num * val_ratio\n\n", "problem": "Divide the image classification dataset into training set, test set, and validation set, with the random seed set at 42.\nThe input is the path of the image folder, and the ratio of dividing the training set, test set, and validation set.\nThe output is the folder of the training set, test set, and validation set, and the output folder is directly placed in the dataset directory.", "testcases": "import os\nimport random\nimport shutil\n\nclass Testsplit_data:\n def test_split_data_2(self):\n dataset_path = 'test2'\n file_num = len(os.listdir(dataset_path))\n train_ratio = 1\n test_ratio = 0\n val_ratio = 0\n split_data(dataset_path,train_ratio,test_ratio,val_ratio)\n assert len(os.listdir(os.path.join(dataset_path, 'train'))) == file_num * train_ratio\n assert len(os.listdir(os.path.join(dataset_path, 'test'))) == file_num * test_ratio\n assert len(os.listdir(os.path.join(dataset_path, 'val'))) == file_num * val_ratio\n\n def test_split_data_3(self):\n dataset_path = 'test3'\n file_num = len(os.listdir(dataset_path))\n train_ratio = 0\n test_ratio = 1\n val_ratio = 0\n split_data(dataset_path,train_ratio,test_ratio,val_ratio)\n assert len(os.listdir(os.path.join(dataset_path,'train'))) == file_num * train_ratio\n assert len(os.listdir(os.path.join(dataset_path,'test'))) == file_num * test_ratio\n assert len(os.listdir(os.path.join(dataset_path,'val'))) == file_num * val_ratio\n\n def test_split_data_4(self):\n dataset_path = 'test4'\n file_num = len(os.listdir(dataset_path))\n train_ratio = 0\n test_ratio = 0\n val_ratio = 1\n split_data(dataset_path,train_ratio,test_ratio,val_ratio)\n assert len(os.listdir(os.path.join(dataset_path,'train'))) == file_num * train_ratio\n assert len(os.listdir(os.path.join(dataset_path,'test'))) == file_num * test_ratio\n assert len(os.listdir(os.path.join(dataset_path,'val'))) == file_num * val_ratio\n\n def test_split_data_5(self):\n dataset_path = 'test5'\n file_num = len(os.listdir(dataset_path))\n train_ratio = 0.6\n test_ratio = 0.3\n val_ratio = 0.1\n split_data(dataset_path,train_ratio,test_ratio,val_ratio)\n assert len(os.listdir(os.path.join(dataset_path,'train'))) == file_num * train_ratio\n assert len(os.listdir(os.path.join(dataset_path,'test'))) == file_num * test_ratio\n assert len(os.listdir(os.path.join(dataset_path,'val'))) == file_num * val_ratio\n\n def test_split_data_6(self):\n dataset_path = 'test6'\n file_num = len(os.listdir(dataset_path))\n train_ratio = 0.6\n test_ratio = 0.2\n val_ratio = 0.2\n split_data(dataset_path,train_ratio,test_ratio,val_ratio)\n assert len(os.listdir(os.path.join(dataset_path,'train'))) == file_num * train_ratio\n assert len(os.listdir(os.path.join(dataset_path,'test'))) == file_num * test_ratio\n assert len(os.listdir(os.path.join(dataset_path,'val'))) == file_num * val_ratio\n", "setup_code": "", "reference_solution": "```python\nimport os\nimport random\nimport shutil\n\n\ndef split_data(dataset_path,train_ratio,test_ratio,val_ratio):\n # 设置随机种子\n random_seed = 42\n random.seed(random_seed)\n train_path = os.path.join(dataset_path,'train')\n test_path = os.path.join(dataset_path,'test')\n val_path = os.path.join(dataset_path,'val')\n\n if not os.path.exists(train_path):\n os.makedirs(train_path)\n\n if not os.path.exists(test_path):\n os.makedirs(test_path)\n\n if not os.path.exists(val_path):\n os.makedirs(val_path)\n\n image_files = [f for f in os.listdir(dataset_path) if f.endswith('.jpg')]\n\n # 随机打乱图像文件列表\n random.shuffle(image_files)\n\n # 计算划分的索引位置\n train_split = int(len(image_files) * train_ratio)\n test_split = int(len(image_files) * (train_ratio + test_ratio))\n\n # 划分训练集\n train_files = image_files[:train_split]\n for file in train_files:\n src_path = os.path.join(dataset_path, file)\n dest_path = os.path.join(train_path, file)\n shutil.copy(src_path, dest_path)\n\n # 划分测试集\n test_files = image_files[train_split:test_split]\n for file in test_files:\n src_path = os.path.join(dataset_path, file)\n dest_path = os.path.join(test_path, file)\n shutil.copy(src_path, dest_path)\n\n # 划分验证集\n val_files = image_files[test_split:]\n for file in val_files:\n src_path = os.path.join(dataset_path, file)\n dest_path = os.path.join(val_path, file)\n shutil.copy(src_path, dest_path)\n\n\n# import os\n# import shutil\n# from sklearn.model_selection import train_test_split\n\n\n# def split_data(dataset_path, train_ratio, test_ratio, val_ratio):\n# # 获取所有文件的路径\n# files = [os.path.join(dataset_path, f) for f in os.listdir(dataset_path) if\n# os.path.isfile(os.path.join(dataset_path, f))]\n#\n# # 划分训练集和其余部分\n# train_files, rest_files = train_test_split(files, train_size=train_ratio, random_state=42)\n#\n# # 计算测试集的比例\n# test_ratio_adjusted = test_ratio / (1 - train_ratio)\n#\n# # 划分测试集和验证集\n# test_files, val_files = train_test_split(rest_files, test_size=test_ratio_adjusted, random_state=42)\n#\n# # 创建训练集、测试集和验证集的文件夹\n# train_dir = os.path.join(dataset_path, 'train')\n# test_dir = os.path.join(dataset_path, 'test')\n# val_dir = os.path.join(dataset_path, 'val')\n# os.makedirs(train_dir, exist_ok=True)\n# os.makedirs(test_dir, exist_ok=True)\n# os.makedirs(val_dir, exist_ok=True)\n#\n# # 将文件移动到对应的文件夹\n# for f in train_files:\n# shutil.move(f, os.path.join(train_dir, os.path.basename(f)))\n# for f in test_files:\n# shutil.move(f, os.path.join(test_dir, os.path.basename(f)))\n# for f in val_files:\n# shutil.move(f, os.path.join(val_dir, os.path.basename(f)))\n```", "classification": "Artificial Intelligence"}
{"_id": 155, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nImplement Hinge loss with numpy.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testhinge_loss:\n def test_hinge_loss_1(self):\n assert np.isclose(hinge_loss(np.array([1, -1, 1]), np.array([1, -1, 1])), 0.0)\n\n", "problem": "Implement Hinge loss with numpy.", "testcases": "import numpy as np\n\n\nclass Testhinge_loss:\n def test_hinge_loss_2(self):\n assert np.isclose(hinge_loss(np.array([-1, -1, -1]), np.array([1, 1, 1])), 2.0)\n\n def test_hinge_loss_3(self):\n assert np.isclose(hinge_loss(np.array([1, 1, 1]), np.array([-1, -1, -1])), 2.0)\n\n def test_hinge_loss_4(self):\n assert np.isclose(hinge_loss(np.array([1, -1, 1]), np.array([-1, 1, -1])), 2.0)\n\n def test_hinge_loss_5(self):\n assert np.isclose(hinge_loss(np.array([1, 1, 1]), np.array([0.5, 0.5, 0.5])), 0.5)\n\n def test_hinge_loss_6(self):\n assert np.isclose(hinge_loss(np.array([-1, -1, -1]), np.array([-0.5, -0.5, -0.5])), 0.5)\n\n def test_hinge_loss_7(self):\n assert np.isclose(hinge_loss(np.array([1]), np.array([1])), 0.0)\n\n def test_hinge_loss_8(self):\n assert np.isclose(hinge_loss(np.array([-1]), np.array([1])), 2.0)\n\n def test_hinge_loss_9(self):\n assert np.isclose(hinge_loss(np.array([1]), np.array([-1])), 2.0)\n\n def test_hinge_loss_10(self):\n assert np.isclose(hinge_loss(np.array([-1]), np.array([-1])), 0.0)", "setup_code": "", "reference_solution": "```python\nimport numpy as np\n\ndef hinge_loss(y_true, y_pred):\n return np.mean(np.maximum(0, 1 - y_true * y_pred))\n\n```", "classification": "Artificial Intelligence"}
{"_id": 156, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nIn the field of image processing, there are abnormal blank lines in the annotation files of the YOLO format dataset, which need to be deleted. Input: The folder path of the YOLO format dataset annotation file.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testremove_empty_lines_folder:\n def test_remove_empty_lines_folder_1(self, tmpdir):\n p = tmpdir.mkdir(\"sub\").join(\"test1.txt\")\n p.write(\"0 0.5 0.5 0.5 0.5\\n\\n\\n1 0.5 0.5 0.5 0.5\\n2 0.5 0.5 0.5 0.5\\n\\n3 0.5 0.5 0.5 0.5\\n4 0.5 0.5 0.5 0.5\")\n remove_empty_lines_folder(str(tmpdir / \"sub\"))\n assert p.read() == \"0 0.5 0.5 0.5 0.5\\n1 0.5 0.5 0.5 0.5\\n2 0.5 0.5 0.5 0.5\\n3 0.5 0.5 0.5 0.5\\n4 0.5 0.5 0.5 0.5\"\n\n", "problem": "In the field of image processing, there are abnormal blank lines in the annotation files of the YOLO format dataset, which need to be deleted. Input: The folder path of the YOLO format dataset annotation file.", "testcases": "import os\n\nclass Testremove_empty_lines_folder:\n def test_remove_empty_lines_folder_2(self, tmpdir):\n p = tmpdir.mkdir(\"sub\").join(\"test2.txt\")\n p.write(\"1 0.5 0.5 0.5 0.5\\n2 0.5 0.5 0.5 0.5\\n3 0.5 0.5 0.5 0.5\")\n remove_empty_lines_folder(str(tmpdir / \"sub\"))\n assert p.read() == \"1 0.5 0.5 0.5 0.5\\n2 0.5 0.5 0.5 0.5\\n3 0.5 0.5 0.5 0.5\"\n\n def test_remove_empty_lines_folder_3(self, tmpdir):\n p = tmpdir.mkdir(\"sub\").join(\"test3.txt\")\n p.write(\"0 0.5 0.5 0.5 0.5\\n\\n4 0.5 0.5 0.5 0.5\")\n remove_empty_lines_folder(str(tmpdir / \"sub\"))\n assert p.read() == \"0 0.5 0.5 0.5 0.5\\n4 0.5 0.5 0.5 0.5\"\n\n def test_remove_empty_lines_folder_4(self, tmpdir):\n p = tmpdir.mkdir(\"sub\").join(\"test4.txt\")\n p.write(\"0 0.5 0.5 0.5 0.5\\n1 0.5 0.5 0.5 0.5\\n\\n2 0.5 0.5 0.5 0.5\\n3 0.5 0.5 0.5 0.5\\n4 0.5 0.5 0.5 0.5\\n\")\n remove_empty_lines_folder(str(tmpdir / \"sub\"))\n assert p.read() == \"0 0.5 0.5 0.5 0.5\\n1 0.5 0.5 0.5 0.5\\n2 0.5 0.5 0.5 0.5\\n3 0.5 0.5 0.5 0.5\\n4 0.5 0.5 0.5 0.5\\n\"\n\n def test_remove_empty_lines_folder_5(self, tmpdir):\n p1 = tmpdir.mkdir(\"sub\").join(\"test5-1.txt\")\n p1.write(\"0 0.5 0.5 0.5 0.5\\n\\n\\n1 0.5 0.5 0.5 0.5\\n2 0.5 0.5 0.5 0.5\\n3 0.5 0.5 0.5 0.5\\n4 0.5 0.5 0.5 0.5\")\n p2 = (tmpdir / \"sub\").join(\"test5-2.txt\")\n p2.write(\"0 0.5 0.5 0.5 0.5\\n1 0.5 0.5 0.5 0.5\\n\\n2 0.5 0.5 0.5 0.5\\n3 0.5 0.5 0.5 0.5\\n4 0.5 0.5 0.5 0.5\\n\")\n remove_empty_lines_folder(str(tmpdir / \"sub\"))\n assert p1.read() == \"0 0.5 0.5 0.5 0.5\\n1 0.5 0.5 0.5 0.5\\n2 0.5 0.5 0.5 0.5\\n3 0.5 0.5 0.5 0.5\\n4 0.5 0.5 0.5 0.5\"\n assert p2.read() == \"0 0.5 0.5 0.5 0.5\\n1 0.5 0.5 0.5 0.5\\n2 0.5 0.5 0.5 0.5\\n3 0.5 0.5 0.5 0.5\\n4 0.5 0.5 0.5 0.5\\n\"\n\n def test_remove_empty_lines_folder_6(self, tmpdir):\n p1 = tmpdir.mkdir(\"sub\").join(\"test6-1.txt\")\n p1.write(\"0 0.5 0.5 0.5 0.5\\n1 0.5 0.5 0.5 0.5\\n2 0.5 0.5 0.5 0.5\\n3 0.5 0.5 0.5 0.5\\n4 0.5 0.5 0.5 0.5\\n\")\n p2 = (tmpdir / \"sub\").join(\"test6-2.txt\")\n p2.write(\"0 0.5 0.5 0.5 0.5\\n\\n4 0.5 0.5 0.5 0.5\")\n remove_empty_lines_folder(str(tmpdir / \"sub\"))\n assert p1.read() == \"0 0.5 0.5 0.5 0.5\\n1 0.5 0.5 0.5 0.5\\n2 0.5 0.5 0.5 0.5\\n3 0.5 0.5 0.5 0.5\\n4 0.5 0.5 0.5 0.5\\n\"\n assert p2.read() == \"0 0.5 0.5 0.5 0.5\\n4 0.5 0.5 0.5 0.5\"\n\n def test_remove_empty_lines_folder_7(self, tmpdir):\n p1 = tmpdir.mkdir(\"sub\").join(\"test7-1.txt\")\n p1.write(\"\\n\\n0 0.5 0.5 0.5 0.5\\n1 0.5 0.5 0.5 0.5\\n2 0.5 0.5 0.5 0.5\\n3 0.5 0.5 0.5 0.5\\n\\n4 0.5 0.5 0.5 0.5\")\n p2 = (tmpdir / \"sub\").join(\"test1-2.txt\")\n p2.write(\"0 0.5 0.5 0.5 0.5\\n\\n\\n1 0.5 0.5 0.5 0.5\\n2 0.5 0.5 0.5 0.5\\n\\n3 0.5 0.5 0.5 0.5\\n4 0.5 0.5 0.5 0.5\")\n remove_empty_lines_folder(str(tmpdir / \"sub\"))\n assert p1.read() == \"0 0.5 0.5 0.5 0.5\\n1 0.5 0.5 0.5 0.5\\n2 0.5 0.5 0.5 0.5\\n3 0.5 0.5 0.5 0.5\\n4 0.5 0.5 0.5 0.5\"\n assert p2.read() == \"0 0.5 0.5 0.5 0.5\\n1 0.5 0.5 0.5 0.5\\n2 0.5 0.5 0.5 0.5\\n3 0.5 0.5 0.5 0.5\\n4 0.5 0.5 0.5 0.5\"", "setup_code": "", "reference_solution": "```python\nimport os\n\n\ndef remove_empty_lines_folder(folder_path):\n for file_name in os.listdir(folder_path):\n if file_name.endswith('.txt'):\n file_path = os.path.join(folder_path, file_name)\n remove_empty_lines(file_path)\n\n\ndef remove_empty_lines(file_path):\n with open(file_path, 'r+') as file:\n lines = file.readlines()\n file.seek(0)\n file.truncate()\n for line in lines:\n if line.strip(): # 检查是否为空行\n file.write(line)\n\n# folder_path=r'C:\\Users\\Administrator\\Desktop\\work\\1207-Q17\\yolo\\labels'\n# remove_empty_lines_folder(folder_path)\n\n```", "classification": "Data Science"}
{"_id": 157, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nFilter the category in the annotation files of the yolo format dataset in the field of image processing, only retain the category labels in Label_category, and delete other category labels, operate on the original file. Enter the path of the annotation file folder of the yolo format dataset and the Label_category list.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testlabel_filter:\n def test_label_filter_1(self, tmpdir):\n p = tmpdir.mkdir(\"sub\").join(\"test1.txt\")\n p.write(\"0 0.5 0.5 0.5 0.5\\n1 0.5 0.5 0.5 0.5\\n2 0.5 0.5 0.5 0.5\\n3 0.5 0.5 0.5 0.5\\n4 0.5 0.5 0.5 0.5\")\n label_filter(str(tmpdir / \"sub\"), [1,2,3])\n assert p.read() == \"0 0.5 0.5 0.5 0.5\\n4 0.5 0.5 0.5 0.5\\n\"\n\n", "problem": "Filter the category in the annotation files of the yolo format dataset in the field of image processing, only retain the category labels in Label_category, and delete other category labels, operate on the original file. Enter the path of the annotation file folder of the yolo format dataset and the Label_category list.", "testcases": "import os\n\n\nclass Testlabel_filter:\n def test_label_filter_2(self, tmpdir):\n p = tmpdir.mkdir(\"sub\").join(\"test2.txt\")\n p.write(\"1 0.5 0.5 0.5 0.5\\n2 0.5 0.5 0.5 0.5\\n3 0.5 0.5 0.5 0.5\")\n label_filter(str(tmpdir / \"sub\"), [1,2,3])\n assert p.read() == \"\"\n\n def test_label_filter_3(self, tmpdir):\n p = tmpdir.mkdir(\"sub\").join(\"test3.txt\")\n p.write(\"0 0.5 0.5 0.5 0.5\\n4 0.5 0.5 0.5 0.5\")\n label_filter(str(tmpdir / \"sub\"), [1,2,3])\n assert p.read() == \"0 0.5 0.5 0.5 0.5\\n4 0.5 0.5 0.5 0.5\\n\"\n\n def test_label_filter_4(self, tmpdir):\n p = tmpdir.mkdir(\"sub\").join(\"test4.txt\")\n p.write(\"0 0.5 0.5 0.5 0.5\\n1 0.5 0.5 0.5 0.5\\n2 0.5 0.5 0.5 0.5\\n3 0.5 0.5 0.5 0.5\\n4 0.5 0.5 0.5 0.5\")\n label_filter(str(tmpdir / \"sub\"), [0,4])\n assert p.read() == \"1 0.5 0.5 0.5 0.5\\n2 0.5 0.5 0.5 0.5\\n3 0.5 0.5 0.5 0.5\\n\"\n\n def test_label_filter_5(self, tmpdir):\n p = tmpdir.mkdir(\"sub\").join(\"test5.txt\")\n p.write(\"0 0.5 0.5 0.5 0.5\\n1 0.5 0.5 0.5 0.5\\n2 0.5 0.5 0.5 0.5\\n3 0.5 0.5 0.5 0.5\\n4 0.5 0.5 0.5 0.5\")\n label_filter(str(tmpdir / \"sub\"), [])\n assert p.read() == \"0 0.5 0.5 0.5 0.5\\n1 0.5 0.5 0.5 0.5\\n2 0.5 0.5 0.5 0.5\\n3 0.5 0.5 0.5 0.5\\n4 0.5 0.5 0.5 0.5\\n\"\n\n def test_label_filter_6(self, tmpdir):\n p = tmpdir.mkdir(\"sub\").join(\"test6.txt\")\n p.write(\"0 0.5 0.5 0.5 0.5\\n1 0.5 0.5 0.5 0.5\\n2 0.5 0.5 0.5 0.5\\n3 0.5 0.5 0.5 0.5\\n4 0.5 0.5 0.5 0.5\\n\")\n label_filter(str(tmpdir / \"sub\"), [0,1,2,3,4])\n assert p.read() == \"\"\n\n def test_label_filter_7(self, tmpdir):\n p = tmpdir.mkdir(\"sub\").join(\"test7.txt\")\n p.write(\"0 0.5 0.5 0.5 0.5\\n1 0.5 0.5 0.5 0.5\\n2 0.5 0.5 0.5 0.5\\n3 0.5 0.5 0.5 0.5\\n4 0.5 0.5 0.5 0.5\")\n label_filter(str(tmpdir / \"sub\"), [5,6,7])\n assert p.read() == \"0 0.5 0.5 0.5 0.5\\n1 0.5 0.5 0.5 0.5\\n2 0.5 0.5 0.5 0.5\\n3 0.5 0.5 0.5 0.5\\n4 0.5 0.5 0.5 0.5\\n\"\n\n def test_label_filter_8(self, tmpdir):\n p = tmpdir.mkdir(\"sub\").join(\"test8.txt\")\n p.write(\"0 0.5 0.5 0.5 0.5\\n1 0.5 0.5 0.5 0.5\\n2 0.5 0.5 0.5 0.5\\n3 0.5 0.5 0.5 0.5\\n4 0.5 0.5 0.5 0.5\")\n label_filter(str(tmpdir / \"sub\"), [0])\n assert p.read() == \"1 0.5 0.5 0.5 0.5\\n2 0.5 0.5 0.5 0.5\\n3 0.5 0.5 0.5 0.5\\n4 0.5 0.5 0.5 0.5\\n\"\n\n def test_label_filter_9(self, tmpdir):\n p = tmpdir.mkdir(\"sub\").join(\"test9.txt\")\n p.write(\"0 0.5 0.5 0.5 0.5\\n1 0.5 0.5 0.5 0.5\\n2 0.5 0.5 0.5 0.5\\n3 0.5 0.5 0.5 0.5\\n4 0.5 0.5 0.5 0.5\")\n label_filter(str(tmpdir / \"sub\"), [4])\n assert p.read() == \"0 0.5 0.5 0.5 0.5\\n1 0.5 0.5 0.5 0.5\\n2 0.5 0.5 0.5 0.5\\n3 0.5 0.5 0.5 0.5\\n\"\n\n def test_label_filter_10(self, tmpdir):\n p = tmpdir.mkdir(\"sub\").join(\"test10.txt\")\n p.write(\"0 0.5 0.5 0.5 0.5\\n1 0.5 0.5 0.5 0.5\\n2 0.5 0.5 0.5 0.5\\n3 0.5 0.5 0.5 0.5\\n4 0.5 0.5 0.5 0.5\")\n label_filter(str(tmpdir / \"sub\"), [0,1,2,3])\n assert p.read() == \"4 0.5 0.5 0.5 0.5\\n\"", "setup_code": "", "reference_solution": "```python\nimport os\n\n\ndef label_filter(folder_path,Label_category):\n\n txt_files = [f for f in os.listdir(folder_path) if f.endswith('.txt')]\n for file_name in txt_files:\n file_path = os.path.join(folder_path, file_name)\n with open(file_path, 'r') as file:\n lines = file.readlines()\n\n new_lines = []\n\n\n for line in lines:\n parts = line.split()\n\n if int(parts[0]) in Label_category :\n continue\n new_line = ' '.join(parts) + '\\n'\n new_lines.append(new_line)\n\n # 将处理后的行写回文件\n with open(file_path, 'w') as file:\n file.writelines(new_lines)\n\n```", "classification": "Artificial Intelligence"}
{"_id": 158, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nPerform category filtering on the annotation files of the yolo format dataset in the field of image processing, where both w and h are greater than limit_wideth and limit_height, operate on the original file. Input the annotation folder path of the yolo format dataset and limit_wideth, limit_height.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testw_h_filter:\n def test_w_h_filter_1(self, tmpdir):\n p = tmpdir.mkdir(\"sub\").join(\"test.txt\")\n p.write(\"0 0.5 0.5 0.1 0.1\\n1 0.5 0.5 0.2 0.2\")\n w_h_filter(str(tmpdir / \"sub\"), 0.15, 0.15)\n assert p.read() == \"1 0.5 0.5 0.2 0.2\\n\"\n\n", "problem": "Perform category filtering on the annotation files of the yolo format dataset in the field of image processing, where both w and h are greater than limit_wideth and limit_height, operate on the original file. Input the annotation folder path of the yolo format dataset and limit_wideth, limit_height.", "testcases": "import os\n\n\nclass Testw_h_filter:\n def test_w_h_filter_2(self, tmpdir):\n p = tmpdir.mkdir(\"sub\").join(\"test.txt\")\n p.write(\"0 0.5 0.5 0.1 0.1\\n1 0.5 0.5 0.2 0.2\")\n w_h_filter(str(tmpdir / \"sub\"), 0.05, 0.05)\n assert p.read() == \"0 0.5 0.5 0.1 0.1\\n1 0.5 0.5 0.2 0.2\\n\"\n\n def test_w_h_filter_3(self, tmpdir):\n p = tmpdir.mkdir(\"sub\").join(\"test.txt\")\n p.write(\"0 0.5 0.5 0.1 0.1\\n1 0.5 0.5 0.2 0.2\")\n w_h_filter(str(tmpdir / \"sub\"), 0.2, 0.2)\n assert p.read() == \"1 0.5 0.5 0.2 0.2\\n\"\n\n def test_w_h_filter_4(self, tmpdir):\n p = tmpdir.mkdir(\"sub\").join(\"test.txt\")\n p.write(\"0 0.5 0.5 0.1 0.1\\n1 0.5 0.5 0.2 0.2\")\n w_h_filter(str(tmpdir / \"sub\"), 0.1, 0.1)\n assert p.read() == \"0 0.5 0.5 0.1 0.1\\n1 0.5 0.5 0.2 0.2\\n\"\n\n def test_w_h_filter_5(self, tmpdir):\n p = tmpdir.mkdir(\"sub\").join(\"test.txt\")\n p.write(\"0 0.5 0.5 0.1 0.1\\n1 0.5 0.5 0.2 0.2\")\n w_h_filter(str(tmpdir / \"sub\"), 0.1, 0.2)\n assert p.read() == \"1 0.5 0.5 0.2 0.2\\n\"\n\n def test_w_h_filter_6(self, tmpdir):\n p = tmpdir.mkdir(\"sub\").join(\"test.txt\")\n p.write(\"0 0.5 0.5 0.1 0.1\\n1 0.5 0.5 0.2 0.2\")\n w_h_filter(str(tmpdir / \"sub\"), 0.2, 0.1)\n assert p.read() == \"1 0.5 0.5 0.2 0.2\\n\"\n\n def test_w_h_filter_7(self, tmpdir):\n p = tmpdir.mkdir(\"sub\").join(\"test.txt\")\n p.write(\"0 0.5 0.5 0.1 0.1\\n1 0.5 0.5 0.2 0.2\")\n w_h_filter(str(tmpdir / \"sub\"), 0, 0)\n assert p.read() == \"0 0.5 0.5 0.1 0.1\\n1 0.5 0.5 0.2 0.2\\n\"\n\n def test_w_h_filter_8(self, tmpdir):\n p = tmpdir.mkdir(\"sub\").join(\"test.txt\")\n p.write(\"0 0.5 0.5 0.1 0.1\\n1 0.5 0.5 0.2 0.2\")\n w_h_filter(str(tmpdir / \"sub\"), 1, 1)\n assert p.read() == \"\"\n\n def test_w_h_filter_9(self, tmpdir):\n p = tmpdir.mkdir(\"sub\").join(\"test.txt\")\n p.write(\"0 0.5 0.5 0.1 0.1\\n1 0.5 0.5 0.2 0.2\")\n w_h_filter(str(tmpdir / \"sub\"), 0.2, 0.2)\n assert p.read() == \"1 0.5 0.5 0.2 0.2\\n\"\n\n def test_w_h_filter_10(self, tmpdir):\n p = tmpdir.mkdir(\"sub\").join(\"test.txt\")\n p.write(\"0 0.5 0.5 0.1 0.1\\n1 0.5 0.5 0.2 0.2\")\n w_h_filter(str(tmpdir / \"sub\"), 0.15, 0.15)\n assert p.read() == \"1 0.5 0.5 0.2 0.2\\n\"", "setup_code": "", "reference_solution": "```python\nimport os\n\n\ndef w_h_filter(folder_path,limit_wideth,limit_height):\n txt_files = [f for f in os.listdir(folder_path) if f.endswith('.txt')]\n for file_name in txt_files:\n file_path = os.path.join(folder_path, file_name)\n with open(file_path, 'r') as file:\n lines = file.readlines()\n\n new_lines = []\n\n\n for line in lines:\n parts = line.split()\n\n if (float(parts[3]) < limit_wideth or float(parts[4]) < limit_height):\n continue\n new_line = ' '.join(parts) + '\\n'\n new_lines.append(new_line)\n\n # 将处理后的行写回文件\n with open(file_path, 'w') as file:\n file.writelines(new_lines)\n\n\n\n\n# if __name__ == \"__main__\":\n#\n# folder_path = r\"C:\\Users\\Administrator\\Desktop\\work\\1207-Q14\\labels\"\n# limit_wideth=0.1\n# limit_height=0.02\n# w_h_filter(folder_path,limit_wideth,limit_height)\n\n```", "classification": "Artificial Intelligence"}
{"_id": 159, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nImplement the Mean Squared Error (MSE) loss function using numpy.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testmean_squared_error:\n def test_mean_squared_error_1(self):\n y_true = np.array([1, 2, 3, 4, 5])\n y_pred = np.array([1, 2, 3, 4, 5])\n assert mean_squared_error(y_true, y_pred) == 0.0\n\n", "problem": "Implement the Mean Squared Error (MSE) loss function using numpy.", "testcases": "import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\n\nclass Testmean_squared_error:\n def test_mean_squared_error_2(self):\n y_true = np.array([1, 2, 3, 4, 5])\n y_pred = np.array([2, 3, 4, 5, 6])\n assert mean_squared_error(y_true, y_pred) == 1.0\n\n def test_mean_squared_error_3(self):\n y_true = np.array([1, 2, 3, 4, 5])\n y_pred = np.array([5, 4, 3, 2, 1])\n assert mean_squared_error(y_true, y_pred) == 8.0\n\n def test_mean_squared_error_4(self):\n y_true = np.array([1, 1, 1, 1, 1])\n y_pred = np.array([1, 1, 1, 1, 1])\n assert mean_squared_error(y_true, y_pred) == 0.0\n\n def test_mean_squared_error_5(self):\n y_true = np.array([1, 1, 1, 1, 1])\n y_pred = np.array([0, 0, 0, 0, 0])\n assert mean_squared_error(y_true, y_pred) == 1.0\n\n def test_mean_squared_error_6(self):\n y_true = np.array([0, 0, 0, 0, 0])\n y_pred = np.array([1, 1, 1, 1, 1])\n assert mean_squared_error(y_true, y_pred) == 1.0\n\n def test_mean_squared_error_7(self):\n y_true = np.array([100, 200, 300, 400, 500])\n y_pred = np.array([100, 200, 300, 400, 500])\n assert mean_squared_error(y_true, y_pred) == 0.0\n\n def test_mean_squared_error_8(self):\n y_true = np.array([100, 200, 300, 400, 500])\n y_pred = np.array([500, 400, 300, 200, 100])\n assert mean_squared_error(y_true, y_pred) == 80000.0\n\n def test_mean_squared_error_9(self):\n y_true = np.array([1.1, 2.2, 3.3, 4.4, 5.5])\n y_pred = np.array([1.1, 2.2, 3.3, 4.4, 5.5])\n assert mean_squared_error(y_true, y_pred) == 0.0\n", "setup_code": "", "reference_solution": "```python\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\n\ndef mean_squared_error(y_true, y_pred):\n return np.mean(np.square(y_true - y_pred))\n```", "classification": "Artificial Intelligence"}
{"_id": 160, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nImport the nltk package. Define a function with a parameter to receive a sentence, perform tokenization, part-of-speech tagging, stop word removal, and stem extraction operations on this sentence, and output the results of each operation. Then call the defined function.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testprocess_sentence:\n def test_process_sentence_1(self):\n assert process_sentence(\"Hello, world!\") == (['Hello', ',', 'world', '!'], [('Hello', 'NNP'), (',', ','), ('world', 'NN'), ('!', '.')], ['hello', ',', 'world', '!'], ['hello', ',', 'world', '!'])\n\n", "problem": "Import the nltk package. Define a function with a parameter to receive a sentence, perform tokenization, part-of-speech tagging, stop word removal, and stem extraction operations on this sentence, and output the results of each operation. Then call the defined function.", "testcases": "import nltk\nnltk.data.path.append('averaged_perceptron_tagger')\nfrom nltk.tokenize import word_tokenize\nfrom nltk.stem import PorterStemmer\n\n\nclass Testprocess_sentence:\n def test_process_sentence_2(self):\n assert process_sentence(\"I am a student.\") == (['I', 'am', 'a', 'student', '.'], [('I', 'PRP'), ('am', 'VBP'), ('a', 'DT'), ('student', 'NN'), ('.', '.')], ['i', 'am', 'a', 'student', '.'], ['i', 'am', 'a', 'student', '.'])\n\n def test_process_sentence_3(self):\n assert process_sentence(\"This is a test sentence.\") == (['This', 'is', 'a', 'test', 'sentence', '.'], [('This', 'DT'), ('is', 'VBZ'), ('a', 'DT'), ('test', 'NN'), ('sentence', 'NN'), ('.', '.')], ['this', 'is', 'a', 'test', 'sentence', '.'], ['thi', 'is', 'a', 'test', 'sentenc', '.'])\n\n def test_process_sentence_4(self):\n assert process_sentence(\"The quick brown fox jumps over the lazy dog.\") == (['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog', '.'], [('The', 'DT'), ('quick', 'JJ'), ('brown', 'NN'), ('fox', 'NN'), ('jumps', 'VBZ'), ('over', 'IN'), ('the', 'DT'), ('lazy', 'JJ'), ('dog', 'NN'), ('.', '.')], ['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog', '.'], ['the', 'quick', 'brown', 'fox', 'jump', 'over', 'the', 'lazi', 'dog', '.'])\n\n def test_process_sentence_5(self):\n assert process_sentence(\"Python is a high-level programming language.\") == (['Python', 'is', 'a', 'high-level', 'programming', 'language', '.'], [('Python', 'NNP'), ('is', 'VBZ'), ('a', 'DT'), ('high-level', 'JJ'), ('programming', 'NN'), ('language', 'NN'), ('.', '.')], ['python', 'is', 'a', 'high-level', 'programming', 'language', '.'], ['python', 'is', 'a', 'high-level', 'program', 'languag', '.'])\n\n def test_process_sentence_6(self):\n assert process_sentence(\"It's a beautiful day!\") == (['It', \"'s\", 'a', 'beautiful', 'day', '!'], [('It', 'PRP'), (\"'s\", 'VBZ'), ('a', 'DT'), ('beautiful', 'JJ'), ('day', 'NN'), ('!', '.')], ['it', \"'s\", 'a', 'beautiful', 'day', '!'], ['it', \"'s\", 'a', 'beauti', 'day', '!'])\n\n def test_process_sentence_7(self):\n assert process_sentence(\"\") == ([], [], [], [])\n\n def test_process_sentence_8(self):\n assert process_sentence(\" \") == ([], [], [], [])\n\n def test_process_sentence_9(self):\n assert process_sentence(\"123\") == (['123'], [('123', 'CD')], ['123'], ['123'])\n\n def test_process_sentence_10(self):\n assert process_sentence(\"!@#$%^&*()\") == (['!', '@', '#', '$', '%', '^', '&', '*', '(', ')'], [('!', '.'), ('@', 'JJ'), ('#', '#'), ('$', '$'), ('%', 'NN'), ('^', 'NNP'), ('&', 'CC'), ('*', 'NNP'), ('(', '('), (')', ')')], ['!', '@', '#', '$', '%', '^', '&', '*', '(', ')'], ['!', '@', '#', '$', '%', '^', '&', '*', '(', ')'])", "setup_code": "", "reference_solution": "```python\nimport nltk\nnltk.data.path.append('nltk_package')\nfrom nltk.tokenize import word_tokenize\nfrom nltk.stem import PorterStemmer\nfrom nltk import pos_tag\n\n\ndef process_sentence(sentence):\n tokens = word_tokenize(sentence)\n pos_tags = pos_tag(tokens)\n # stop_words = set(stopwords.words('english'))\n # filtered_tokens = [word.lower() for word in tokens if word.lower() not in stop_words]\n filtered_tokens = [word.lower() for word in tokens]\n stemmer = PorterStemmer()\n stemmed_tokens = [stemmer.stem(word) for word in filtered_tokens]\n # 输出结果\n print(\"Original Sentence:\\n\", sentence)\n print(\"\\nTokenized Sentence:\\n\", tokens)\n print(\"\\nPOS Tagged Sentence:\\n\", pos_tags)\n print(\"\\nSentence without Stopwords:\\n\", filtered_tokens)\n print(\"\\nStemmed Sentence:\\n\", stemmed_tokens)\n return tokens, pos_tags, filtered_tokens, stemmed_tokens\n\nprint(process_sentence(\"!@#$%^&*()\"))\n\n```", "classification": "Artificial Intelligence"}
{"_id": 161, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nThere is a dataset.csv, which contains 5 columns: PassengerID, Survived, Pclass, Sex, Age. Please read the file and calculate the probability of the Sex column being female and the Survived column being 1, and the probability of the Sex column being male and the Survived column being 1. Finally, convert the non-numeric columns in the dataset to one-hot encoding, and save the dataset to a new file named new_train.csv.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testcalculate_and_save_probabilities:\n def test_case1(self):\n assert calculate_and_save_probabilities(\"test1/dataset.csv\", \"test1/new_train.csv\") == (0.1, 0.8)\n df1 = pd.read_csv(\"test1/new_train.csv\")\n df2 = pd.read_csv(\"test1/test_label.csv\")\n assert df1.equals(df2)\n\n", "problem": "There is a dataset.csv, which contains 5 columns: PassengerID, Survived, Pclass, Sex, Age. Please read the file and calculate the probability of the Sex column being female and the Survived column being 1, and the probability of the Sex column being male and the Survived column being 1. Finally, convert the non-numeric columns in the dataset to one-hot encoding, and save the dataset to a new file named new_train.csv.", "testcases": "import pandas as pd\nfrom sklearn.preprocessing import OneHotEncoder\n\n\nclass Testcalculate_and_save_probabilities:\n def test_case2(self):\n assert calculate_and_save_probabilities(\"test2/dataset.csv\", \"test2/new_train.csv\") == (0.2, 0.8)\n df1 = pd.read_csv(\"test2/new_train.csv\")\n df2 = pd.read_csv(\"test2/test_label.csv\")\n assert df1.equals(df2)\n\n def test_case3(self):\n assert calculate_and_save_probabilities(\"test3/dataset.csv\", \"test3/new_train.csv\") == (0.2727272727272727, 0.8888888888888888)\n df1 = pd.read_csv(\"test3/new_train.csv\")\n df2 = pd.read_csv(\"test3/test_label.csv\")\n assert df1.equals(df2)\n\n def test_case4(self):\n assert calculate_and_save_probabilities(\"test4/dataset.csv\", \"test4/new_train.csv\") == (0.36363636363636365, 0.7777777777777778)\n df1 = pd.read_csv(\"test4/new_train.csv\")\n df2 = pd.read_csv(\"test4/test_label.csv\")\n assert df1.equals(df2)\n\n def test_case5(self):\n assert calculate_and_save_probabilities(\"test5/dataset.csv\", \"test5/new_train.csv\") == (0.2, 0.8)\n df1 = pd.read_csv(\"test5/new_train.csv\")\n df2 = pd.read_csv(\"test5/test_label.csv\")\n assert df1.equals(df2)\n\n def test_case6(self):\n assert calculate_and_save_probabilities(\"test6/dataset.csv\", \"test6/new_train.csv\") == (0.2222222222222222, 0.7272727272727273)\n df1 = pd.read_csv(\"test6/new_train.csv\")\n df2 = pd.read_csv(\"test6/test_label.csv\")\n assert df1.equals(df2)", "setup_code": "", "reference_solution": "```python\nimport pandas as pd\nfrom sklearn.preprocessing import OneHotEncoder\n\n\ndef calculate_and_save_probabilities(input_file, output_file):\n # 读取数据集\n df = pd.read_csv(input_file)\n\n # 计算概率\n probabilities = {}\n for column_value in df['Sex'].unique():\n prob = df[(df['Sex'] == column_value) & (df[\"Survived\"] == 1)].shape[0] / df[df['Sex'] == column_value].shape[0]\n probabilities[f\"Probability({'Sex'}={column_value}, {'Survived'}=1)\"] = prob\n\n # 打印计算结果\n for key, value in probabilities.items():\n print(key + \":\", value)\n\n # 进行独热编码\n non_numeric_columns = df.select_dtypes(include=['object']).columns\n encoder = OneHotEncoder(sparse=False)\n encoded_features = pd.DataFrame(encoder.fit_transform(df[non_numeric_columns]))\n encoded_features.columns = encoder.get_feature_names_out(non_numeric_columns)\n\n # 替换原始数据集中的非数值列\n df.drop(non_numeric_columns, axis=1, inplace=True)\n df = pd.concat([df, encoded_features], axis=1)\n\n # 将数据集保存到新文件\n df.to_csv(output_file, index=False)\n\n return probabilities[f\"Probability(Sex=male, Survived=1)\"], probabilities[\"Probability(Sex=female, Survived=1)\"]\n\n\nprint(calculate_and_save_probabilities(\"test6/dataset.csv\", \"test6/test_label.csv\"))\n```", "classification": "Data Science"}
{"_id": 162, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nGiven two vectors of equal length x, y, use the numpy toolkit to solve for a and b using the least squares method for linear fitting, and find the slope a, intercept b, and correlation coefficient r.\nFunction usage: a, b, r = linear_fit(x, y)\nPlease complete the code for the linear_fit function.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testlinear_fit:\n def test_linear_fit_1(self):\n x = [1, 2, 3, 4, 5]\n y = [2, 4, 6, 8, 10]\n a, b, r = linear_fit(x, y)\n assert a == 2\n assert b == 0\n assert r == 0.9999999999999999\n\n", "problem": "Given two vectors of equal length x, y, use the numpy toolkit to solve for a and b using the least squares method for linear fitting, and find the slope a, intercept b, and correlation coefficient r.\nFunction usage: a, b, r = linear_fit(x, y)\nPlease complete the code for the linear_fit function.", "testcases": "import numpy as np\n\n\nclass Testlinear_fit:\n def test_linear_fit_2(self):\n x = [1, 2, 3, 4, 5]\n y = [3, 5, 7, 9, 11]\n a, b, r = linear_fit(x, y)\n assert a == 2\n assert b == 1\n assert r == 0.9999999999999999\n\n def test_linear_fit_3(self):\n x = [1, 2, 3, 4, 5]\n y = [1, 2, 3, 4, 5]\n a, b, r = linear_fit(x, y)\n assert a == 1\n assert b == 0\n assert r == 0.9999999999999999\n\n def test_linear_fit_4(self):\n x = [1, 2, 3, 4, 5]\n y = [2, 3, 4, 5, 6]\n a, b, r = linear_fit(x, y)\n assert a == 1\n assert b == 1\n assert r == 0.9999999999999999\n\n def test_linear_fit_5(self):\n x = [1, 2, 3, 4, 5]\n y = [5, 7, 9, 11, 13]\n a, b, r = linear_fit(x, y)\n assert a == 2\n assert b == 3\n assert r == 0.9999999999999999\n\n def test_linear_fit_6(self):\n x = [1, 2, 3, 4, 5]\n y = [1, 1, 1, 1, 1]\n a, b, r = linear_fit(x, y)\n assert a == 0\n assert b == 1\n assert np.isnan(r)\n\n def test_linear_fit_7(self):\n x = [1, 1, 1, 1, 1]\n y = [1, 2, 3, 4, 5]\n a, b, r = linear_fit(x, y)\n assert np.isnan(a)\n assert np.isnan(b)\n assert np.isnan(r)\n\n def test_linear_fit_8(self):\n x = [1, 2, 3, 4, 5]\n y = [5, 4, 3, 2, 1]\n a, b, r = linear_fit(x, y)\n assert a == -1\n assert b == 6\n assert r == -0.9999999999999999\n\n def test_linear_fit_9(self):\n x = [1, 2, 3, 4, 5]\n y = [10, 8, 6, 4, 2]\n a, b, r = linear_fit(x, y)\n assert a == -2\n assert b == 12\n assert r == -0.9999999999999999\n\n def test_linear_fit_10(self):\n x = [1, 2, 3, 4, 5]\n y = [1, 4, 9, 16, 25]\n a, b, r = linear_fit(x, y)\n assert a == 6.0\n assert b == -7.0\n assert r == 0.981104910251593", "setup_code": "", "reference_solution": "```python\nimport numpy as np\n\n\ndef linear_fit(x, y):\n x = np.array(x)\n y = np.array(y)\n\n mean_x = np.mean(x)\n mean_y = np.mean(y)\n\n SS_xy = np.dot(x - mean_x, y - mean_y)\n SS_xx = np.dot(x - mean_x, x - mean_x)\n a = SS_xy / SS_xx\n b = mean_y - a * mean_x\n\n r = np.corrcoef(x, y)[0, 1]\n\n return a, b, r\n\n\n```", "classification": "Data Science"}
{"_id": 163, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nCreate a Python class that accepts a path parameter. If the received path does not exist, output \"Invalid directory path.\" If the received path exists, output the names of all files in this path and the names of all files in its subdirectories.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testlist_files:\n def test_list_files_1(self, tmp_path, capsys):\n d = tmp_path / \"sub\"\n d.mkdir()\n p = d / \"hello.txt\"\n p.write_text(\"content\")\n list_files(tmp_path)\n captured = capsys.readouterr()\n assert captured.out == \"hello.txt\\n\"\n\n", "problem": "Create a Python class that accepts a path parameter. If the received path does not exist, output \"Invalid directory path.\" If the received path exists, output the names of all files in this path and the names of all files in its subdirectories.", "testcases": "\n\nclass Testlist_files:\n def test_list_files_2(self, tmp_path, capsys):\n d = tmp_path / \"sub\"\n d.mkdir()\n p = d / \"hello.txt\"\n p.write_text(\"content\")\n p2 = tmp_path / \"world.txt\"\n p2.write_text(\"content\")\n list_files(tmp_path)\n captured = capsys.readouterr()\n assert 'world.txt' in captured.out and 'hello.txt' in captured.out\n\n def test_list_files_3(self, tmp_path, capsys):\n list_files(tmp_path)\n captured = capsys.readouterr()\n assert captured.out == \"\"\n\n def test_list_files_4(self, tmp_path, capsys):\n d = tmp_path / \"sub\"\n d.mkdir()\n p = d / \"hello.txt\"\n p.write_text(\"content\")\n d2 = tmp_path / \"sub2\"\n d2.mkdir()\n p2 = d2 / \"world.txt\"\n p2.write_text(\"content\")\n list_files(tmp_path)\n captured = capsys.readouterr()\n assert 'world.txt' in captured.out and 'hello.txt' in captured.out\n\n def test_list_files_5(self, tmp_path, capsys):\n d = tmp_path / \"sub\"\n d.mkdir()\n p = d / \"hello.txt\"\n p.write_text(\"content\")\n d2 = d / \"sub2\"\n d2.mkdir()\n p2 = d2 / \"world.txt\"\n p2.write_text(\"content\")\n list_files(tmp_path)\n captured = capsys.readouterr()\n assert 'world.txt' in captured.out and 'hello.txt' in captured.out\n\n def test_list_files_6(self, tmp_path, capsys):\n d = tmp_path / \"sub\"\n d.mkdir()\n p = d / \"hello.txt\"\n p.write_text(\"content\")\n d2 = d / \"sub2\"\n d2.mkdir()\n p2 = d2 / \"world.txt\"\n p2.write_text(\"content\")\n d3 = d2 / \"sub3\"\n d3.mkdir()\n p3 = d3 / \"python.txt\"\n p3.write_text(\"content\")\n list_files(tmp_path)\n captured = capsys.readouterr()\n assert 'world.txt' in captured.out and 'hello.txt' in captured.out and 'python.txt' in captured.out\n\n def test_list_files_7(self, capsys):\n list_files(\"/invalid/path\")\n captured = capsys.readouterr()\n assert 'Invalid directory path.' in captured.out", "setup_code": "", "reference_solution": "```python\nimport os\n\ndef list_files(directory_path):\n # 检查目录是否存在\n if not os.path.exists(directory_path) or not os.path.isdir(directory_path):\n print(\"Invalid directory path.\")\n return\n\n list_files_recursive(directory_path)\n\ndef list_files_recursive(directory):\n # 获取目录中的所有文件和子目录\n files = os.listdir(directory)\n for file in files:\n file_path = os.path.join(directory, file)\n if os.path.isfile(file_path):\n # 如果是文件,则输出文件名\n print(file)\n elif os.path.isdir(file_path):\n # 如果是目录,则输出目录名,并递归调用列出子目录\n list_files_recursive(file_path)\n\n```", "classification": "Operation System"}
{"_id": 164, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nDesign a Python function that accepts a filename and a path information, used to check whether the file exists in the specified directory. If it does not exist, output \"The file is not on disk\". If it exists, output the absolute path of the file. If the file exists in the specified directory and there are multiple files with the same name, output the absolute paths of all files with the same name.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testfind_file:\n def test_find_file_1(self, tmpdir, capsys):\n p = tmpdir.mkdir(\"sub\").join(\"hello.txt\")\n p.write(\"content\")\n find_file('hello.txt', tmpdir)\n captured = capsys.readouterr()\n assert captured.out == f\"{os.path.join(tmpdir, 'sub', 'hello.txt')}\\n\"\n\n", "problem": "Design a Python function that accepts a filename and a path information, used to check whether the file exists in the specified directory. If it does not exist, output \"The file is not on disk\". If it exists, output the absolute path of the file. If the file exists in the specified directory and there are multiple files with the same name, output the absolute paths of all files with the same name.", "testcases": "\n\nclass Testfind_file:\n def test_find_file_2(self, tmpdir, capsys):\n p = tmpdir.mkdir(\"sub\").join(\"hello.txt\")\n p.write(\"content\")\n find_file('world.txt', tmpdir)\n captured = capsys.readouterr()\n assert 'The file is not on disk' in captured.out\n\n def test_find_file_3(self, tmpdir, capsys):\n p1 = tmpdir.mkdir(\"sub1\").join(\"hello.txt\")\n p1.write(\"content\")\n p2 = tmpdir.mkdir(\"sub2\").join(\"hello.txt\")\n p2.write(\"content\")\n find_file('hello.txt', tmpdir)\n captured = capsys.readouterr()\n assert f\"{os.path.join(tmpdir, 'sub1', 'hello.txt')}\" in captured.out and f\"{os.path.join(tmpdir, 'sub2', 'hello.txt')}\" in captured.out\n\n def test_find_file_4(self, tmpdir, capsys):\n find_file('hello.txt', tmpdir)\n captured = capsys.readouterr()\n assert 'The file is not on disk' in captured.out\n\n def test_find_file_5(self, tmpdir, capsys):\n p = tmpdir.mkdir(\"sub\").join(\"hello.txt\")\n p.write(\"content\")\n find_file('hello.txt', os.path.join(tmpdir, 'sub'))\n captured = capsys.readouterr()\n assert f\"{os.path.join(tmpdir, 'sub', 'hello.txt')}\" in captured.out\n\n def test_find_file_6(self, tmpdir, capsys):\n p = tmpdir.mkdir(\"sub\").join(\"hello.txt\")\n p.write(\"content\")\n find_file('hello.txt', os.path.join(tmpdir, 'sub2'))\n captured = capsys.readouterr()\n assert 'The file is not on disk' in captured.out\n\n def test_find_file_7(self, tmpdir, capsys):\n p = tmpdir.mkdir(\"sub\").join(\"hello.txt\")\n p.write(\"content\")\n find_file('hello.txt', os.path.join(tmpdir, 'sub', 'subsub'))\n captured = capsys.readouterr()\n assert 'The file is not on disk' in captured.out\n", "setup_code": "", "reference_solution": "```python\nimport os\n\ndef find_file(file_name, directory_path):\n exist = False\n # 使用os.walk遍历指定目录及其子目录中的文件\n for root, dirs, files in os.walk(directory_path):\n for file in files:\n if file == file_name:\n exist = True\n # 如果找到文件,输出文件的绝对路径\n file_path = os.path.join(root, file)\n print(file_path)\n \n if not exist:\n print(\"The file is not on disk\")\n\n```", "classification": "Operation System"}
{"_id": 165, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nGiven a CSV file that contains multiple columns of data, each column consisting of numbers, read the file and calculate the average of the third column. (Hint, you need to skip the title row)\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testcalculate_average:\n def test_calculate_average_1(self):\n assert calculate_average('test1.csv', 2) == 85\n\n", "problem": "Given a CSV file that contains multiple columns of data, each column consisting of numbers, read the file and calculate the average of the third column. (Hint, you need to skip the title row)", "testcases": "\n\nclass Testcalculate_average:\n def test_calculate_average_2(self):\n assert calculate_average('test2.csv', 2) == 80\n\n def test_calculate_average_3(self):\n assert calculate_average('test3.csv', 2) == 8\n\n def test_calculate_average_4(self):\n assert calculate_average('test4.csv', 2) == 800\n\n def test_calculate_average_5(self):\n assert calculate_average('test5.csv', 2) == 0\n\n def test_calculate_average_6(self):\n assert calculate_average('test6.csv', 2) == 0\n\n def test_calculate_average_7(self):\n assert calculate_average('test7.csv', 2) == 15500\n", "setup_code": "", "reference_solution": "```python\nimport csv\n\ndef calculate_average(filename, column_index):\n with open(filename, 'r') as file:\n reader = csv.reader(file)\n next(reader) \n total, count = 0, 0\n for row in reader:\n if row[column_index].isdigit():\n total += int(row[column_index])\n count += 1\n return total / count if count != 0 else 0\n\n\n```", "classification": "Data Science"}
{"_id": 166, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nThere are multiple CSV files in the data folder, each file has two columns, containing the daily temperature records of a certain city in 2022. The first row is the title, which are Date and Temperature. The temperature value is an integer. I need to find out the highest temperature value and the corresponding date of each city in that year, and save the results to a new CSV file. The result CSV consists of three columns, including city, highest temperature, and date. Note that if the highest temperature is the same for multiple days, keep all dates that reach the highest temperature. How can I use the pandas library's dataframe to complete this task?\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testfind_max_temperature:\n def test_single_file_single_max(self, tmpdir):\n data = \"Date,Temperature\\n2022-01-01,10\\n2022-01-02,20\\n2022-01-03,30\"\n p = tmpdir.mkdir(\"data\").join(\"city1.csv\")\n p.write(data)\n output_file = tmpdir.join(\"output.csv\")\n find_max_temperature(str(tmpdir.join(\"data\")), str(output_file))\n assert output_file.read() == \"City,Max_Temperature,Date\\ncity1,30,2022-01-03\\n\"\n\n", "problem": "There are multiple CSV files in the data folder, each file has two columns, containing the daily temperature records of a certain city in 2022. The first row is the title, which are Date and Temperature. The temperature value is an integer. I need to find out the highest temperature value and the corresponding date of each city in that year, and save the results to a new CSV file. The result CSV consists of three columns, including city, highest temperature, and date. Note that if the highest temperature is the same for multiple days, keep all dates that reach the highest temperature. How can I use the pandas library's dataframe to complete this task?", "testcases": "import os\n\nclass Testfind_max_temperature:\n def test_single_file_multiple_max(self, tmpdir):\n data = \"Date,Temperature\\n2022-01-01,30\\n2022-01-02,20\\n2022-01-03,30\"\n p = tmpdir.mkdir(\"data\").join(\"city1.csv\")\n p.write(data)\n output_file = tmpdir.join(\"output.csv\")\n find_max_temperature(str(tmpdir.join(\"data\")), str(output_file))\n assert 'city1,30,2022-01-01' in output_file.read() and 'city1,30,2022-01-03' in output_file.read()\n\n def test_multiple_files_single_max(self, tmpdir):\n data1 = \"Date,Temperature\\n2022-01-01,10\\n2022-01-02,20\\n2022-01-03,30\"\n data2 = \"Date,Temperature\\n2022-01-01,20\\n2022-01-02,30\\n2022-01-03,40\"\n p1 = tmpdir.mkdir(\"data\").join(\"city1.csv\")\n p1.write(data1)\n p2 = tmpdir.join(\"data\").join(\"city2.csv\")\n p2.write(data2)\n output_file = tmpdir.join(\"output.csv\")\n find_max_temperature(str(tmpdir.join(\"data\")), str(output_file))\n assert 'city1,30,2022-01-03' in output_file.read() and 'city2,40,2022-01-03' in output_file.read()\n\n def test_multiple_files_multiple_max(self, tmpdir):\n data1 = \"Date,Temperature\\n2022-01-01,30\\n2022-01-02,20\\n2022-01-03,30\"\n data2 = \"Date,Temperature\\n2022-01-01,40\\n2022-01-02,30\\n2022-01-03,40\"\n p1 = tmpdir.mkdir(\"data\").join(\"city1.csv\")\n p1.write(data1)\n p2 = tmpdir.join(\"data\").join(\"city2.csv\")\n p2.write(data2)\n output_file = tmpdir.join(\"output.csv\")\n find_max_temperature(str(tmpdir.join(\"data\")), str(output_file))\n assert 'city1,30,2022-01-01' in output_file.read() and 'city1,30,2022-01-03' in output_file.read() and 'city2,40,2022-01-01' in output_file.read() and 'city2,40,2022-01-03' in output_file.read()\n\n def test_no_csv_files(self, tmpdir):\n tmpdir.mkdir(\"data\")\n output_file = tmpdir.join(\"output.csv\")\n find_max_temperature(str(tmpdir.join(\"data\")), str(output_file))\n assert output_file.read() == \"City,Max_Temperature,Date\\n\"\n\n def test_empty_csv_file(self, tmpdir):\n p = tmpdir.mkdir(\"data\").join(\"city1.csv\")\n p.write(\"Date,Temperature\\n\")\n output_file = tmpdir.join(\"output.csv\")\n find_max_temperature(str(tmpdir.join(\"data\")), str(output_file))\n assert output_file.read() == \"City,Max_Temperature,Date\\n\"\n\n def test_single_file_single_max_boundary(self, tmpdir):\n data = \"Date,Temperature\\n2022-01-01,999999\\n2022-01-02,20\\n2022-01-03,30\"\n p = tmpdir.mkdir(\"data\").join(\"city1.csv\")\n p.write(data)\n output_file = tmpdir.join(\"output.csv\")\n find_max_temperature(str(tmpdir.join(\"data\")), str(output_file))\n assert 'city1,999999,2022-01-01' in output_file.read()\n\n def test_single_file_multiple_max_boundary(self, tmpdir):\n data = \"Date,Temperature\\n2022-01-01,999999\\n2022-01-02,20\\n2022-01-03,999999\"\n p = tmpdir.mkdir(\"data\").join(\"city1.csv\")\n p.write(data)\n output_file = tmpdir.join(\"output.csv\")\n find_max_temperature(str(tmpdir.join(\"data\")), str(output_file))\n assert 'city1,999999,2022-01-01' in output_file.read() and 'city1,999999,2022-01-03' in output_file.read()\n\n def test_multiple_files_single_max_boundary(self, tmpdir):\n data1 = \"Date,Temperature\\n2022-01-01,10\\n2022-01-02,20\\n2022-01-03,30\"\n data2 = \"Date,Temperature\\n2022-01-01,999999\\n2022-01-02,30\\n2022-01-03,40\"\n p1 = tmpdir.mkdir(\"data\").join(\"city1.csv\")\n p1.write(data1)\n p2 = tmpdir.join(\"data\").join(\"city2.csv\")\n p2.write(data2)\n output_file = tmpdir.join(\"output.csv\")\n find_max_temperature(str(tmpdir.join(\"data\")), str(output_file))\n assert 'city2,999999,2022-01-01' in output_file.read() and 'city1,30,2022-01-03' in output_file.read()\n\n def test_multiple_files_multiple_max_boundary(self, tmpdir):\n data1 = \"Date,Temperature\\n2022-01-01,999999\\n2022-01-02,20\\n2022-01-03,999999\"\n data2 = \"Date,Temperature\\n2022-01-01,999999\\n2022-01-02,30\\n2022-01-03,999999\"\n p1 = tmpdir.mkdir(\"data\").join(\"city1.csv\")\n p1.write(data1)\n p2 = tmpdir.join(\"data\").join(\"city2.csv\")\n p2.write(data2)\n output_file = tmpdir.join(\"output.csv\")\n find_max_temperature(str(tmpdir.join(\"data\")), str(output_file))\n assert 'city2,999999,2022-01-01' in output_file.read() and 'city1,999999,2022-01-01' in output_file.read() and 'city2,999999,2022-01-03' in output_file.read() and 'city1,999999,2022-01-03' in output_file.read()", "setup_code": "", "reference_solution": "```python\nimport os\nimport pandas as pd\n\n\ndef find_max_temperature(folder_path, output_file):\n csv_files = [f for f in os.listdir(folder_path) if f.endswith('.csv')]\n \n result_df = pd.DataFrame(columns=['City', 'Max_Temperature', 'Date'])\n \n for csv_file in csv_files:\n file_path = os.path.join(folder_path, csv_file)\n df = pd.read_csv(file_path)\n \n city_name = csv_file[:-4]\n \n # 找到最高气温的值\n max_temp = df['Temperature'].max()\n \n # 找到所有最高气温的日期\n max_temp_dates = df.loc[df['Temperature'] == max_temp, 'Date'].tolist()\n \n # 将结果添加到result_df\n for date in max_temp_dates:\n result_df = result_df._append({'City': city_name,\n 'Max_Temperature': max_temp,\n 'Date': date}, ignore_index=True)\n \n result_df.to_csv(output_file, index=False)\n\n```", "classification": "Data Science"}
{"_id": 167, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nRead data from multiple CSV files, each file representing a data source. Merge these data according to the timestamp, and then calculate the moving average of the merged data.\nThe format of data.csv is\ntimestamp,feature1,feature2,feature3\n2023-03-15 14:30:00,10,20,30\n2023-03-15 14:35:00,11,21,31\n2023-03-15 14:40:00,12,22,32\n...\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testmerge_and_smooth_data:\n def test_merge_and_smooth_data_1(self):\n data1 = pd.DataFrame({\n 'timestamp': ['2023-03-15 14:30:00', '2023-03-15 14:35:00', '2023-03-15 14:40:00'],\n 'feature1': [10, 11, 12],\n 'feature2': [20, 21, 22],\n 'feature3': [30, 31, 32]\n })\n data1.to_csv('data1.csv.csv', index=False)\n data2 = pd.DataFrame({\n 'timestamp': ['2023-03-15 14:45:00', '2023-03-15 14:50:00', '2023-03-15 14:55:00'],\n 'feature1': [13, 14, 15],\n 'feature2': [23, 24, 25],\n 'feature3': [33, 34, 35]\n })\n data2.to_csv('data2.csv', index=False)\n assert merge_and_smooth_data(['data1.csv.csv', 'data2.csv'], 2).tolist() == [[11.5, 21.5, 31.5], [12.5, 22.5, 32.5], [13.5, 23.5, 33.5], [14.5, 24.5, 34.5]]\n\n", "problem": "Read data from multiple CSV files, each file representing a data source. Merge these data according to the timestamp, and then calculate the moving average of the merged data.\nThe format of data.csv is\ntimestamp,feature1,feature2,feature3\n2023-03-15 14:30:00,10,20,30\n2023-03-15 14:35:00,11,21,31\n2023-03-15 14:40:00,12,22,32\n...", "testcases": "import pandas as pd\n\nclass Testmerge_and_smooth_data:\n def test_merge_and_smooth_data_2(self):\n data1 = pd.DataFrame({\n 'timestamp': ['2023-03-15 14:30:00', '2023-03-15 14:35:00', '2023-03-15 14:40:00'],\n 'feature1': [10, 11, 12],\n 'feature2': [20, 21, 22],\n 'feature3': [30, 31, 32]\n })\n data1.to_csv('data1.csv.csv', index=False)\n data2 = pd.DataFrame({\n 'timestamp': ['2023-03-15 14:45:00', '2023-03-15 14:50:00', '2023-03-15 14:55:00'],\n 'feature1': [13, 14, 15],\n 'feature2': [23, 24, 25],\n 'feature3': [33, 34, 35]\n })\n data2.to_csv('data2.csv', index=False)\n assert merge_and_smooth_data(['data1.csv.csv', 'data2.csv'], 3).tolist() == [[12.0, 22.0, 32.0], [13.0, 23.0, 33.0], [14.0, 24.0, 34.0]]\n\n def test_merge_and_smooth_data_3(self):\n data1 = pd.DataFrame({\n 'timestamp': ['2023-03-15 14:30:00', '2023-03-15 14:35:00', '2023-03-15 14:40:00'],\n 'feature1': [10, 11, 12],\n 'feature2': [20, 21, 22],\n 'feature3': [30, 31, 32]\n })\n data1.to_csv('data1.csv.csv', index=False)\n assert merge_and_smooth_data(['data1.csv.csv'], 2).tolist() == [[11.5, 21.5, 31.5]]\n\n def test_merge_and_smooth_data_4(self):\n data1 = pd.DataFrame({\n 'timestamp': ['2023-03-15 14:30:00', '2023-03-15 14:35:00', '2023-03-15 14:40:00'],\n 'feature1': [10, 11, 12],\n 'feature2': [20, 21, 22],\n 'feature3': [30, 31, 32]\n })\n data1.to_csv('data1.csv.csv', index=False)\n assert merge_and_smooth_data(['data1.csv.csv'], 1).tolist() == [[11.0, 21.0, 31.0], [12.0, 22.0, 32.0]]\n\n def test_merge_and_smooth_data_5(self):\n data1 = pd.DataFrame({\n 'timestamp': ['2023-03-15 14:30:00'],\n 'feature1': [10],\n 'feature2': [20],\n 'feature3': [30]\n })\n data1.to_csv('data1.csv.csv', index=False)\n assert merge_and_smooth_data(['data1.csv.csv'], 1).tolist() == []\n\n def test_merge_and_smooth_data_6(self):\n data1 = pd.DataFrame({\n 'timestamp': ['2023-03-15 14:30:00'],\n 'feature1': [10],\n 'feature2': [20],\n 'feature3': [30]\n })\n data1.to_csv('data1.csv.csv', index=False)\n assert merge_and_smooth_data(['data1.csv.csv'], 2).tolist() == []", "setup_code": "", "reference_solution": "```python\nimport pandas as pd\nimport torch\n\ndef merge_and_smooth_data(filenames, window_size):\n dfs = [pd.read_csv(filename) for filename in filenames]\n merged_df = pd.concat(dfs).sort_values(by='timestamp')\n\n tensor = torch.tensor(merged_df.drop(columns=['timestamp']).values)\n\n cumsum = tensor.cumsum(dim=0)\n sliding_avg = (cumsum[window_size:] - cumsum[:-window_size]) / float(window_size)\n return sliding_avg\n\n\n```", "classification": "Data Science"}
{"_id": 168, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nUse Python to convert the images in the folder to RGB format, then number the images from smallest to largest, and change the resolution of all images to a specified resolution (x, y). Save the modified folder to the given path. Then output the resolution of all images in the modified folder.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testresize_and_rename_images:\n def test_resize_and_rename_images_1(self, capsys):\n resize_and_rename_images('test1/input', 'test1/output', (800, 600))\n captured = capsys.readouterr()\n assert captured.out == \"Modified images resolutions:\\n001.jpg: 800 x 600\\n002.jpg: 800 x 600\\n003.jpg: 800 x 600\\n\"\n\n", "problem": "Use Python to convert the images in the folder to RGB format, then number the images from smallest to largest, and change the resolution of all images to a specified resolution (x, y). Save the modified folder to the given path. Then output the resolution of all images in the modified folder.", "testcases": "from PIL import Image\n\nclass Testresize_and_rename_images:\n def test_resize_and_rename_images_2(self, capsys):\n resize_and_rename_images('test2/input', 'test2/output', (1024, 768))\n captured = capsys.readouterr()\n assert captured.out == \"Modified images resolutions:\\n001.jpg: 1024 x 768\\n002.jpg: 1024 x 768\\n\"\n\n def test_resize_and_rename_images_3(self, capsys):\n resize_and_rename_images('test3/input', 'test3/output', (1920, 1080))\n captured = capsys.readouterr()\n assert captured.out == \"Modified images resolutions:\\n001.jpg: 1920 x 1080\\n\"\n\n def test_resize_and_rename_images_4(self, capsys):\n resize_and_rename_images('test4/input', 'test4/output', (1280, 720))\n captured = capsys.readouterr()\n assert captured.out == \"Modified images resolutions:\\n001.jpg: 1280 x 720\\n002.jpg: 1280 x 720\\n003.jpg: 1280 x 720\\n004.jpg: 1280 x 720\\n005.jpg: 1280 x 720\\n006.jpg: 1280 x 720\\n007.jpg: 1280 x 720\\n008.jpg: 1280 x 720\\n\"\n\n def test_resize_and_rename_images_5(self, capsys):\n resize_and_rename_images('test5/input', 'test5/output', (1600, 900))\n captured = capsys.readouterr()\n assert captured.out == \"Modified images resolutions:\\n001.jpg: 1600 x 900\\n002.jpg: 1600 x 900\\n\"\n\n def test_resize_and_rename_images_6(self, capsys):\n resize_and_rename_images('test6/input', 'test6/output', (2560, 1440))\n captured = capsys.readouterr()\n assert captured.out == \"Modified images resolutions:\\n001.jpg: 2560 x 1440\\n002.jpg: 2560 x 1440\\n003.jpg: 2560 x 1440\\n\"\n\n def test_resize_and_rename_images_7(self, capsys):\n resize_and_rename_images('test7/input', 'test7/output', (800, 600))\n captured = capsys.readouterr()\n assert captured.out == \"Modified images resolutions:\\n\"\n", "setup_code": "", "reference_solution": "```python\nfrom PIL import Image\nimport os\n\n\ndef resize_and_rename_images(input_folder, output_folder, target_resolution=(800, 600)):\n if not os.path.exists(output_folder):\n os.makedirs(output_folder)\n image_files = [f for f in os.listdir(input_folder) if f.endswith(('.png', '.jpg', '.jpeg'))]\n image_files.sort() # 按文件名排序\n for i, image_file in enumerate(image_files):\n input_path = os.path.join(input_folder, image_file)\n output_path = os.path.join(output_folder, f\"{i + 1:03d}.jpg\") # 格式化文件名\n\n # 打开图片\n img = Image.open(input_path)\n\n # 转换为RGB模式\n img = img.convert(\"RGB\")\n\n # 统一分辨率\n img = img.resize(target_resolution, Image.LANCZOS)\n\n # 保存图片\n img.save(output_path)\n\n print(\"Modified images resolutions:\")\n print_resolutions(output_folder)\n return output_folder\n\n\ndef print_resolutions(folder_path):\n image_files = [f for f in os.listdir(folder_path) if f.endswith(('.png', '.jpg', '.jpeg'))]\n image_files.sort()\n\n for image_file in image_files:\n image_path = os.path.join(folder_path, image_file)\n img = Image.open(image_path)\n resolution = img.size\n print(f\"{image_file}: {resolution[0]} x {resolution[1]}\")\n\n\nresize_and_rename_images('test6/input', 'test6/output', (2560, 1440))\n```", "classification": "Software Engineering"}
{"_id": 169, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nPlease implement focal loss, a method proposed in 2017. Specifically, initialize two parameters alpha and gamma. The forward function receives inputs and targets representing the model output and GT.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Test__init__:\n def test_focal_loss_1(self):\n criterion = FocalLoss(alpha=0.25, gamma=2.0)\n inputs = torch.tensor([0.1, 0.2, 0.4, 0.8, 1.2, -0.1, -0.2, -0.4, -0.8, -1.2], requires_grad=True)\n targets = torch.tensor([0., 0., 0., 1., 1., 0., 0., 0., 1., 1.])\n assert torch.allclose(criterion(inputs, targets).detach(), torch.tensor(0.0649), atol=1e-4)\n\n", "problem": "Please implement focal loss, a method proposed in 2017. Specifically, initialize two parameters alpha and gamma. The forward function receives inputs and targets representing the model output and GT.", "testcases": "import torch\nimport torch.nn as nn\n\nclass Test__init__:\n def test_focal_loss_2(self):\n criterion = FocalLoss(alpha=0.5, gamma=2.0)\n inputs = torch.tensor([0.1, 0.2, 0.4, 0.8, 1.2, -0.1, -0.2, -0.4, -0.8, -1.2], requires_grad=True)\n targets = torch.tensor([0., 0., 0., 1., 1., 0., 0., 0., 1., 1.])\n assert torch.allclose(criterion(inputs, targets).detach(), torch.tensor(0.1297), atol=1e-4)\n\n def test_focal_loss_3(self):\n criterion = FocalLoss(alpha=0.25, gamma=3.0)\n inputs = torch.tensor([0.1, 0.2, 0.4, 0.8, 1.2, -0.1, -0.2, -0.4, -0.8, -1.2], requires_grad=True)\n targets = torch.tensor([0., 0., 0., 1., 1., 0., 0., 0., 1., 1.])\n assert torch.allclose(criterion(inputs, targets).detach(), torch.tensor(0.0414), atol=1e-4)\n\n def test_focal_loss_4(self):\n criterion = FocalLoss(alpha=0.25, gamma=2.0)\n inputs = torch.tensor([0.1, 0.2, 0.4, 0.8, 1.2, -0.1, -0.2, -0.4, -0.8, -1.2], requires_grad=True)\n targets = torch.tensor([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])\n assert torch.allclose(criterion(inputs, targets).detach(), torch.tensor(0.0649), atol=1e-4)\n\n def test_focal_loss_5(self):\n criterion = FocalLoss(alpha=0.25, gamma=2.0)\n inputs = torch.tensor([0.1, 0.2, 0.4, 0.8, 1.2, -0.1, -0.2, -0.4, -0.8, -1.2], requires_grad=True)\n targets = torch.tensor([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])\n assert torch.allclose(criterion(inputs, targets).detach(), torch.tensor(0.0649), atol=1e-4)\n\n def test_focal_loss_6(self):\n criterion = FocalLoss(alpha=0.25, gamma=2.0)\n inputs = torch.tensor([0.1, 0.2, 0.4, 0.8, 1.2, -0.1, -0.2, -0.4, -0.8, -1.2], requires_grad=True)\n targets = torch.tensor([0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5])\n assert torch.allclose(criterion(inputs, targets).detach(), torch.tensor(0.0524), atol=1e-4)\n\n def test_focal_loss_7(self):\n criterion = FocalLoss(alpha=0.25, gamma=2.0)\n inputs = torch.tensor([0.1, 0.2, 0.4, 0.8, 1.2, -0.1, -0.2, -0.4, -0.8, -1.2], requires_grad=True)\n targets = torch.tensor([0., 1., 0., 1., 0., 1., 0., 1., 0., 1.])\n assert torch.allclose(criterion(inputs, targets).detach(), torch.tensor(0.0777), atol=1e-4)\n\n def test_focal_loss_8(self):\n criterion = FocalLoss(alpha=0.25, gamma=2.0)\n inputs = torch.tensor([0.1, 0.2, 0.4, 0.8, 1.2, -0.1, -0.2, -0.4, -0.8, -1.2], requires_grad=True)\n targets = torch.tensor([1., 0., 1., 0., 1., 0., 1., 0., 1., 0.])\n assert torch.allclose(criterion(inputs, targets).detach(), torch.tensor(0.0520), atol=1e-4)\n\n def test_focal_loss_9(self):\n criterion = FocalLoss(alpha=0.25, gamma=2.0)\n inputs = torch.tensor([0.1, 0.2, 0.4, 0.8, 1.2, -0.1, -0.2, -0.4, -0.8, -1.2], requires_grad=True)\n targets = torch.tensor([0., 0., 0., 0., 0., 1., 1., 1., 1., 1.])\n assert torch.allclose(criterion(inputs, targets).detach(), torch.tensor(0.1098), atol=1e-4)\n\n def test_focal_loss_10(self):\n criterion = FocalLoss(alpha=0.25, gamma=2.0)\n inputs = torch.tensor([0.1, 0.2, 0.4, 0.8, 1.2, -0.1, -0.2, -0.4, -0.8, -1.2], requires_grad=True)\n targets = torch.tensor([1., 1., 1., 1., 1., 0., 0., 0., 0., 0.])\n assert torch.allclose(criterion(inputs, targets).detach(), torch.tensor(0.0200), atol=1e-4)", "setup_code": "", "reference_solution": "```python\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass FocalLoss(nn.Module):\n def __init__(self, alpha=0.25, gamma=2.0):\n super(FocalLoss, self).__init__()\n self.alpha = alpha\n self.gamma = gamma\n\n def forward(self, inputs, targets):\n \n BCE_loss = F.binary_cross_entropy_with_logits(inputs, targets, reduction='none')\n pt = torch.exp(-BCE_loss) \n focal_loss = self.alpha * (1-pt)**self.gamma * BCE_loss\n return focal_loss.mean()\n\n\ncriterion = FocalLoss(alpha=0.25, gamma=2.0)\ninputs = torch.tensor([0.1, 0.2, 0.4, 0.8, 1.2, -0.1, -0.2, -0.4, -0.8, -1.2], requires_grad=True)\ntargets = torch.tensor([1., 0., 1., 0., 1., 0., 1., 0., 1., 0.])\n\nloss = criterion(inputs, targets).detach()\nprint(loss)\n\n\n```", "classification": "Artificial Intelligence"}
{"_id": 170, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nUse a Python function to accept two path parameters, copy the file pointed to by the first path parameter and move it to the folder pointed to by the second path parameter. If the file does not exist, output \"File not exist.\".\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testcopy_and_move_file:\n def test_copy_and_move_file_1(self):\n copy_and_move_file('test1/test.txt', 'test1/target')\n assert os.path.exists('test1/target/test.txt')\n\n", "problem": "Use a Python function to accept two path parameters, copy the file pointed to by the first path parameter and move it to the folder pointed to by the second path parameter. If the file does not exist, output \"File not exist.\".", "testcases": "import os\n\nclass Testcopy_and_move_file:\n def test_copy_and_move_file_2(self, capsys):\n copy_and_move_file('test2/test.txt', 'test2/target')\n captured = capsys.readouterr()\n assert captured.out == \"File not exist.\\n\"\n\n def test_copy_and_move_file_3(self):\n copy_and_move_file('test3/source/test.txt', 'test3')\n assert os.path.exists('test3/test.txt')\n\n def test_copy_and_move_file_4(self):\n with pytest.raises(FileNotFoundError):\n copy_and_move_file('test4/test.txt', 'test4/target')\n\n def test_copy_and_move_file_5(self):\n copy_and_move_file('test5/source/test.txt', 'test5/target')\n assert os.path.exists('test5/target/test.txt')\n\n def test_copy_and_move_file_6(self):\n copy_and_move_file('test6/test.txt', 'test6/target')\n assert os.path.exists('test6/target/test.txt')", "setup_code": "", "reference_solution": "```python\nimport os\nimport shutil\n\n\ndef copy_and_move_file(source_path, destination_directory):\n # 获取源文件的文件名\n file_name = os.path.basename(source_path)\n\n # 构建目标路径\n destination_path = os.path.join(destination_directory, file_name)\n\n # 检查源文件是否存在\n if os.path.exists(source_path):\n # 复制文件\n shutil.copy(source_path, destination_path)\n else:\n print(\"File not exist.\")\n\n```", "classification": "Operation System"}
{"_id": 171, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nDefine a Python function that uses the docx package to read a Word document, then merges all the paragraph texts in the document into a single string. Iterate through the keyword list, counting the number of times each keyword appears in the string. Finally, call the function to output the results.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testcount_keywords_in_docx:\n def test_count_keywords_in_docx_1(self):\n doc = Document()\n doc.add_paragraph('test'*10+'python'*5+'docx'*3)\n doc.save('test1.docx')\n assert count_keywords_in_docx('test1.docx', ['test', 'python', 'docx']) == {'test': 10, 'python': 5, 'docx': 3}\n\n", "problem": "Define a Python function that uses the docx package to read a Word document, then merges all the paragraph texts in the document into a single string. Iterate through the keyword list, counting the number of times each keyword appears in the string. Finally, call the function to output the results.", "testcases": "from docx import Document\n\n\nclass Testcount_keywords_in_docx:\n def test_count_keywords_in_docx_2(self):\n doc = Document()\n doc.add_paragraph('word' * 7 + 'document' * 4 + 'paragraph' * 2)\n doc.save('test2.docx')\n assert count_keywords_in_docx('test2.docx', ['word', 'document', 'paragraph']) == {'word': 7, 'document': 4, 'paragraph': 2}\n\n def test_count_keywords_in_docx_3(self):\n doc = Document()\n doc.add_paragraph('string' * 5 + 'join' * 2 + 'for' * 7)\n doc.save('test3.docx')\n assert count_keywords_in_docx('test3.docx', ['string', 'join', 'for']) == {'string': 5, 'join': 2, 'for': 7}\n\n def test_count_keywords_in_docx_4(self):\n doc = Document()\n doc.add_paragraph('in' * 10 + 'the' * 15 + 'and' * 7)\n doc.save('test4.docx')\n assert count_keywords_in_docx('test4.docx', ['in', 'the', 'and']) == {'in': 10, 'the': 15, 'and': 7}\n\n def test_count_keywords_in_docx_5(self):\n doc = Document()\n doc.add_paragraph('test' * 10 + 'python' * 5 + 'docx' * 3)\n doc.save('test5.docx')\n assert count_keywords_in_docx('test5.docx', []) == {}\n\n def test_count_keywords_in_docx_6(self):\n doc = Document()\n doc.add_paragraph('test' * 10 + 'python' * 5 + 'docx' * 3)\n doc.save('test6.docx')\n assert count_keywords_in_docx('test6.docx', ['in', 'the', 'and']) == {'and': 0, 'in': 0, 'the': 0}\n\n def test_count_keywords_in_docx_7(self):\n doc = Document()\n doc.add_paragraph('')\n doc.save('test7.docx')\n assert count_keywords_in_docx('test7.docx', ['test', 'python', 'docx']) == {'docx': 0, 'python': 0, 'test': 0}", "setup_code": "", "reference_solution": "```python\nfrom docx import Document\n\n\ndef count_keywords_in_docx(docx_path, keywords):\n doc = Document(docx_path)\n text = \" \".join([paragraph.text for paragraph in doc.paragraphs])\n\n keyword_counts = {}\n for keyword in keywords:\n count = text.lower().count(keyword.lower())\n keyword_counts[keyword] = count\n\n return keyword_counts\n\n```", "classification": "Software Engineering"}
{"_id": 172, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nWrite a Python function that accepts a path parameter, deletes all files in the specified path, and if successfully deleted, outputs \"Successfully delete the folder.\", otherwise outputs \"Can't delete the folder.\"\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testdelete_folder:\n def test_delete_folder_1(self, tmp_path):\n d = tmp_path / \"sub\"\n d.mkdir()\n delete_folder(str(d))\n assert not os.path.exists(str(d))\n\n", "problem": "Write a Python function that accepts a path parameter, deletes all files in the specified path, and if successfully deleted, outputs \"Successfully delete the folder.\", otherwise outputs \"Can't delete the folder.\"", "testcases": "import shutil\nimport os\n\n\nclass Testdelete_folder:\n def test_delete_folder_2(self, tmp_path):\n d = tmp_path / \"sub\"\n d.mkdir()\n (d / \"file.txt\").write_text(\"content\")\n delete_folder(str(d))\n assert not os.path.exists(str(d / \"file.txt\"))\n\n def test_delete_folder_3(self, tmp_path):\n d = tmp_path / \"sub\"\n d.mkdir()\n (d / \"file.txt\").write_text(\"content\")\n (d / \"subsub\").mkdir()\n delete_folder(str(d / 'subsub'))\n assert os.path.exists(str(d / \"file.txt\"))\n assert not os.path.exists(str(d / \"subsub\"))\n\n def test_delete_folder_4(self, tmp_path):\n d = tmp_path / \"sub\"\n d.mkdir()\n (d / \"file.txt\").write_text(\"content\")\n (d / \"subsub\").mkdir()\n (d / \"subsub\" / \"file.txt\").write_text(\"content\")\n delete_folder(str(d / \"subsub\"))\n assert not os.path.exists(str(d / \"subsub\" / \"file.txt\"))\n\n def test_delete_folder_5(self, tmp_path):\n d = tmp_path / \"sub\"\n d.mkdir()\n for i in range(1000):\n (d / f\"file{i}.txt\").write_text(\"content\")\n delete_folder(str(d))\n assert not os.path.exists(str(d / \"file1.txt\"))\n\n def test_delete_folder_6(self, tmp_path):\n d = tmp_path / \"sub\"\n d.mkdir()\n for i in range(1000):\n (d / f\"sub{i}\").mkdir()\n delete_folder(str(d / \"sub1\"))\n assert os.path.exists(str(d / \"sub2\"))\n assert not os.path.exists(str(d / \"sub1\"))\n\n def test_delete_folder_7(self, tmp_path):\n d = tmp_path / \"sub\"\n d.mkdir()\n for i in range(1000):\n (d / f\"sub{i}\").mkdir()\n (d / f\"sub{i}\" / \"file.txt\").write_text(\"content\")\n delete_folder(str(d / \"sub1\"))\n assert os.path.exists(str(d / \"sub2\" / \"file.txt\"))\n assert not os.path.exists(str(d / \"sub1\" / \"file.txt\"))", "setup_code": "", "reference_solution": "```python\nimport shutil\nimport os\n\ndef delete_folder(folder_path):\n try:\n if os.path.exists(folder_path):\n if os.path.isdir(folder_path):\n shutil.rmtree(folder_path)\n print(f\"Successfully delete the folder.\")\n else:\n print(f\"{folder_path} is not a directory\")\n else:\n print(f\"Path not exist: {folder_path}\")\n except Exception as e:\n print(f\"Can't delete the folder.\")\n\n```", "classification": "Software Engineering"}
{"_id": 173, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nConvert a scipy.sparse.csr_matrix to ndarray and save it in a npy file,\nwhere the initial csr_matrix is saved in a npz file and needs to be loaded before conversion.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testcsr_to_numpy:\n def test_csr_to_numpy_1(self):\n csr_to_numpy('test1/test.npz', 'test1/test.npy')\n assert np.array_equal(np.load('test1/test.npy'), np.load('test1/label.npy'))\n\n", "problem": "Convert a scipy.sparse.csr_matrix to ndarray and save it in a npy file,\nwhere the initial csr_matrix is saved in a npz file and needs to be loaded before conversion.", "testcases": "import numpy as np\nimport scipy.sparse as sp\n\n\nclass Testcsr_to_numpy:\n def test_csr_to_numpy_2(self):\n csr_to_numpy('test2/test.npz', 'test2/test.npy')\n assert np.array_equal(np.load('test2/test.npy'), np.load('test2/label.npy'))\n\n def test_csr_to_numpy_3(self):\n csr_to_numpy('test3/test.npz', 'test3/test.npy')\n assert np.array_equal(np.load('test3/test.npy'), np.load('test3/label.npy'))\n\n def test_csr_to_numpy_4(self):\n csr_to_numpy('test4/test.npz', 'test4/test.npy')\n assert np.array_equal(np.load('test4/test.npy'), np.load('test4/label.npy'))\n\n def test_csr_to_numpy_5(self):\n csr_to_numpy('test5/test.npz', 'test5/test.npy')\n assert np.array_equal(np.load('test5/test.npy'), np.load('test5/label.npy'))\n\n def test_csr_to_numpy_6(self):\n csr_to_numpy('test6/test.npz', 'test6/test.npy')\n assert np.array_equal(np.load('test6/test.npy'), np.load('test6/label.npy'))\n\n def test_csr_to_numpy_7(self):\n csr_to_numpy('test7/test.npz', 'test7/test.npy')\n assert np.array_equal(np.load('test7/test.npy'), np.load('test7/label.npy'))\n\n def test_csr_to_numpy_8(self):\n csr_to_numpy('test8/test.npz', 'test8/test.npy')\n assert np.array_equal(np.load('test8/test.npy'), np.load('test8/label.npy'))\n\n def test_csr_to_numpy_9(self):\n csr_to_numpy('test9/test.npz', 'test9/test.npy')\n assert np.array_equal(np.load('test9/test.npy'), np.load('test9/label.npy'))", "setup_code": "", "reference_solution": "```python\nimport numpy as np\nimport scipy.sparse as sp\n\n\ndef csr_to_numpy(input_file, output_file):\n input_arr_csr = sp.load_npz(input_file)\n input_arr = input_arr_csr.toarray()\n np.save(output_file, input_arr)\n\n```", "classification": "Data Science"}
{"_id": 174, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nCopy the source folder to multiple target directories using multithreading, with each thread handling a portion of the target folder's copy work. After all threads have finished, record the end time and output the duration.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testcopy_folder:\n def test_multithread_copy_1(self):\n multithread_copy(self.source_folder, self.dest_folders[:7])\n for folder in self.dest_folders[:7]:\n assert os.path.exists(os.path.join(folder, \"test_file.txt\"))\n\n", "problem": "Copy the source folder to multiple target directories using multithreading, with each thread handling a portion of the target folder's copy work. After all threads have finished, record the end time and output the duration.", "testcases": "import shutil\nimport os\nimport threading\n\nclass Testcopy_folder:\n def test_multithread_copy_2(self):\n multithread_copy(self.source_folder, self.dest_folders[:2])\n for folder in self.dest_folders[:2]:\n assert os.path.exists(os.path.join(folder, \"test_file.txt\"))\n\n def test_multithread_copy_3(self):\n multithread_copy(self.source_folder, self.dest_folders[:3])\n for folder in self.dest_folders[:3]:\n assert os.path.exists(os.path.join(folder, \"test_file.txt\"))\n\n def test_multithread_copy_4(self):\n multithread_copy(self.source_folder, self.dest_folders[:4])\n for folder in self.dest_folders[:4]:\n assert os.path.exists(os.path.join(folder, \"test_file.txt\"))\n\n def test_multithread_copy_5(self):\n multithread_copy(self.source_folder, self.dest_folders[:1])\n for folder in self.dest_folders[:1]:\n assert os.path.exists(os.path.join(folder, \"test_file.txt\"))\n\n def test_multithread_copy_6(self):\n multithread_copy(self.source_folder, self.dest_folders[:10])\n for folder in self.dest_folders[:10]:\n assert os.path.exists(os.path.join(folder, \"test_file.txt\"))\n\n def test_multithread_copy_7(self):\n multithread_copy(self.source_folder, self.dest_folders[:100])\n for folder in self.dest_folders[:100]:\n assert os.path.exists(os.path.join(folder, \"test_file.txt\"))\n\n def test_multithread_copy_8(self):\n multithread_copy(self.source_folder, self.dest_folders[:1000])\n for folder in self.dest_folders[:1000]:\n assert os.path.exists(os.path.join(folder, \"test_file.txt\"))\n\n def test_multithread_copy_9(self):\n multithread_copy(self.source_folder, self.dest_folders)\n for folder in self.dest_folders:\n assert os.path.exists(os.path.join(folder, \"test_file.txt\"))\n\n\n def setup_method(self):\n self.source_folder = \"source_folder\"\n self.dest_folders = [f\"dest_folder{i}\" for i in range(5000)]\n os.mkdir(self.source_folder)\n for folder in self.dest_folders:\n if os.path.exists(folder):\n shutil.rmtree(folder)\n with open(os.path.join(self.source_folder, \"test_file.txt\"), \"w\") as f:\n f.write(\"test\")\n\n def teardown_method(self):\n shutil.rmtree(self.source_folder)\n for folder in self.dest_folders:\n if os.path.exists(folder):\n shutil.rmtree(folder)\n", "setup_code": "", "reference_solution": "```python\nimport shutil\nimport os\nimport threading\nimport time\n\n\ndef copy_folder(source_folder, dest_folders):\n for dest_folder in dest_folders:\n try:\n if os.path.exists(dest_folder):\n shutil.rmtree(dest_folder)\n shutil.copytree(source_folder, dest_folder)\n print(\"success from {source_folder} to {dest_folder}\")\n except Exception as e:\n print(\"copy {source_folder} to {dest_folder} is err:{e}\")\ndef create_thread(source_folder, dest_folders):\n # 计算每个线程需要拷贝的目标文件夹数量\n threads_num = len(dest_folders)\n folders_per_thread = len(dest_folders) // threads_num\n\n threads = []\n for i in range(threads_num):\n start = i * folders_per_thread\n end = start + folders_per_thread\n if i == threads_num - 1:\n end = len(dest_folders)\n thread = threading.Thread(target=copy_folder, args=(source_folder, dest_folders[start:end]))\n threads.append(thread)\n \n return threads\n \ndef run(threads):\n # 记录开始时间\n start_time = time.time()\n # 启动所有线程\n for thread in threads:\n thread.start()\n # 等待所有线程结束\n for thread in threads:\n thread.join()\n # 记录结束时间并输出用时\n end_time = time.time()\n print(f\"time: {end_time - start_time} 秒\")\n \n \ndef multithread_copy(source_folder, dest_folders):\n threads = create_thread(source_folder, dest_folders)\n run(threads)\n\n```", "classification": "Operation System"}
{"_id": 175, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nConvert a sparse ndarray into a scipy.sparse.csr_matrix and save it in an npz file, where the initial ndarray is saved in an npy file and needs to be loaded before conversion.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testnumpy_to_csr:\n def test_case1(self):\n numpy_to_csr('test1/test.npy', 'test1/test.npz')\n test_arr = sp.load_npz('test1/test.npz').toarray()\n label_arr = sp.load_npz('test1/label.npz').toarray()\n assert np.array_equal(test_arr, label_arr)\n\n", "problem": "Convert a sparse ndarray into a scipy.sparse.csr_matrix and save it in an npz file, where the initial ndarray is saved in an npy file and needs to be loaded before conversion.", "testcases": "import numpy as np\nimport scipy.sparse as sp\n\n\nclass Testnumpy_to_csr:\n def test_case2(self):\n numpy_to_csr('test2/test.npy', 'test2/test.npz')\n test_arr = sp.load_npz('test2/test.npz').toarray()\n label_arr = sp.load_npz('test2/label.npz').toarray()\n assert np.array_equal(test_arr, label_arr)\n\n def test_case3(self):\n numpy_to_csr('test3/test.npy', 'test3/test.npz')\n test_arr = sp.load_npz('test3/test.npz').toarray()\n label_arr = sp.load_npz('test3/label.npz').toarray()\n assert np.array_equal(test_arr, label_arr)\n\n def test_case4(self):\n numpy_to_csr('test4/test.npy', 'test4/test.npz')\n test_arr = sp.load_npz('test4/test.npz').toarray()\n label_arr = sp.load_npz('test4/label.npz').toarray()\n assert np.array_equal(test_arr, label_arr)\n\n def test_case5(self):\n numpy_to_csr('test5/test.npy', 'test5/test.npz')\n test_arr = sp.load_npz('test5/test.npz').toarray()\n label_arr = sp.load_npz('test5/label.npz').toarray()\n assert np.array_equal(test_arr, label_arr)\n\n def test_case6(self):\n numpy_to_csr('test6/test.npy', 'test6/test.npz')\n test_arr = sp.load_npz('test6/test.npz').toarray()\n label_arr = sp.load_npz('test6/label.npz').toarray()\n assert np.array_equal(test_arr, label_arr)\n\n def test_case7(self):\n numpy_to_csr('test7/test.npy', 'test7/test.npz')\n test_arr = sp.load_npz('test7/test.npz').toarray()\n label_arr = sp.load_npz('test7/label.npz').toarray()\n assert np.array_equal(test_arr, label_arr)\n\n def test_case8(self):\n numpy_to_csr('test8/test.npy', 'test8/test.npz')\n test_arr = sp.load_npz('test8/test.npz').toarray()\n label_arr = sp.load_npz('test8/label.npz').toarray()\n assert np.array_equal(test_arr, label_arr)\n\n def test_case9(self):\n numpy_to_csr('test9/test.npy', 'test9/test.npz')\n test_arr = sp.load_npz('test9/test.npz').toarray()\n label_arr = sp.load_npz('test9/label.npz').toarray()\n assert np.array_equal(test_arr, label_arr)", "setup_code": "", "reference_solution": "```python\nimport numpy as np\nimport scipy.sparse as sp\n\ndef numpy_to_csr(input_file, output_file):\n input_arr = np.load(input_file)\n input_arr_csr = sp.csr_matrix(input_arr)\n sp.save_npz(output_file, input_arr_csr)\n```", "classification": "Data Science"}
{"_id": 176, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nCalculate the cosine similarity of two matrices using sklearn. The dimensions of matrix A and B are the same, initially stored in matrix_A.npy and matrix_B.npy. The final result is a similarity matrix with the same dimensions as matrix A and B, stored in cos_sim.npy.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testcalculate_similarity:\n def test_calculate_similarity_1(self):\n A = np.array([[1, 2], [3, 4]])\n B = np.array([[5, 6], [7, 8]])\n np.save('matrix_A.npy', A)\n np.save('matrix_B.npy', B)\n calculate_similarity('matrix_A.npy', 'matrix_B.npy', 'cos_sim.npy')\n result = np.load('cos_sim.npy')\n assert np.array_equal(result, cosine_similarity(A, B))\n\n", "problem": "Calculate the cosine similarity of two matrices using sklearn. The dimensions of matrix A and B are the same, initially stored in matrix_A.npy and matrix_B.npy. The final result is a similarity matrix with the same dimensions as matrix A and B, stored in cos_sim.npy.", "testcases": "import numpy as np\n\n\nclass Testcalculate_similarity:\n def test_calculate_similarity_2(self):\n A = np.array([[1, 0], [0, 1]])\n B = np.array([[0, 1], [1, 0]])\n np.save('matrix_A.npy', A)\n np.save('matrix_B.npy', B)\n calculate_similarity('matrix_A.npy', 'matrix_B.npy', 'cos_sim.npy')\n result = np.load('cos_sim.npy')\n assert np.array_equal(result, cosine_similarity(A, B))\n\n def test_calculate_similarity_3(self):\n A = np.array([[1, 1], [1, 1]])\n B = np.array([[1, 1], [1, 1]])\n np.save('matrix_A.npy', A)\n np.save('matrix_B.npy', B)\n calculate_similarity('matrix_A.npy', 'matrix_B.npy', 'cos_sim.npy')\n result = np.load('cos_sim.npy')\n assert np.array_equal(result, cosine_similarity(A, B))\n\n def test_calculate_similarity_4(self):\n A = np.array([[1, 2, 3], [4, 5, 6]])\n B = np.array([[7, 8, 9], [10, 11, 12]])\n np.save('matrix_A.npy', A)\n np.save('matrix_B.npy', B)\n calculate_similarity('matrix_A.npy', 'matrix_B.npy', 'cos_sim.npy')\n result = np.load('cos_sim.npy')\n assert np.array_equal(result, cosine_similarity(A, B))\n\n def test_calculate_similarity_5(self):\n A = np.array([[1, 0, 0], [0, 1, 0]])\n B = np.array([[0, 0, 1], [0, 1, 0]])\n np.save('matrix_A.npy', A)\n np.save('matrix_B.npy', B)\n calculate_similarity('matrix_A.npy', 'matrix_B.npy', 'cos_sim.npy')\n result = np.load('cos_sim.npy')\n assert np.array_equal(result, cosine_similarity(A, B))\n\n def test_calculate_similarity_6(self):\n A = np.array([[1, 1, 1], [1, 1, 1]])\n B = np.array([[1, 1, 1], [1, 1, 1]])\n np.save('matrix_A.npy', A)\n np.save('matrix_B.npy', B)\n calculate_similarity('matrix_A.npy', 'matrix_B.npy', 'cos_sim.npy')\n result = np.load('cos_sim.npy')\n assert np.array_equal(result, cosine_similarity(A, B))\n\n def test_calculate_similarity_7(self):\n A = np.zeros((1000, 1000))\n B = np.ones((1000, 1000))\n np.save('matrix_A.npy', A)\n np.save('matrix_B.npy', B)\n calculate_similarity('matrix_A.npy', 'matrix_B.npy', 'cos_sim.npy')\n result = np.load('cos_sim.npy')\n assert np.array_equal(result, cosine_similarity(A, B))\n\n def test_calculate_similarity_8(self):\n A = np.ones((1000, 1000))\n B = np.ones((1000, 1000))\n np.save('matrix_A.npy', A)\n np.save('matrix_B.npy', B)\n calculate_similarity('matrix_A.npy', 'matrix_B.npy', 'cos_sim.npy')\n result = np.load('cos_sim.npy')\n assert np.array_equal(result, cosine_similarity(A, B))\n\n def test_calculate_similarity_9(self):\n A = np.eye(1000)\n B = np.eye(1000)\n np.save('matrix_A.npy', A)\n np.save('matrix_B.npy', B)\n calculate_similarity('matrix_A.npy', 'matrix_B.npy', 'cos_sim.npy')\n result = np.load('cos_sim.npy')\n assert np.array_equal(result, cosine_similarity(A, B))\n\n def test_calculate_similarity_10(self):\n A = np.random.rand(1000, 1000)\n B = np.random.rand(1000, 1000)\n np.save('matrix_A.npy', A)\n np.save('matrix_B.npy', B)\n calculate_similarity('matrix_A.npy', 'matrix_B.npy', 'cos_sim.npy')\n result = np.load('cos_sim.npy')\n assert np.array_equal(result, cosine_similarity(A, B))", "setup_code": "", "reference_solution": "```python\nimport numpy as np\nfrom sklearn.metrics.pairwise import cosine_similarity\n\n\ndef calculate_similarity(file_A, file_B, target_file):\n A = np.load(file_A)\n B = np.load(file_B)\n cos_sim = cosine_similarity(A, B)\n np.save(target_file, cos_sim)\n\n\n```", "classification": "Artificial Intelligence"}
{"_id": 177, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nConvert two numpy arrays of shape (X, Y, Z) into tensor type and single-precision floating point type. Change the shape of one of them to (X, Z, Y). Calculate the attention scores of these two matrices and output the results. Then write the results into a file named result.txt.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testprocess_tensor:\n def test_process_tensor_1(self):\n array1 = np.ones((3, 9, 5))\n array2 = np.ones((3, 9, 5))\n assert torch.all(torch.eq(process_tensor(array1, array2), torch.ones((3, 9, 9))*5))\n\n", "problem": "Convert two numpy arrays of shape (X, Y, Z) into tensor type and single-precision floating point type. Change the shape of one of them to (X, Z, Y). Calculate the attention scores of these two matrices and output the results. Then write the results into a file named result.txt.", "testcases": "import torch\n\nclass Testprocess_tensor:\n def test_process_tensor_2(self):\n array1 = np.zeros((3, 9, 5))\n array2 = np.ones((3, 9, 5))\n assert torch.all(torch.eq(process_tensor(array1, array2), torch.zeros((3, 9, 9))))\n\n def test_process_tensor_3(self):\n array1 = np.ones((3, 9, 5))*2\n array2 = np.ones((3, 9, 5))*3\n assert torch.all(torch.eq(process_tensor(array1, array2), torch.ones((3, 9, 9))*30))\n\n def test_process_tensor_4(self):\n array1 = np.ones((3, 9, 5))*-1\n array2 = np.ones((3, 9, 5))*-1\n assert torch.all(torch.eq(process_tensor(array1, array2), torch.ones((3, 9, 9))*5))\n\n def test_process_tensor_5(self):\n array1 = np.ones((3, 9, 5))*-1\n array2 = np.ones((3, 9, 5))\n assert torch.all(torch.eq(process_tensor(array1, array2), torch.ones((3, 9, 9))*-5))\n\n # boundary cases\n def test_process_tensor_6(self):\n array1 = np.ones((1, 1, 1))\n array2 = np.ones((1, 1, 1))\n assert torch.all(torch.eq(process_tensor(array1, array2), torch.ones((1, 1, 1))))\n\n def test_process_tensor_7(self):\n array1 = np.ones((100, 130, 80))\n array2 = np.ones((100, 130, 80))\n assert torch.all(torch.eq(process_tensor(array1, array2), torch.ones((100, 130, 130))*80))\n\n def test_process_tensor_8(self):\n array1 = np.ones((2, 2, 2))*np.inf\n array2 = np.ones((2, 2, 2))\n assert torch.all(torch.eq(process_tensor(array1, array2), torch.ones((2, 2, 2))*np.inf))\n\n def test_process_tensor_9(self):\n array1 = np.ones((2, 2, 2))*np.nan\n array2 = np.ones((2, 2, 2))\n assert torch.all(torch.isnan(process_tensor(array1, array2)))", "setup_code": "", "reference_solution": "```python\nimport torch\nimport numpy as np\n\n\ndef process_tensor(array1, array2):\n tensor1 = torch.FloatTensor(array1)\n tensor2 = torch.FloatTensor(array2)\n tensor2 = tensor2.permute(0, 2, 1)\n attention_scores = torch.bmm(tensor1, tensor2)\n with open('result.txt', 'w') as file:\n file.write(str(attention_scores))\n return attention_scores\n\n\narray1 = np.ones((100, 130, 80))\narray2 = np.ones((100, 130, 80))\nprint(process_tensor(array1, array2).shape)\n\n\n```", "classification": "Artificial Intelligence"}
{"_id": 178, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nWrite Euclidean, Manhattan, Chebyshev, Minkowski, Cosine similarity, Hamming distance, Jaccard similarity and other distance calculation methods in Python functions. Manually write data to call these distance calculation functions. Output the calculation results.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testeuclidean_distance:\n def test_euclidean_distance_1(self):\n assert euclidean_distance((1, 2, 3), (4, 5, 6)) == 5.196152422706632\n assert manhattan_distance((1, 2, 3), (4, 5, 6)) == 9\n assert chebyshev_distance((1, 2, 3), (4, 5, 6)) == 3\n assert minkowski_distance((1, 2, 3), (4, 5, 6), 2) == 6.244997998398398\n assert cosine_similarity([1, 2, 3], [4, 5, 6]) == 0.9746318461970762\n assert hamming_distance(\"1010101\", \"1001001\") == 3\n assert jaccard_similarity({1, 2, 3, 4, 5}, {4, 5, 6, 7, 8}) == 0.25\n\n", "problem": "Write Euclidean, Manhattan, Chebyshev, Minkowski, Cosine similarity, Hamming distance, Jaccard similarity and other distance calculation methods in Python functions. Manually write data to call these distance calculation functions. Output the calculation results.", "testcases": "\n\nclass Testeuclidean_distance:\n def test_euclidean_distance_2(self):\n assert euclidean_distance((0, 0), (0, 0)) == 0\n assert manhattan_distance((0, 0), (0, 0)) == 0\n assert chebyshev_distance((0, 0), (0, 0)) == 0\n assert minkowski_distance((0, 0), (0, 0), 2) == 1.4142135623730951\n assert cosine_similarity([0, 1], [0, 1]) == 1\n assert hamming_distance(\"0000000\", \"0000000\") == 0\n assert jaccard_similarity({1, 2, 3}, {4, 5, 6}) == 0\n\n def test_euclidean_distance_3(self):\n assert euclidean_distance((1, 1), (-1, -1)) == 2.8284271247461903\n assert manhattan_distance((1, 1), (-1, -1)) == 4\n assert chebyshev_distance((1, 1), (-1, -1)) == 2\n assert minkowski_distance((1, 1), (-1, -1), 2) == 2.0\n assert cosine_similarity([1, 1], [-1, -1]) == -0.9999999999999998\n assert hamming_distance(\"1111111\", \"0000000\") == 7\n assert jaccard_similarity({1, 2, 3}, {1, 2, 3}) == 1\n\n def test_euclidean_distance_4(self):\n assert euclidean_distance((1, 2, 3, 4), (5, 6, 7, 8)) == 8.0\n assert manhattan_distance((1, 2, 3, 4), (5, 6, 7, 8)) == 16\n assert chebyshev_distance((1, 2, 3, 4), (5, 6, 7, 8)) == 4\n assert minkowski_distance((1, 2, 3, 4), (5, 6, 7, 8), 2) == 18.439088914585774\n assert cosine_similarity([1, 2, 3, 4], [5, 6, 7, 8]) == 0.9688639316269662\n assert hamming_distance(\"1010101\", \"0101010\") == 7\n assert jaccard_similarity({1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}) == 0\n\n def test_euclidean_distance_5(self):\n assert euclidean_distance((1, 1, 1, 1), (2, 2, 2, 2)) == 2.0\n assert manhattan_distance((1, 1, 1, 1), (2, 2, 2, 2)) == 4\n assert chebyshev_distance((1, 1, 1, 1), (2, 2, 2, 2)) == 1\n assert minkowski_distance((1, 1, 1, 1), (2, 2, 2, 2), 2) == 2.0\n assert cosine_similarity([1] * 100, [100] * 100) == 1.0\n assert hamming_distance(\"1101001\", \"1010110\") == 6\n assert jaccard_similarity({143, 2, 1234, 4, 5, 23}, {422, 5, 346, 7343, 1234123, 1}) == 0.09090909090909091\n\n def test_euclidean_distance_6(self):\n assert euclidean_distance((1, 2, 3, 4, 5), (6, 7, 8, 9, 10)) == 11.180339887498949\n assert manhattan_distance((1, 2, 3, 4, 5), (6, 7, 8, 9, 10)) == 25\n assert chebyshev_distance((1, 2, 3, 4, 5), (6, 7, 8, 9, 10)) == 5\n assert minkowski_distance((1, 2, 3, 4, 5), (6, 7, 8, 9, 10), 2) == 62.489999199871974\n assert cosine_similarity([1] * 100 + [2] * 100 + [3] * 100, [100] * 300) == 0.9258200997725514\n assert hamming_distance(\"1100110\", \"0011001\") == 7\n assert jaccard_similarity({143, 2, 1234, 4, 5, 23, 123}, {1, 2, 3, 4, 5, 6, 7}) == 0.2727272727272727\n", "setup_code": "", "reference_solution": "```python\nimport math\n\ndef euclidean_distance(point1, point2):\n return math.sqrt(sum((p - q) ** 2 for p, q in zip(point1, point2)))\n\ndef manhattan_distance(point1, point2):\n return sum(abs(p - q) for p, q in zip(point1, point2))\n\ndef chebyshev_distance(point1, point2):\n return max(abs(p - q) for p, q in zip(point1, point2))\n\ndef minkowski_distance(point1, point2, p):\n return math.pow(sum(abs(p - q) ** p for p, q in zip(point1, point2)), 1/p)\n\ndef cosine_similarity(vector1, vector2):\n dot_product = sum(p * q for p, q in zip(vector1, vector2))\n norm_vector1 = math.sqrt(sum(p ** 2 for p in vector1))\n norm_vector2 = math.sqrt(sum(q ** 2 for q in vector2))\n return dot_product / (norm_vector1 * norm_vector2)\n\n\ndef hamming_distance(string1, string2):\n return sum(p != q for p, q in zip(string1, string2))\n\ndef jaccard_similarity(set1, set2):\n intersection_size = len(set1.intersection(set2))\n union_size = len(set1.union(set2))\n return intersection_size / union_size\n\n\n\n\n```", "classification": "Algorithm and Data Structure"}
{"_id": 179, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nAssuming there is a matrix of size=[N*N], how to set the values above its diagonal to zero, output the resulting matrix, then calculate the sum of the remaining values, and output the sum.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testdiag_zero:\n def test_diag_zero_1(self):\n matrix = np.arange(1, 10).reshape(3, 3)\n assert diag_zero(matrix) == 34\n\n", "problem": "Assuming there is a matrix of size=[N*N], how to set the values above its diagonal to zero, output the resulting matrix, then calculate the sum of the remaining values, and output the sum.", "testcases": "\n\nclass Testdiag_zero:\n def test_diag_zero_2(self):\n matrix = np.arange(1, 17).reshape(4, 4)\n assert diag_zero(matrix) == 100\n\n def test_diag_zero_3(self):\n matrix = np.arange(1, 26).reshape(5, 5)\n assert diag_zero(matrix) == 235\n\n def test_diag_zero_4(self):\n matrix = np.arange(1, 37).reshape(6, 6)\n assert diag_zero(matrix) == 476\n\n def test_diag_zero_5(self):\n matrix = np.arange(1, 50).reshape(7, 7)\n assert diag_zero(matrix) == 868\n\n def test_diag_zero_6(self):\n matrix = np.arange(1, 65).reshape(8, 8)\n assert diag_zero(matrix) == 1464\n\n def test_diag_zero_7(self):\n matrix = np.ones((1, 1))\n assert diag_zero(matrix) == 1\n\n def test_diag_zero_8(self):\n matrix = np.ones((2, 2))\n assert diag_zero(matrix) == 3\n\n def test_diag_zero_9(self):\n matrix = np.ones((3, 3))\n assert diag_zero(matrix) == 6\n\n def test_diag_zero_10(self):\n matrix = np.ones((4, 4))\n assert diag_zero(matrix) == 10", "setup_code": "", "reference_solution": "```python\nimport numpy as np\n\ndef diag_zero(matrix):\n matrix[np.triu_indices(matrix.shape[0], k=1)] = 0\n sum_remaining_values = np.sum(matrix)\n return sum_remaining_values\n\nmatrix = np.arange(1, 10).reshape(3, 3)\nprint(diag_zero(matrix))\n\n\n```", "classification": "Algorithm and Data Structure"}
{"_id": 180, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nAssume there is a numpy array of size=[N, N]. Calculate the average of the array elements, then keep the elements that are greater than the average unchanged, set the elements that are less than the average to 1, flatten the array into a one-dimensional list, and output the result.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testarray_avg:\n def test_array_avg_1(self):\n matrix = np.array([[2,1,4,3],[4,5,8,9],[10,2,3,4],[1,14,21,2]])\n mean_value, flattened_array = array_avg(matrix)\n assert mean_value == 5.8125\n assert np.all(flattened_array == np.array([2, 1, 4, 3, 4, 5, 0, 0, 0, 2, 3, 4, 1, 0, 0, 2]))\n\n", "problem": "Assume there is a numpy array of size=[N, N]. Calculate the average of the array elements, then keep the elements that are greater than the average unchanged, set the elements that are less than the average to 1, flatten the array into a one-dimensional list, and output the result.", "testcases": "\n\nclass Testarray_avg:\n def test_array_avg_2(self):\n matrix = np.array([[1,1,1,1],[1,1,1,1],[1,1,1,1],[1,1,1,1]])\n mean_value, flattened_array = array_avg(matrix)\n assert mean_value == 1\n assert np.all(flattened_array == np.array([1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]))\n\n def test_array_avg_3(self):\n matrix = np.array([[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]])\n mean_value, flattened_array = array_avg(matrix)\n assert mean_value == 0\n assert np.all(flattened_array == np.array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]))\n\n def test_array_avg_4(self):\n matrix = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]])\n mean_value, flattened_array = array_avg(matrix)\n assert mean_value == 8.5\n assert np.all(flattened_array == np.array([1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0]))\n\n def test_array_avg_5(self):\n matrix = np.array([[10,20,30,40],[50,60,70,80],[90,100,110,120],[130,140,150,160]])\n mean_value, flattened_array = array_avg(matrix)\n assert mean_value == 85\n assert np.all(flattened_array == np.array([10, 20, 30, 40, 50, 60, 70, 80, 0, 0, 0, 0, 0, 0, 0, 0]))\n\n def test_array_avg_6(self):\n matrix = np.array([[1,2,3,4],[4,3,2,1],[1,2,3,4],[4,3,2,1]])\n mean_value, flattened_array = array_avg(matrix)\n assert mean_value == 2.5\n assert np.all(flattened_array == np.array([1, 2, 0, 0, 0, 0, 2, 1, 1, 2, 0, 0, 0, 0, 2, 1]))\n\n def test_array_avg_7(self):\n matrix = np.array([[1,1,1,1],[2,2,2,2],[3,3,3,3],[4,4,4,4]])\n mean_value, flattened_array = array_avg(matrix)\n assert mean_value == 2.5\n assert np.all(flattened_array == np.array([1, 1, 1, 1, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0]))\n\n def test_array_avg_8(self):\n matrix = np.array([[1,1,1,1],[1,1,1,1],[1,1,1,1],[100,100,100,100]])\n mean_value, flattened_array = array_avg(matrix)\n assert mean_value == 25.75\n assert np.all(flattened_array == np.array([1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0]))\n\n def test_array_avg_9(self):\n matrix = np.array([[1,1,1,1],[1,1,1,1],[1,1,1,1],[1000,1000,1000,1000]])\n mean_value, flattened_array = array_avg(matrix)\n assert mean_value == 250.75\n assert np.all(flattened_array == np.array([1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0]))\n\n def test_array_avg_10(self):\n matrix = np.array([[1,1,1,1],[1,1,1,1],[1,1,1,1],[10000,10000,10000,10000]])\n mean_value, flattened_array = array_avg(matrix)\n assert mean_value == 2500.75\n assert np.all(flattened_array == np.array([1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0]))", "setup_code": "", "reference_solution": "```python\nimport numpy as np\n\n\ndef array_avg(matrix):\n # 计算数组元素的平均值\n mean_value = np.mean(matrix)\n\n # 大于平均值的元素置为零\n matrix[matrix > mean_value] = 0\n\n # 将数组展开为一维列表\n flattened_array = matrix.flatten()\n return mean_value, flattened_array\n\nmatrix = [[2,1,4,3],[4,5,8,9],[10,2,3,4],[1,14,21,2]]\nmatrix = np.array(matrix)\nprint(array_avg(matrix))\n\n```", "classification": "Algorithm and Data Structure"}
{"_id": 181, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nThere is a directory with multiple subdirectories, each subdirectory contains a different number of files. Please write a Python program to calculate the total number of files in this directory and print it out.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testcount_files:\n def test_case1(self, tmpdir):\n p = tmpdir.mkdir(\"sub\").join(\"hello.txt\")\n p.write(\"content\")\n assert count_files(tmpdir) == 1\n\n", "problem": "There is a directory with multiple subdirectories, each subdirectory contains a different number of files. Please write a Python program to calculate the total number of files in this directory and print it out.", "testcases": "\n\nclass Testcount_files:\n def test_case2(self, tmpdir):\n p1 = tmpdir.mkdir(\"sub1\").join(\"hello.txt\")\n p1.write(\"content\")\n p2 = tmpdir.mkdir(\"sub2\").join(\"world.txt\")\n p2.write(\"content\")\n assert count_files(tmpdir) == 2\n\n def test_case3(self, tmpdir):\n p1 = tmpdir.mkdir(\"sub1\").join(\"hello.txt\")\n p1.write(\"content\")\n p2 = tmpdir.mkdir(\"sub2\").join(\"world.txt\")\n p2.write(\"content\")\n p3 = tmpdir.mkdir(\"sub3\").join(\"file.txt\")\n p3.write(\"content\")\n assert count_files(tmpdir) == 3\n\n def test_case4(self, tmpdir):\n p1 = tmpdir.mkdir(\"sub1\").join(\"hello.txt\")\n p1.write(\"content\")\n p2 = tmpdir.mkdir(\"sub2\").join(\"world.txt\")\n p2.write(\"content\")\n assert count_files(tmpdir) == 2\n\n def test_case5(self, tmpdir):\n assert count_files(tmpdir) == 0\n\n def test_case6(self, tmpdir):\n p1 = tmpdir.mkdir(\"sub1\").join(\"hello.txt\")\n p1.write(\"content\")\n p2 = tmpdir.mkdir(\"sub2\").join(\"world.txt\")\n p2.write(\"content\")\n p3 = tmpdir.mkdir(\"sub3\").join(\"file.txt\")\n p3.write(\"content\")\n p4 = tmpdir.mkdir(\"sub4\").join(\"example.txt\")\n p4.write(\"content\")\n assert count_files(tmpdir) == 4\n\n # Boundary test cases\n def test_case7(self, tmpdir):\n for i in range(100):\n p = tmpdir.mkdir(f\"sub{i}\").join(\"file.txt\")\n p.write(\"content\")\n assert count_files(tmpdir) == 100\n\n def test_case8(self, tmpdir):\n for i in range(1000):\n p = tmpdir.mkdir(f\"sub{i}\").join(\"file.txt\")\n p.write(\"content\")\n assert count_files(tmpdir) == 1000\n\n def test_case9(self, tmpdir):\n for i in range(500):\n p = tmpdir.mkdir(f\"sub{i}\").join(\"file.txt\")\n p.write(\"content\")\n assert count_files(tmpdir) == 500\n\n def test_case10(self, tmpdir):\n for i in range(10000):\n p = tmpdir.mkdir(f\"sub{i}\").join(\"file.txt\")\n p.write(\"content\")\n assert count_files(tmpdir) == 10000", "setup_code": "", "reference_solution": "```python\nimport os\n\ndef count_files(dir):\n count = 0\n for root, dirs, files in os.walk(dir):\n count += len(files)\n return count\n\n```", "classification": "Operation System"}
{"_id": 182, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nUse PCA in the sklearn library to reduce the dimensions of 'characters', and examine the interpretability of each principal component. Here, 'characters' is a pandas.DataFrame, where each row is a sample and each column is a feature, imported from ./characters.csv.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testpac_fit:\n def test_pac_fit_1(self):\n df = pd.DataFrame({'A': [1, 2, 3, 4, 5], 'B': [2, 3, 4, 5, 6], 'C': [3, 4, 5, 6, 7]})\n df.to_csv('test.csv', index=False)\n assert np.allclose(pac_fit('test.csv'), np.array([1.00000000e+00, 1.23259516e-32, 4.24471989e-95]), atol=1e-7)\n\n", "problem": "Use PCA in the sklearn library to reduce the dimensions of 'characters', and examine the interpretability of each principal component. Here, 'characters' is a pandas.DataFrame, where each row is a sample and each column is a feature, imported from ./characters.csv.", "testcases": "import pandas as pd\nfrom sklearn.preprocessing import StandardScaler\nimport numpy as np\n\n\nclass Testpac_fit:\n def test_pac_fit_2(self):\n df = pd.DataFrame({'A': [1, 1, 1, 1, 1], 'B': [1, 1, 1, 1, 1], 'C': [1, 1, 1, 1, 1]})\n df.to_csv('test.csv', index=False)\n assert np.isnan(pac_fit('test.csv')).all()\n\n def test_pac_fit_3(self):\n df = pd.DataFrame({'A': [1, 2, 3, 4, 5], 'B': [5, 4, 3, 2, 1], 'C': [2, 3, 4, 5, 6]})\n df.to_csv('test.csv', index=False)\n assert np.allclose(pac_fit('test.csv'), np.array([1.00000000e+00, 1.23259516e-32, 4.24471989e-95]), atol=1e-8)\n\n def test_pac_fit_4(self):\n df = pd.DataFrame({'A': [1, 2, 3, 4, 5], 'B': [2, 3, 4, 5, 6], 'C': [3, 4, 5, 6, 7]})\n df.to_csv('test.csv', index=False)\n assert np.allclose(pac_fit('test.csv'), np.array([1.00000000e+00, 1.23259516e-32, 4.24471989e-95]), atol=1e-8)\n\n def test_pac_fit_5(self):\n df = pd.DataFrame({'A': [1, 2, 3, 4, 5], 'B': [2, 3, 4, 5, 6], 'C': [3, 4, 5, 6, 7]})\n df.to_csv('test.csv', index=False)\n assert np.allclose(pac_fit('test.csv'), np.array([1.00000000e+00, 1.23259516e-32, 4.24471989e-95]), atol=1e-8)\n\n def test_pac_fit_6(self):\n df = pd.DataFrame({'A': [1, 2, 3, 4, 5], 'B': [2, 3, 4, 5, 6], 'C': [3, 4, 5, 6, 7]})\n df.to_csv('test.csv', index=False)\n assert np.allclose(pac_fit('test.csv'), np.array([1.00000000e+00, 1.23259516e-32, 4.24471989e-95]), atol=1e-8)\n\n def test_pac_fit_7(self):\n df = pd.DataFrame({'A': [1], 'B': [2], 'C': [3]})\n df.to_csv('test.csv', index=False)\n assert np.isnan(pac_fit('test.csv')).all()\n\n def test_pac_fit_8(self):\n df = pd.DataFrame({'A': [1, 2], 'B': [2, 3], 'C': [3, 4]})\n df.to_csv('test.csv', index=False)\n assert np.allclose(pac_fit('test.csv'), np.array([1.00000000e+00, 2.05432527e-33]), atol=1e-8)\n\n def test_pac_fit_9(self):\n df = pd.DataFrame({'A': [1, 2, 3], 'B': [2, 3, 4], 'C': [3, 4, 5]})\n df.to_csv('test.csv', index=False)\n assert np.allclose(pac_fit('test.csv'), np.array([1.00000000e+00, 1.23259516e-32, 4.24471989e-95]), atol=1e-8)\n\n def test_pac_fit_10(self):\n df = pd.DataFrame({'A': [1, 2, 3, 4], 'B': [2, 3, 4, 5], 'C': [3, 4, 5, 6]})\n df.to_csv('test.csv', index=False)\n assert np.allclose(pac_fit('test.csv'), np.array([1.00000000e+00, 1.23259516e-32, 4.24471989e-95]), atol=1e-8)", "setup_code": "", "reference_solution": "```python\nimport pandas as pd\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.decomposition import PCA\n\ndef pac_fit(input_file):\n characters = pd.read_csv(input_file)\n characters = StandardScaler().fit_transform(characters)\n pca = PCA().fit(characters)\n return pca.explained_variance_ratio_\n\n\ndf = pd.DataFrame({'A': [1, 2], 'B': [2, 3], 'C': [3, 4]})\ndf.to_csv('test.csv', index=False)\nprint(pac_fit('test.csv'))\n```", "classification": "Artificial Intelligence"}
{"_id": 183, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nDesign a backup program, which should be written in Python. The program input is the source path and the target path. It should complete the backup of the contents under the specified folder (for example, the data folder). Each backup should include a timestamp, and the backup files should be compressed. The compressed backup files should be stored in another specified folder (for example, the backup folder). There may already be some backup files in the backup folder. When the total size of the backup folder exceeds a threshold (MB), the program should automatically delete the oldest backup files to free up space.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testbackup:\n def test_backup_1(self, tmp_path):\n source_path = tmp_path / \"source\"\n backup_folder = tmp_path / \"backup\"\n source_path.mkdir()\n backup_folder.mkdir()\n (source_path / \"file1.txt\").write_text(\"Hello, World!\")\n backup(source_path, backup_folder)\n assert len(list(backup_folder.glob(\"*.zip\"))) == 1\n\n", "problem": "Design a backup program, which should be written in Python. The program input is the source path and the target path. It should complete the backup of the contents under the specified folder (for example, the data folder). Each backup should include a timestamp, and the backup files should be compressed. The compressed backup files should be stored in another specified folder (for example, the backup folder). There may already be some backup files in the backup folder. When the total size of the backup folder exceeds a threshold (MB), the program should automatically delete the oldest backup files to free up space.", "testcases": "import os\nimport shutil\nimport zipfile\nfrom datetime import datetime\nimport time\n\n\nclass Testbackup:\n def test_backup_2(self, tmp_path):\n source_path = tmp_path / \"source\"\n backup_folder = tmp_path / \"backup\"\n source_path.mkdir()\n backup_folder.mkdir()\n (source_path / \"file1.txt\").write_text(\"Hello, World!\")\n backup(source_path, backup_folder, max_size_mb=0.00001)\n assert len(list(backup_folder.glob(\"*.zip\"))) == 0\n\n def test_backup_3(self, tmp_path):\n source_path = tmp_path / \"source\"\n backup_folder = tmp_path / \"backup\"\n source_path.mkdir()\n backup_folder.mkdir()\n (source_path / \"file1.txt\").write_text(\"Hello, World!\")\n backup(source_path, backup_folder, max_size_mb=0.01)\n assert len(list(backup_folder.glob(\"*.zip\"))) == 1\n\n def test_backup_4(self, tmp_path):\n source_path = tmp_path / \"source\"\n backup_folder = tmp_path / \"backup\"\n source_path.mkdir()\n backup_folder.mkdir()\n (source_path / \"file1.txt\").write_text(\"Hello, World!\")\n backup(source_path, backup_folder, max_size_mb=0.01)\n time.sleep(1)\n backup(source_path, backup_folder, max_size_mb=0.01)\n assert len(list(backup_folder.glob(\"*.zip\"))) == 2\n\n def test_backup_5(self, tmp_path):\n source_path = tmp_path / \"source\"\n backup_folder = tmp_path / \"backup\"\n source_path.mkdir()\n backup_folder.mkdir()\n (source_path / \"file1.txt\").write_text(\"Hello, World!\")\n backup(source_path, backup_folder, max_size_mb=0.00001)\n time.sleep(1)\n backup(source_path, backup_folder, max_size_mb=0.02)\n assert len(list(backup_folder.glob(\"*.zip\"))) == 1\n\n def test_backup_6(self, tmp_path):\n source_path = tmp_path / \"source\"\n backup_folder = tmp_path / \"backup\"\n source_path.mkdir()\n backup_folder.mkdir()\n (source_path / \"file1.txt\").write_text(\"Hello, World!\")\n backup(source_path, backup_folder, max_size_mb=0.01)\n time.sleep(1)\n backup(source_path, backup_folder, max_size_mb=0.01)\n time.sleep(1)\n backup(source_path, backup_folder, max_size_mb=0.01)\n assert len(list(backup_folder.glob(\"*.zip\"))) == 3\n\n def test_backup_7(self, tmp_path):\n source_path = tmp_path / \"source\"\n backup_folder = tmp_path / \"backup\"\n source_path.mkdir()\n backup_folder.mkdir()\n (source_path / \"file1.txt\").write_text(\"Hello, World!\")\n backup(source_path, backup_folder, max_size_mb=0.01)\n time.sleep(1)\n backup(source_path, backup_folder, max_size_mb=0.01)\n time.sleep(1)\n backup(source_path, backup_folder, max_size_mb=0.01)\n time.sleep(1)\n backup(source_path, backup_folder, max_size_mb=0.01)\n time.sleep(1)\n assert len(list(backup_folder.glob(\"*.zip\"))) == 4\n\n def test_backup_8(self, tmp_path):\n source_path = tmp_path / \"source\"\n backup_folder = tmp_path / \"backup\"\n source_path.mkdir()\n backup_folder.mkdir()\n (source_path / \"file1.txt\").write_text(\"Hello, World!\")\n backup(source_path, backup_folder, max_size_mb=0.01)\n time.sleep(1)\n backup(source_path, backup_folder, max_size_mb=0.01)\n time.sleep(1)\n backup(source_path, backup_folder, max_size_mb=0.01)\n time.sleep(1)\n backup(source_path, backup_folder, max_size_mb=0.01)\n time.sleep(1)\n backup(source_path, backup_folder, max_size_mb=0.000001)\n assert len(list(backup_folder.glob(\"*.zip\"))) == 0\n\n def test_backup_9(self, tmp_path):\n source_path = tmp_path / \"source\"\n backup_folder = tmp_path / \"backup\"\n source_path.mkdir()\n backup_folder.mkdir()\n (source_path / \"file1.txt\").write_text(\"Hello, World!\")\n backup(source_path, backup_folder, max_size_mb=0.01)\n time.sleep(1)\n backup(source_path, backup_folder, max_size_mb=0.01)\n time.sleep(1)\n backup(source_path, backup_folder, max_size_mb=0.01)\n time.sleep(1)\n backup(source_path, backup_folder, max_size_mb=0.01)\n time.sleep(1)\n backup(source_path, backup_folder, max_size_mb=0.01)\n time.sleep(1)\n backup(source_path, backup_folder, max_size_mb=0.01)\n assert len(list(backup_folder.glob(\"*.zip\"))) == 6\n\n def test_backup_10(self, tmp_path):\n source_path = tmp_path / \"source\"\n backup_folder = tmp_path / \"backup\"\n source_path.mkdir()\n backup_folder.mkdir()\n (source_path / \"file1.txt\").write_text(\"Hello, World!\")\n backup(source_path, backup_folder, max_size_mb=0.000001)\n time.sleep(1)\n backup(source_path, backup_folder, max_size_mb=0.000001)\n time.sleep(1)\n backup(source_path, backup_folder, max_size_mb=0.000001)\n time.sleep(1)\n backup(source_path, backup_folder, max_size_mb=0.000001)\n time.sleep(1)\n backup(source_path, backup_folder, max_size_mb=0.000001)\n time.sleep(1)\n backup(source_path, backup_folder, max_size_mb=0.000001)\n time.sleep(1)\n backup(source_path, backup_folder, max_size_mb=0.000001)\n assert len(list(backup_folder.glob(\"*.zip\"))) == 0\n", "setup_code": "", "reference_solution": "```python\nimport os\nimport shutil\nimport zipfile\nfrom datetime import datetime\nimport glob\n\ndef backup(source_path, backup_folder, max_size_mb=10):\n # 创建备份文件夹\n if not os.path.exists(backup_folder):\n os.makedirs(backup_folder)\n\n # 生成时间戳\n timestamp = datetime.now().strftime('%Y%m%d%H%M%S')\n\n # 构建备份文件名\n backup_filename = f\"backup_{timestamp}.zip\"\n backup_path = os.path.join(backup_folder, backup_filename)\n\n # 备份文件夹\n shutil.make_archive(backup_path[:-4], 'zip', source_path)\n\n # 获取备份文件夹总大小\n total_size_mb = sum(os.path.getsize(f) for f in glob.glob(os.path.join(backup_folder, '*.zip'))) / (1024 ** 2)\n\n # 如果总大小超过设定的阈值,删除最旧的备份文件\n while total_size_mb > max_size_mb:\n oldest_backup = min(glob.glob(os.path.join(backup_folder, '*.zip')), key=os.path.getctime)\n total_size_mb -= os.path.getsize(oldest_backup) / (1024 ** 2)\n os.remove(oldest_backup)\n\n print(f\"Backup completed: {backup_path}\")\n```", "classification": "Operation System"}
{"_id": 184, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nPlease use Python language and PyTorch package to calculate the IOU of two sets of bounding boxes.\n\nEach set of bounding boxes has dimensions of [N, 4], representing N bounding boxes, and 4 represents [x, y, w, h].\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testbbox_iou:\n def test_bbox_iou_1(self):\n boxes1 = torch.tensor([[10, 20, 30, 40], [30, 40, 50, 60]])\n boxes2 = torch.tensor([[15, 25, 35, 45], [40, 50, 60, 70]])\n assert torch.allclose(bbox_iou(boxes1, boxes2), torch.tensor([0.5914, 0.5238]), atol=1e-4)\n\n", "problem": "Please use Python language and PyTorch package to calculate the IOU of two sets of bounding boxes.\n\nEach set of bounding boxes has dimensions of [N, 4], representing N bounding boxes, and 4 represents [x, y, w, h].", "testcases": "import torch\n\n\nclass Testbbox_iou:\n def test_bbox_iou_2(self):\n boxes1 = torch.tensor([[0, 0, 10, 10]])\n boxes2 = torch.tensor([[0, 0, 10, 10]])\n assert torch.allclose(bbox_iou(boxes1, boxes2), torch.tensor([1.0]), atol=1e-4)\n\n def test_bbox_iou_3(self):\n boxes1 = torch.tensor([[0, 0, 10, 10]])\n boxes2 = torch.tensor([[10, 10, 10, 10]])\n assert torch.allclose(bbox_iou(boxes1, boxes2), torch.tensor([0.0]), atol=1e-4)\n\n def test_bbox_iou_4(self):\n boxes1 = torch.tensor([[0, 0, 10, 10]])\n boxes2 = torch.tensor([[5, 5, 10, 10]])\n assert torch.allclose(bbox_iou(boxes1, boxes2), torch.tensor([0.1429]), atol=1e-4)\n\n def test_bbox_iou_5(self):\n boxes1 = torch.tensor([[0, 0, 10, 10]])\n boxes2 = torch.tensor([[5, 5, 5, 5]])\n assert torch.allclose(bbox_iou(boxes1, boxes2), torch.tensor([0.0526]), atol=1e-4)\n\n def test_bbox_iou_6(self):\n boxes1 = torch.tensor([[0, 0, 10, 10]])\n boxes2 = torch.tensor([[5, 5, 15, 15]])\n assert torch.allclose(bbox_iou(boxes1, boxes2), torch.tensor([0.2093]), atol=1e-4)\n\n def test_bbox_iou_7(self):\n boxes1 = torch.tensor([[0, 0, 0, 0]])\n boxes2 = torch.tensor([[0, 0, 0, 0]])\n assert torch.isnan(bbox_iou(boxes1, boxes2))\n\n def test_bbox_iou_8(self):\n boxes1 = torch.tensor([[0, 0, 100, 100]])\n boxes2 = torch.tensor([[0, 0, 100, 100]])\n assert torch.allclose(bbox_iou(boxes1, boxes2), torch.tensor([1.0]), atol=1e-4)\n\n def test_bbox_iou_9(self):\n boxes1 = torch.tensor([[0, 0, 100, 100]])\n boxes2 = torch.tensor([[100, 100, 100, 100]])\n assert torch.allclose(bbox_iou(boxes1, boxes2), torch.tensor([0.0]), atol=1e-4)\n\n def test_bbox_iou_10(self):\n boxes1 = torch.tensor([[0, 0, 100, 100]])\n boxes2 = torch.tensor([[50, 50, 100, 100]])\n assert torch.allclose(bbox_iou(boxes1, boxes2), torch.tensor([0.1429]), atol=1e-4)", "setup_code": "", "reference_solution": "```python\nimport torch\n\ndef bbox_iou(boxes1, boxes2):\n \"\"\"\n 计算两组对应位置bounding boxes的IoU。\n \n 参数:\n boxes1, boxes2: 维度为[N, 4]的tensor,表示bounding boxes,格式为[x, y, w, h]。\n \n 返回:\n 一个长度为N的tensor,表示boxes1和boxes2中对应box的IoU。\n \"\"\"\n assert boxes1.shape == boxes2.shape\n boxes1_x1 = boxes1[:, 0] - boxes1[:, 2] / 2\n boxes1_y1 = boxes1[:, 1] - boxes1[:, 3] / 2\n boxes1_x2 = boxes1[:, 0] + boxes1[:, 2] / 2\n boxes1_y2 = boxes1[:, 1] + boxes1[:, 3] / 2\n\n boxes2_x1 = boxes2[:, 0] - boxes2[:, 2] / 2\n boxes2_y1 = boxes2[:, 1] - boxes2[:, 3] / 2\n boxes2_x2 = boxes2[:, 0] + boxes2[:, 2] / 2\n boxes2_y2 = boxes2[:, 1] + boxes2[:, 3] / 2\n\n\n inter_x1 = torch.max(boxes1_x1, boxes2_x1)\n inter_y1 = torch.max(boxes1_y1, boxes2_y1)\n inter_x2 = torch.min(boxes1_x2, boxes2_x2)\n inter_y2 = torch.min(boxes1_y2, boxes2_y2)\n\n inter_area = torch.clamp(inter_x2 - inter_x1, min=0) * torch.clamp(inter_y2 - inter_y1, min=0)\n\n\n boxes1_area = (boxes1_x2 - boxes1_x1) * (boxes1_y2 - boxes1_y1)\n boxes2_area = (boxes2_x2 - boxes2_x1) * (boxes2_y2 - boxes2_y1)\n\n\n union_area = boxes1_area + boxes2_area - inter_area\n\n\n iou = inter_area / union_area\n\n return iou\n\n\n\n\n```", "classification": "Artificial Intelligence"}
{"_id": 185, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nWe need to analyze the access logs of the Nginx server and monitor users with high frequency access. This will help us identify potential abnormal activities, optimize performance, and respond promptly to possible attacks. We need to use python to count the number of accesses for each IP address in the nginx log. The statistical results should be stored in a data file under a data folder for further analysis and auditing.\nUsers with high frequency access are defined as those who access more than 30 times in one second.\nRequirement 1:\nUse a script to extract IP addresses from the Nginx access log and count the number of accesses for each IP address.\nRequirement 2: High frequency access monitoring\nIdentify and record IP addresses with high frequency access for subsequent processing. High frequency is defined as more than 30 accesses in one second. If this IP is a high-frequency abnormal IP, record it in a separate file for subsequent analysis.\nRequirement 3 Data output\nOutput the statistical results to a data file, the format includes the IP address and the corresponding number of accesses. This data file will be used for further analysis and auditing.\nRequirement 4 File format\nAll files are in JSON format, where the key is the IP address and the value is the number of accesses.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testnginx_log_analysis:\n def test_nginx_log_analysis_1(self, tmpdir):\n nginx_log_file = tmpdir.join(\"nginx.log\")\n nginx_log_file.write(\"192.168.1.1 - - [01/Jan/2021:00:00:01 +0000] \\\"GET / HTTP/1.1\\\" 200 612\\n\" * 35)\n statistics_output_file = tmpdir.join(\"statistics.json\")\n high_frequency_output_file = tmpdir.join(\"high_frequency.json\")\n nginx_log_analysis(nginx_log_file, statistics_output_file, high_frequency_output_file)\n with open(statistics_output_file, 'r') as f:\n assert json.load(f) == {\"192.168.1.1\": 35}\n with open(high_frequency_output_file, 'r') as f:\n assert json.load(f) == {\"192.168.1.1\": 35}\n\n", "problem": "We need to analyze the access logs of the Nginx server and monitor users with high frequency access. This will help us identify potential abnormal activities, optimize performance, and respond promptly to possible attacks. We need to use python to count the number of accesses for each IP address in the nginx log. The statistical results should be stored in a data file under a data folder for further analysis and auditing.\nUsers with high frequency access are defined as those who access more than 30 times in one second.\nRequirement 1:\nUse a script to extract IP addresses from the Nginx access log and count the number of accesses for each IP address.\nRequirement 2: High frequency access monitoring\nIdentify and record IP addresses with high frequency access for subsequent processing. High frequency is defined as more than 30 accesses in one second. If this IP is a high-frequency abnormal IP, record it in a separate file for subsequent analysis.\nRequirement 3 Data output\nOutput the statistical results to a data file, the format includes the IP address and the corresponding number of accesses. This data file will be used for further analysis and auditing.\nRequirement 4 File format\nAll files are in JSON format, where the key is the IP address and the value is the number of accesses.", "testcases": "import re\nfrom collections import defaultdict\n\nclass Testnginx_log_analysis:\n def test_nginx_log_analysis_2(self, tmpdir):\n nginx_log_file = tmpdir.join(\"nginx.log\")\n nginx_log_file.write(\"192.168.1.1 - - [01/Jan/2021:00:00:01 +0000] \\\"GET / HTTP/1.1\\\" 200 612\\n\" * 30)\n statistics_output_file = tmpdir.join(\"statistics.json\")\n high_frequency_output_file = tmpdir.join(\"high_frequency.json\")\n nginx_log_analysis(nginx_log_file, statistics_output_file, high_frequency_output_file)\n with open(statistics_output_file, 'r') as f:\n assert json.load(f) == {\"192.168.1.1\": 30}\n with open(high_frequency_output_file, 'r') as f:\n assert json.load(f) == {}\n\n def test_nginx_log_analysis_3(self, tmpdir):\n nginx_log_file = tmpdir.join(\"nginx.log\")\n nginx_log_file.write(\"\")\n statistics_output_file = tmpdir.join(\"statistics.json\")\n high_frequency_output_file = tmpdir.join(\"high_frequency.json\")\n nginx_log_analysis(nginx_log_file, statistics_output_file, high_frequency_output_file)\n with open(statistics_output_file, 'r') as f:\n assert json.load(f) == {}\n with open(high_frequency_output_file, 'r') as f:\n assert json.load(f) == {}\n\n def test_nginx_log_analysis_4(self, tmpdir):\n nginx_log_file = tmpdir.join(\"nginx.log\")\n content = \"192.168.1.1 - - [01/Jan/2021:00:00:01 +0000] \\\"GET / HTTP/1.1\\\" 200 612\\n\" * 20 + \"192.168.1.2 - - [01/Jan/2021:00:00:01 +0000] \\\"GET / HTTP/1.1\\\" 200 612\\n\" * 25\n nginx_log_file.write(content)\n statistics_output_file = tmpdir.join(\"statistics.json\")\n high_frequency_output_file = tmpdir.join(\"high_frequency.json\")\n nginx_log_analysis(nginx_log_file, statistics_output_file, high_frequency_output_file)\n with open(statistics_output_file, 'r') as f:\n assert json.load(f) == {\"192.168.1.1\": 20, \"192.168.1.2\": 25}\n with open(high_frequency_output_file, 'r') as f:\n assert json.load(f) == {}\n\n def test_nginx_log_analysis_5(self, tmpdir):\n nginx_log_file = tmpdir.join(\"nginx.log\")\n content = \"192.168.1.1 - - [01/Jan/2021:00:00:01 +0000] \\\"GET / HTTP/1.1\\\" 200 612\\n\" * 31 + \"192.168.1.2 - - [01/Jan/2021:00:00:01 +0000] \\\"GET / HTTP/1.1\\\" 200 612\\n\" * 31\n nginx_log_file.write(content)\n statistics_output_file = tmpdir.join(\"statistics.json\")\n high_frequency_output_file = tmpdir.join(\"high_frequency.json\")\n nginx_log_analysis(nginx_log_file, statistics_output_file, high_frequency_output_file)\n with open(statistics_output_file, 'r') as f:\n assert json.load(f) == {\"192.168.1.1\": 31, \"192.168.1.2\": 31}\n with open(high_frequency_output_file, 'r') as f:\n assert json.load(f) == {\"192.168.1.1\": 31, \"192.168.1.2\": 31}\n\n def test_nginx_log_analysis_6(self, tmpdir):\n nginx_log_file = tmpdir.join(\"nginx.log\")\n nginx_log_file.write(\"192.168.1.1 - - [01/Jan/2021:00:00:01 +0000] \\\"GET / HTTP/1.1\\\" 200 612\\n\" * 0)\n statistics_output_file = tmpdir.join(\"statistics.json\")\n high_frequency_output_file = tmpdir.join(\"high_frequency.json\")\n nginx_log_analysis(nginx_log_file, statistics_output_file, high_frequency_output_file)\n with open(statistics_output_file, 'r') as f:\n assert json.load(f) == {}\n with open(high_frequency_output_file, 'r') as f:\n assert json.load(f) == {}\n\n def test_nginx_log_analysis_7(self, tmpdir):\n nginx_log_file = tmpdir.join(\"nginx.log\")\n nginx_log_file.write(\"192.168.1.1 - - [01/Jan/2021:00:00:01 +0000] \\\"GET / HTTP/1.1\\\" 200 612\\n\" * 1)\n statistics_output_file = tmpdir.join(\"statistics.json\")\n high_frequency_output_file = tmpdir.join(\"high_frequency.json\")\n nginx_log_analysis(nginx_log_file, statistics_output_file, high_frequency_output_file)\n with open(statistics_output_file, 'r') as f:\n assert json.load(f) == {\"192.168.1.1\": 1}\n with open(high_frequency_output_file, 'r') as f:\n assert json.load(f) == {}\n\n def test_nginx_log_analysis_8(self, tmpdir):\n nginx_log_file = tmpdir.join(\"nginx.log\")\n nginx_log_file.write(\"192.168.1.1 - - [01/Jan/2021:00:00:01 +0000] \\\"GET / HTTP/1.1\\\" 200 612\\n\" * 100)\n statistics_output_file = tmpdir.join(\"statistics.json\")\n high_frequency_output_file = tmpdir.join(\"high_frequency.json\")\n nginx_log_analysis(nginx_log_file, statistics_output_file, high_frequency_output_file)\n with open(statistics_output_file, 'r') as f:\n assert json.load(f) == {\"192.168.1.1\": 100}\n with open(high_frequency_output_file, 'r') as f:\n assert json.load(f) == {\"192.168.1.1\": 100}\n\n def test_nginx_log_analysis_9(self, tmpdir):\n nginx_log_file = tmpdir.join(\"nginx.log\")\n nginx_log_file.write(\"192.168.1.1 - - [01/Jan/2021:00:00:01 +0000] \\\"GET / HTTP/1.1\\\" 200 612\\n\" * 500)\n statistics_output_file = tmpdir.join(\"statistics.json\")\n high_frequency_output_file = tmpdir.join(\"high_frequency.json\")\n nginx_log_analysis(nginx_log_file, statistics_output_file, high_frequency_output_file)\n with open(statistics_output_file, 'r') as f:\n assert json.load(f) == {\"192.168.1.1\": 500}\n with open(high_frequency_output_file, 'r') as f:\n assert json.load(f) == {\"192.168.1.1\": 500}", "setup_code": "", "reference_solution": "```python\nimport re\nfrom collections import defaultdict\nimport json\n\ndef nginx_log_analysis(nginx_log_file, statistics_output_file, high_frequency_output_file):\n # 定义一个字典用于存储IP地址访问次数\n ip_count = defaultdict(int)\n\n # 定义一个集合用于存储高频率访问的IP地址\n high_frequency_ips = defaultdict(int)\n \n # 定义正则表达式来匹配IP地址\n ip_pattern = re.compile(r'\\b(?:[0-9]{1,3}\\.){3}[0-9]{1,3}\\b')\n \n # 打开Nginx日志文件并逐行处理\n with open(nginx_log_file, 'r') as file:\n for line in file:\n # 使用正则表达式匹配IP地址\n match = ip_pattern.search(line)\n if match:\n ip_address = match.group(0)\n \n # 增加IP地址访问次数\n ip_count[ip_address] += 1\n \n # 判断是否是高频率访问\n if ip_count[ip_address] > 30:\n high_frequency_ips[ip_address] = ip_count[ip_address]\n\n print(ip_count)\n # 输出IP地址及其访问次数到统计文件\n with open(statistics_output_file, 'w') as output:\n json.dump(ip_count, output, ensure_ascii=False, indent=2)\n \n # 输出高频率访问的IP地址到单独的文件\n with open(high_frequency_output_file, 'w') as output:\n json.dump(high_frequency_ips, output, ensure_ascii=False, indent=2)\n\n```", "classification": "Software Engineering"}
{"_id": 186, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nAssume there is a file system that stores both files and directories. \nConsider 'dir' as the only directory in the root directory. 'dir' contains two subdirectories 'subdir1' and 'subdir2'. 'subdir1' contains a file 'file1.ext' and a subdirectory 'subsubdir1'; 'subdir2' contains a subdirectory 'subsubdir2', which contains the file 'file2.ext'.\nIn text format, it is shown as follows (⟶ represents a tab)\ndir\n⟶ subdir1\n⟶ ⟶ file1.ext\n⟶ ⟶ subsubdir1\n⟶ subdir2\n⟶ ⟶ subsubdir2\n⟶ ⟶ ⟶ file2.ext\nIf it is represented in code, the above file system can be written as \"dir\\n\\tsubdir1\\n\\t\\tfile1.ext\\n\\t\\tsubsubdir1\\n\\tsubdir2\\n\\t\\tsubsubdir2\\n\\t\\t\\tfile2.ext\". '\\n' and '\\t' are newline and tab characters respectively.\nEach file and folder in the file system has a unique absolute path, which is the order of directories that must be opened to reach the location of the file/directory, all paths are connected with '/'. In the above example, the absolute path pointing to 'file2.ext' is \"dir/subdir2/subsubdir2/file2.ext\". Each directory name is composed of letters, numbers and/or spaces, and each file name follows the format of 'name.extension', where 'name' and 'extension' are composed of letters, numbers and/or spaces.\nGiven a string 'input' representing the file system in the above format, return the length of the longest absolute path to the file in the file system. If there are no files in the system, return 0.\nFor example:\n Input: input = \"dir\\n\\tsubdir1\\n\\t\\tfile1.ext\\n\\t\\tsubsubdir1\\n\\tsubdir2\\n\\t\\tsubsubdir2\\n\\t\\t\\tfile2.ext\"\n Output: 32\n Explanation: There are two files:\n \"dir/subdir1/file1.ext\", path length 21\n \"dir/subdir2/subsubdir2/file2.ext\", path length 32\n Return 32, because this is the longest path\nHints:\n 1 <= input.length <= 104\n input may contain lowercase or uppercase English letters, a newline character '\\n', a tab character '\\t', a dot '.', a space ' ', and numbers.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass TestlengthLongestPath:\n def test_case1(self):\n assert lengthLongestPath(\"dir\\n\\tsubdir1\\n\\t\\tfile1.ext\\n\\t\\tsubsubdir1\\n\\tsubdir2\\n\\t\\tsubsubdir2\\n\\t\\t\\tfile2.ext\") == 32\n\n", "problem": "Assume there is a file system that stores both files and directories. \nConsider 'dir' as the only directory in the root directory. 'dir' contains two subdirectories 'subdir1' and 'subdir2'. 'subdir1' contains a file 'file1.ext' and a subdirectory 'subsubdir1'; 'subdir2' contains a subdirectory 'subsubdir2', which contains the file 'file2.ext'.\nIn text format, it is shown as follows (⟶ represents a tab)\ndir\n⟶ subdir1\n⟶ ⟶ file1.ext\n⟶ ⟶ subsubdir1\n⟶ subdir2\n⟶ ⟶ subsubdir2\n⟶ ⟶ ⟶ file2.ext\nIf it is represented in code, the above file system can be written as \"dir\\n\\tsubdir1\\n\\t\\tfile1.ext\\n\\t\\tsubsubdir1\\n\\tsubdir2\\n\\t\\tsubsubdir2\\n\\t\\t\\tfile2.ext\". '\\n' and '\\t' are newline and tab characters respectively.\nEach file and folder in the file system has a unique absolute path, which is the order of directories that must be opened to reach the location of the file/directory, all paths are connected with '/'. In the above example, the absolute path pointing to 'file2.ext' is \"dir/subdir2/subsubdir2/file2.ext\". Each directory name is composed of letters, numbers and/or spaces, and each file name follows the format of 'name.extension', where 'name' and 'extension' are composed of letters, numbers and/or spaces.\nGiven a string 'input' representing the file system in the above format, return the length of the longest absolute path to the file in the file system. If there are no files in the system, return 0.\nFor example:\n Input: input = \"dir\\n\\tsubdir1\\n\\t\\tfile1.ext\\n\\t\\tsubsubdir1\\n\\tsubdir2\\n\\t\\tsubsubdir2\\n\\t\\t\\tfile2.ext\"\n Output: 32\n Explanation: There are two files:\n \"dir/subdir1/file1.ext\", path length 21\n \"dir/subdir2/subsubdir2/file2.ext\", path length 32\n Return 32, because this is the longest path\nHints:\n 1 <= input.length <= 104\n input may contain lowercase or uppercase English letters, a newline character '\\n', a tab character '\\t', a dot '.', a space ' ', and numbers.", "testcases": "\n\nclass TestlengthLongestPath:\n def test_case2(self):\n assert lengthLongestPath(\"dir\\n\\tsubdir1\\n\\t\\tfile1.ext\\n\\t\\tsubsubdir1\\n\\tsubdir2\\n\\t\\tsubsubdir2\\n\\t\\t\\tfile2.ext\\n\\t\\t\\tfile3.ext\") == 32\n\n def test_case3(self):\n assert lengthLongestPath(\"dir\\n\\tsubdir1\\n\\t\\tfile1.ext\\n\\t\\tsubsubdir1\\n\\tsubdir2\\n\\t\\tsubsubdir2\\n\\t\\t\\tfile2.ext\\n\\t\\t\\tfile3.ext\\n\\t\\t\\tfile4.ext\") == 32\n\n def test_case4(self):\n assert lengthLongestPath(\"dir\\n\\tsubdir1\\n\\t\\tfile1.ext\\n\\t\\tsubsubdir1\\n\\tsubdir2\\n\\t\\tsubsubdir2\\n\\t\\t\\tfile2.ext\\n\\t\\t\\tfile3.ext\\n\\t\\t\\tfile4.ext\\n\\t\\t\\tfile5.ext\") == 32\n\n def test_case5(self):\n assert lengthLongestPath(\"dir\\n\\tsubdir1\\n\\t\\tfile1.ext\\n\\t\\tsubsubdir1\\n\\tsubdir2\\n\\t\\tsubsubdir2\\n\\t\\t\\tfile2.ext\\n\\t\\t\\tfile3.ext\\n\\t\\t\\tfile4.ext\\n\\t\\t\\tfile5.ext\\n\\t\\t\\tfile6.ext\") == 32\n\n def test_case6(self):\n assert lengthLongestPath(\"dir\\n\\tsubdir1\\n\\t\\tfile1.ext\\n\\t\\tsubsubdir1\\n\\tsubdir2\\n\\t\\tsubsubdir2\\n\\t\\t\\tfile2.ext\\n\\t\\t\\tfile3.ext\\n\\t\\t\\tfile4.ext\\n\\t\\t\\tfile5.ext\\n\\t\\t\\tfile6.ext\\n\\t\\t\\tfile7.ext\") == 32\n\n def test_case7(self):\n assert lengthLongestPath(\"dir\\n\\tsubdir1\\n\\t\\tfile1.ext\\n\\t\\tsubsubdir1\\n\\tsubdir2\\n\\t\\tsubsubdir2\\n\\t\\t\\tfile2.ext\\n\\t\\t\\tfile3.ext\\n\\t\\t\\tfile4.ext\\n\\t\\t\\tfile5.ext\\n\\t\\t\\tfile6.ext\\n\\t\\t\\tfile7.ext\\n\\t\\t\\tfile8.ext\") == 32\n\n def test_case8(self):\n assert lengthLongestPath(\"dir\\n\\tsubdir1\\n\\t\\tfile1.ext\\n\\t\\tsubsubdir1\\n\\tsubdir2\\n\\t\\tsubsubdir2\\n\\t\\t\\tfile2.ext\\n\\t\\t\\tfile3.ext\\n\\t\\t\\tfile4.ext\\n\\t\\t\\tfile5.ext\\n\\t\\t\\tfile6.ext\\n\\t\\t\\tfile7.ext\\n\\t\\t\\tfile8.ext\\n\\t\\t\\tfile9.ext\") == 32\n\n def test_case9(self):\n assert lengthLongestPath(\"dir\\n\\tsubdir1\\n\\t\\tfile1.ext\\n\\t\\tsubsubdir1\\n\\tsubdir2\\n\\t\\tsubsubdir2\\n\\t\\t\\tfile2.ext\\n\\t\\t\\tfile3.ext\\n\\t\\t\\tfile4.ext\\n\\t\\t\\tfile5.ext\\n\\t\\t\\tfile6.ext\\n\\t\\t\\tfile7.ext\\n\\t\\t\\tfile8.ext\\n\\t\\t\\tfile9.ext\\n\\t\\t\\tfile10.ext\") == 33\n\n def test_case10(self):\n assert lengthLongestPath(\"dir\\n\\tsubdir1\\n\\t\\tfile1.ext\\n\\t\\tsubsubdir1\\n\\tsubdir2\\n\\t\\tsubsubdir2\\n\\t\\t\\tfile2.ext\\n\\t\\t\\tfile3.ext\\n\\t\\t\\tfile4.ext\\n\\t\\t\\tfile5.ext\\n\\t\\t\\tfile6.ext\\n\\t\\t\\tfile7.ext\\n\\t\\t\\tfile8.ext\\n\\t\\t\\tfile9.ext\\n\\t\\t\\tfile10.ext\\n\\t\\t\\tfile11.ext\") == 33", "setup_code": "", "reference_solution": "```python\ndef lengthLongestPath(input: str) -> int:\n st = []\n ans, i, n = 0, 0, len(input)\n while i < n:\n # 检测当前文件的深度\n depth = 1\n while i < n and input[i] == '\\t':\n depth += 1\n i += 1\n # 统计当前文件名的长度\n length, isFile = 0, False\n while i < n and input[i] != '\\n':\n if input[i] == '.':\n isFile = True\n length += 1\n i += 1\n i += 1 # 跳过换行符\n while len(st) >= depth:\n st.pop()\n if st:\n length += st[-1] + 1\n if isFile:\n ans = max(ans, length)\n else:\n st.append(length)\n return ans\n\n\n```", "classification": "Algorithm and Data Structure"}
{"_id": 187, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nManually write data to demonstrate the use of the K-means clustering algorithm in the scikit-learn library (sklearn). The random seed is 42. Calculate the output results of each data sample.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testk_means_clustering:\n def test_k_means_clustering_1(self):\n np.random.seed(0)\n data = np.array([[1, 2], [5, 8], [1.5, 1.8], [8, 8], [1, 0.6], [9, 11]])\n num_clusters = 2\n assert np.all(k_means_clustering(data, num_clusters) == np.array([1, 0, 1, 0, 1, 0]))\n\n", "problem": "Manually write data to demonstrate the use of the K-means clustering algorithm in the scikit-learn library (sklearn). The random seed is 42. Calculate the output results of each data sample.", "testcases": "from sklearn.cluster import KMeans\nimport numpy as np\n\n\nclass Testk_means_clustering:\n def test_k_means_clustering_2(self):\n np.random.seed(0)\n data = np.array([[1, 2], [5, 8], [1.5, 1.8], [8, 8], [1, 0.6], [9, 11]])\n num_clusters = 3\n assert np.all(k_means_clustering(data, num_clusters) == np.array([0, 1, 0, 1, 0, 2]))\n\n def test_k_means_clustering_3(self):\n np.random.seed(0)\n data = np.array([[1, 2], [5, 8], [1.5, 1.8], [8, 8], [1, 0.6], [9, 11]])\n num_clusters = 1\n assert np.all(k_means_clustering(data, num_clusters) == np.array([0, 0, 0, 0, 0, 0]))\n\n def test_k_means_clustering_4(self):\n np.random.seed(0)\n data = np.array([[1, 2], [5, 8], [1.5, 1.8], [8, 8], [1, 0.6], [9, 11]])\n num_clusters = 6\n assert np.all(k_means_clustering(data, num_clusters) == np.array([5, 2, 1, 0, 4, 3]))\n\n def test_k_means_clustering_5(self):\n np.random.seed(0)\n data = np.array([[1, 2], [1, 2], [1, 2], [1, 2], [1, 2], [1, 2]])\n num_clusters = 2\n assert np.all(k_means_clustering(data, num_clusters) == np.array([0, 0, 0, 0, 0, 0]))\n\n def test_k_means_clustering_6(self):\n np.random.seed(0)\n data = np.array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]])\n num_clusters = 2\n assert np.all(k_means_clustering(data, num_clusters) == np.array([1, 1, 1, 0, 0, 0]))\n\n def test_k_means_clustering_7(self):\n np.random.seed(0)\n data = np.array([[1, 2], [1, 2], [1, 2], [1, 2], [1, 2], [1, 2]])\n num_clusters = 1\n assert np.all(k_means_clustering(data, num_clusters) == np.array([0, 0, 0, 0, 0, 0]))\n\n def test_k_means_clustering_8(self):\n np.random.seed(0)\n data = np.array([[1, 2], [1, 2], [1, 2], [1, 2], [1, 2], [1, 2]])\n num_clusters = 6\n assert np.all(k_means_clustering(data, num_clusters) == np.array([0, 0, 0, 0, 0, 0]))\n\n def test_k_means_clustering_9(self):\n np.random.seed(0)\n data = np.array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]])\n num_clusters = 1\n assert np.all(k_means_clustering(data, num_clusters) == np.array([0, 0, 0, 0, 0, 0]))\n\n def test_k_means_clustering_10(self):\n np.random.seed(0)\n data = np.array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]])\n num_clusters = 6\n assert np.all(k_means_clustering(data, num_clusters) == np.array([4, 1, 2, 0, 5, 3]))", "setup_code": "", "reference_solution": "```python\nfrom sklearn.cluster import KMeans\nimport numpy as np\n\ndef k_means_clustering(data, num_clusters):\n kmeans = KMeans(n_clusters=num_clusters, random_state=42)\n kmeans.fit(data)\n return kmeans.labels_\n\n```", "classification": "Artificial Intelligence"}
{"_id": 188, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nComplete gamma brightness correction for images using Python.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testgamma_correction:\n def test_gamma_correction_1(self):\n image = cv2.imread('test1/test.jpg', cv2.IMREAD_COLOR)\n gamma = 1.5\n corrected_image = gamma_correction(image, gamma)\n label = cv2.imread('test1/label.png', cv2.IMREAD_COLOR)\n assert (corrected_image == label).all()\n\n", "problem": "Complete gamma brightness correction for images using Python.", "testcases": "import cv2\n\nclass Testgamma_correction:\n def test_gamma_correction_2(self):\n image = cv2.imread('test2/test.jpg', cv2.IMREAD_COLOR)\n gamma = 2.0\n corrected_image = gamma_correction(image, gamma)\n label = cv2.imread('test2/label.png', cv2.IMREAD_COLOR)\n assert (corrected_image == label).all()\n\n def test_gamma_correction_3(self):\n image = cv2.imread('test3/test.jpg', cv2.IMREAD_COLOR)\n gamma = 0.5\n corrected_image = gamma_correction(image, gamma)\n label = cv2.imread('test3/label.png', cv2.IMREAD_COLOR)\n assert (corrected_image == label).all()\n\n def test_gamma_correction_4(self):\n image = cv2.imread('test4/test.jpg', cv2.IMREAD_COLOR)\n gamma = 0.1\n corrected_image = gamma_correction(image, gamma)\n label = cv2.imread('test4/label.png', cv2.IMREAD_COLOR)\n assert (corrected_image == label).all()\n\n def test_gamma_correction_5(self):\n image = cv2.imread('test5/test.jpg', cv2.IMREAD_COLOR)\n gamma = 10.0\n corrected_image = gamma_correction(image, gamma)\n label = cv2.imread('test5/label.png', cv2.IMREAD_COLOR)\n assert (corrected_image == label).all()\n", "setup_code": "", "reference_solution": "```python\nimport cv2\nimport numpy as np\n\ndef gamma_correction(image, gamma):\n # 将图像的亮度值转换为范围在[0, 1]之间的浮点数\n image = image / 255.0\n \n # 对图像进行伽马亮度矫正\n corrected_image = np.power(image, gamma)\n \n # 将亮度值重新缩放到范围[0, 255]\n corrected_image = np.uint8(corrected_image * 255)\n \n return corrected_image\n```", "classification": "Software Engineering"}
{"_id": 189, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nPlease help me write a piece of code to implement the following requirements: There is a target folder called root folder, which contains files of type file folder. Each file folder contains many files of different types. We need to merge these files of different types in each file folder into pdfs and place them together with the files before the merge.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testmerge_pdfs:\n\n def test_merge_pdfs_1(self):\n d = './test1'\n merge_pdfs(d)\n page_text = self.readpdf(os.path.join(d, 'sub', \"merged.pdf\"))\n assert page_text == \"content\"\n\n", "problem": "Please help me write a piece of code to implement the following requirements: There is a target folder called root folder, which contains files of type file folder. Each file folder contains many files of different types. We need to merge these files of different types in each file folder into pdfs and place them together with the files before the merge.", "testcases": "import pytest\n\nimport os\nfrom PyPDF2 import PdfMerger, PdfReader\n\nclass Testmerge_pdfs:\n def test_merge_pdfs_2(self):\n d = './test2'\n merge_pdfs('./test2')\n page_text = self.readpdf(os.path.join(d, 'sub', \"merged.pdf\"))\n assert page_text == \"content1content2content3\"\n\n def test_merge_pdfs_3(self, tmp_path):\n d = './test3'\n merge_pdfs('./test3')\n page_text = self.readpdf(os.path.join(d, 'sub', \"merged.pdf\"))\n assert page_text == \"content1 content11content2content3_1\"\n\n def test_merge_pdfs_4(self, tmp_path):\n d = './test4'\n merge_pdfs('./test4')\n page_text = self.readpdf(os.path.join(d, 'sub', \"merged.pdf\"))\n assert page_text == 'Today is a good day, I want to try something new. How about you?1 + 1 = 3?\\n' \\\n 'No! \\n' \\\n 'Actually #1 + 1 = 3;The weather is so nice today.*/\\n' \\\n 'Yes, let’s travel together!*/\\n' \\\n 'Goody goody!*/'\n\n def test_merge_pdfs_5(self, tmp_path):\n d = './test5'\n merge_pdfs('./test5')\n page_text = self.readpdf(os.path.join(d, 'sub', \"merged.pdf\"))\n assert page_text == ''\n\n def test_merge_pdfs_6(self, tmp_path):\n d = './test6'\n merge_pdfs('./test6')\n assert not os.path.exists(os.path.join(d, 'sub1', \"merged.pdf\"))\n assert not os.path.exists(os.path.join(d, 'sub2', \"merged.pdf\"))\n\n def test_merge_pdfs_7(self, tmp_path):\n d = './test7'\n merge_pdfs('./test7')\n page_text1 = self.readpdf(os.path.join(d, 'sub1', \"merged.pdf\"))\n page_text2 = self.readpdf(os.path.join(d, 'sub2', \"merged.pdf\"))\n assert page_text1 == \"!@#$%^&*()\\n~`'/.,<>\\\\[]#include\\n int main(\"\n assert page_text2 == 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa#include\\n int main('\n\n def test_merge_pdfs_8(self, tmp_path):\n d = './test8'\n merge_pdfs('./test8')\n page_text1 = self.readpdf(os.path.join(d, 'sub1', \"merged.pdf\"))\n page_text11 = self.readpdf(os.path.join(d, 'sub1', 'sub11', \"merged.pdf\"))\n page_text2 = self.readpdf(os.path.join(d, 'sub2', \"merged.pdf\"))\n assert page_text1 == \"!@#$%^&*()\\n~`'/.,<>\\\\[]#include\\n int main(\"\n assert page_text11 == \"!@#$%^&*()\\n~`'/.,<>\\\\[]#include\\n int main(\"\n assert page_text2 == 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa#include\\n int main('\n assert not os.path.exists(os.path.join(d, 'sub1', 'sub12', \"merged.pdf\"))\n assert not os.path.exists(os.path.join(d, 'sub2', 'sub21', \"merged.pdf\"))\n\n def readpdf(self, file_path):\n with open(file_path, 'rb') as pdf_file:\n pdf_reader = PdfReader(pdf_file)\n total_pages = len(pdf_reader.pages)\n page_text = ''\n for page_num in range(total_pages):\n page = pdf_reader.pages[page_num]\n page_text += page.extract_text().strip()\n os.remove(file_path)\n return page_text", "setup_code": "", "reference_solution": "```python\n\nimport os\nfrom PyPDF2 import PdfMerger\n\n# 定义一个函数来合并PDF文件\ndef merge_pdfs(root_dir):\n def merge(files, output):\n merger = PdfMerger()\n for pdf in files:\n merger.append(pdf)\n merger.write(output)\n merger.close()\n\n # 遍历文件夹\n for root, dirs, files in os.walk(root_dir):\n pdf_files = [f for f in files if f.endswith(\".pdf\")]\n if pdf_files: # 如果存在PDF文件\n output = os.path.join(root, \"merged.pdf\") # 输出文件名\n full_pdf_files = [os.path.join(root, f) for f in pdf_files] # 获取完整路径\n full_pdf_files = sorted(full_pdf_files)\n merge(full_pdf_files, output) # 合并PDF文件\n\n\n\n\n\n\n\n```", "classification": "Software Engineering"}
{"_id": 190, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nGiven a the contents of a CSV file as csv_contents, return the difference in days between the date of the earliest and the oldest entry.\n\nThe CSV file starts with a header row, which contains at least one column called Date.\n\nYou are optionally provided with the pandas library if you need it. show me the code regarding to this question.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testcalculate_date_difference:\n def test_calculate_date_difference_1(self):\n csv_contents = \"Date\\n2020-01-01\\n2020-01-02\\n2020-01-03\"\n assert calculate_date_difference(csv_contents) == 2\n\n", "problem": "Given a the contents of a CSV file as csv_contents, return the difference in days between the date of the earliest and the oldest entry.\n\nThe CSV file starts with a header row, which contains at least one column called Date.\n\nYou are optionally provided with the pandas library if you need it. show me the code regarding to this question.", "testcases": "import pytest\n\nimport pandas as pd\nfrom io import StringIO\n\nclass Testcalculate_date_difference:\n def test_calculate_date_difference_2(self):\n csv_contents = \"Date\\n2020-01-01\\n2020-01-01\\n2020-01-01\"\n assert calculate_date_difference(csv_contents) == 0\n\n def test_calculate_date_difference_3(self):\n csv_contents = \"Date\\n2020-01-01\\n2020-12-31\"\n assert calculate_date_difference(csv_contents) == 365\n\n def test_calculate_date_difference_4(self):\n csv_contents = \"Date\\n2020-01-01\\n2021-01-01\"\n assert calculate_date_difference(csv_contents) == 366\n\n def test_calculate_date_difference_5(self):\n csv_contents = \"Date,Value\\n\" \\\n \"2024-01-01,100\\n\" \\\n \"2024-02-15,110\\n\" \\\n \"2024-03-10,120\\n\"\n\n assert calculate_date_difference(csv_contents) == 69\n\n def test_calculate_date_difference_6(self):\n csv_contents = \"Date,date,DATE\\n\" \\\n \"2020-01-01,100,2020-01-01\\n\" \\\n \"2020-02-15,110,2020-01-02\\n\" \\\n \"2020-03-10,120,2020-01-02\\n\"\n assert calculate_date_difference(csv_contents) == 69\n\n def test_calculate_date_difference_7(self):\n csv_contents = \"Date\\n2020-01-01\"\n assert calculate_date_difference(csv_contents) == 0\n\n def test_calculate_date_difference_8(self):\n csv_contents = \"Date\\n2020-01-01\\n2020-01-01\"\n assert calculate_date_difference(csv_contents) == 0\n\n def test_calculate_date_difference_9(self):\n csv_contents = \"Date\\n2020-01-01\\n2021-01-02\\n2022-01-03\\n2023-01-04\\n2024-01-05\\n2025-01-06\"\n assert calculate_date_difference(csv_contents) == 1832\n\n def test_calculate_date_difference_10(self):\n csv_contents = \"Date\\n2020-01-01\\n2022-01-02\\n2022-01-03\\n2023-01-04\\n2023-01-05\\n2021-01-06\\n2021-01-07\"\n assert calculate_date_difference(csv_contents) == 1100", "setup_code": "", "reference_solution": "```python\n\nimport pandas as pd\nfrom io import StringIO\n\ndef calculate_date_difference(csv_contents):\n # Read the CSV contents into a pandas DataFrame\n df = pd.read_csv(StringIO(csv_contents))\n\n # Convert the 'Date' column to datetime\n df['Date'] = pd.to_datetime(df['Date'])\n\n # Calculate the difference in days between the earliest and latest date\n date_difference = (df['Date'].max() - df['Date'].min()).days\n\n return date_difference\n\n\n```", "classification": "Data Science"}
{"_id": 191, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nI currently have a folder named file_path, which contains some files. These files appear in pairs, for example, mix_7560000_content_document.bin and mix_7560000_content_document.idx form a pair. Now, I want to copy the files from this folder into multiple subfolders, each subfolder containing 10 pairs of data. Each new folder will also have a suffix added, which is 'sub' followed by a number.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testcopy_files:\n def test_copy_files_1(self, tmpdir):\n source = tmpdir.mkdir(\"source\")\n dest = tmpdir.mkdir(\"dest\")\n for i in range(20):\n open(os.path.join(source, f\"mix_{i}_content_document.bin\"), 'a').close()\n open(os.path.join(source, f\"mix_{i}_content_document.idx\"), 'a').close()\n copy_files(str(source), str(dest))\n assert len(os.listdir(os.path.join(dest, \"sub0\"))) == 20\n assert len(os.listdir(os.path.join(dest, \"sub1\"))) == 20\n\n", "problem": "I currently have a folder named file_path, which contains some files. These files appear in pairs, for example, mix_7560000_content_document.bin and mix_7560000_content_document.idx form a pair. Now, I want to copy the files from this folder into multiple subfolders, each subfolder containing 10 pairs of data. Each new folder will also have a suffix added, which is 'sub' followed by a number.", "testcases": "import pytest\n\nimport os\nimport shutil\n\nclass Testcopy_files:\n def test_copy_files_2(self, tmpdir):\n source = tmpdir.mkdir(\"source\")\n dest = tmpdir.mkdir(\"dest\")\n for i in range(30):\n open(os.path.join(source, f\"mix_{i}_content_document.bin\"), 'a').close()\n open(os.path.join(source, f\"mix_{i}_content_document.idx\"), 'a').close()\n copy_files(str(source), str(dest))\n assert len(os.listdir(os.path.join(dest, \"sub0\"))) == 20\n assert len(os.listdir(os.path.join(dest, \"sub1\"))) == 20\n assert len(os.listdir(os.path.join(dest, \"sub2\"))) == 20\n\n def test_copy_files_3(self, tmpdir):\n source = tmpdir.mkdir(\"source\")\n dest = tmpdir.mkdir(\"dest\")\n for i in range(10):\n open(os.path.join(source, f\"mix_{i}_content_document.bin\"), 'a').close()\n open(os.path.join(source, f\"mix_{i}_content_document.idx\"), 'a').close()\n copy_files(str(source), str(dest))\n assert len(os.listdir(os.path.join(dest, \"sub0\"))) == 20\n\n def test_copy_files_4(self, tmpdir):\n source = tmpdir.mkdir(\"source\")\n dest = tmpdir.mkdir(\"dest\")\n for i in range(5):\n open(os.path.join(source, f\"mix_{i}_content_document.bin\"), 'a').close()\n open(os.path.join(source, f\"mix_{i}_content_document.idx\"), 'a').close()\n copy_files(str(source), str(dest))\n assert len(os.listdir(os.path.join(dest, \"sub0\"))) == 10\n\n def test_copy_files_5(self, tmpdir):\n source = tmpdir.mkdir(\"source\")\n dest = tmpdir.mkdir(\"dest\")\n for i in range(0):\n open(os.path.join(source, f\"mix_{i}_content_document.bin\"), 'a').close()\n open(os.path.join(source, f\"mix_{i}_content_document.idx\"), 'a').close()\n copy_files(str(source), str(dest))\n assert os.path.exists(os.path.join(dest, \"sub0\")) == False\n\n def test_copy_files_6(self, tmpdir):\n source = tmpdir.mkdir(\"source\")\n dest = tmpdir.mkdir(\"dest\")\n for i in range(41):\n open(os.path.join(source, f\"mix_{i}_content_document.bin\"), 'a').close()\n open(os.path.join(source, f\"mix_{i}_content_document.idx\"), 'a').close()\n copy_files(str(source), str(dest))\n assert len(os.listdir(os.path.join(dest, \"sub0\"))) == 20\n assert len(os.listdir(os.path.join(dest, \"sub1\"))) == 20\n assert len(os.listdir(os.path.join(dest, \"sub2\"))) == 20\n assert len(os.listdir(os.path.join(dest, \"sub4\"))) == 2\n\n def test_copy_files_7(self, tmpdir):\n source = tmpdir.mkdir(\"source\")\n dest = tmpdir.mkdir(\"dest\")\n for i in range(1):\n open(os.path.join(source, f\"mix_{i}_content_document.bin\"), 'a').close()\n open(os.path.join(source, f\"mix_{i}_content_document.idx\"), 'a').close()\n copy_files(str(source), str(dest))\n assert len(os.listdir(os.path.join(dest, \"sub0\"))) == 2\n\n def test_copy_files_8(self, tmpdir):\n source = tmpdir.mkdir(\"source\")\n dest = tmpdir.mkdir(\"dest\")\n for i in range(100):\n open(os.path.join(source, f\"mix_{i}_content_document.bin\"), 'a').close()\n open(os.path.join(source, f\"mix_{i}_content_document.idx\"), 'a').close()\n copy_files(str(source), str(dest))\n assert len(os.listdir(os.path.join(dest, \"sub0\"))) == 20\n assert len(os.listdir(os.path.join(dest, \"sub1\"))) == 20\n assert len(os.listdir(os.path.join(dest, \"sub2\"))) == 20\n assert len(os.listdir(os.path.join(dest, \"sub3\"))) == 20\n assert len(os.listdir(os.path.join(dest, \"sub4\"))) == 20\n assert len(os.listdir(os.path.join(dest, \"sub9\"))) == 20\n assert os.path.exists(os.path.join(dest, \"sub10\")) == False\n\n def test_copy_files_9(self, tmpdir):\n source = tmpdir.mkdir(\"source\")\n dest = tmpdir.mkdir(\"dest\")\n for i in range(11):\n open(os.path.join(source, f\"mix_{i}_content_document.bin\"), 'a').close()\n open(os.path.join(source, f\"mix_{i}_content_document.idx\"), 'a').close()\n copy_files(str(source), str(dest))\n assert len(os.listdir(os.path.join(dest, \"sub0\"))) == 20\n assert len(os.listdir(os.path.join(dest, \"sub1\"))) == 2\n\n def test_copy_files_10(self, tmpdir):\n source = tmpdir.mkdir(\"source\")\n dest = tmpdir.mkdir(\"dest\")\n for i in range(21):\n open(os.path.join(source, f\"mix_{i}_content_document.bin\"), 'a').close()\n open(os.path.join(source, f\"mix_{i}_content_document.idx\"), 'a').close()\n copy_files(str(source), str(dest))\n assert len(os.listdir(os.path.join(dest, \"sub0\"))) == 20\n assert len(os.listdir(os.path.join(dest, \"sub2\"))) == 2", "setup_code": "", "reference_solution": "```python\n\nimport os\nimport shutil\n\ndef copy_files(file_path, dest_path, pairs_per_folder=10):\n files = os.listdir(file_path)\n files.sort()\n pairs = zip(files[::2], files[1::2])\n for i, pair in enumerate(pairs):\n sub_folder = os.path.join(dest_path, 'sub{}'.format(i // pairs_per_folder))\n os.makedirs(sub_folder, exist_ok=True)\n for file in pair:\n shutil.copy(os.path.join(file_path, file), sub_folder)\n\n# 使用方法\n# copy_files('/path/to/source/folder', '/path/to/destination/folder')\n\n\n```", "classification": "Operation System"}
{"_id": 192, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nHow to replace a string containing content like ```html ```, ```css ```, ```python ```, ```javascript ```, ```golang ``` with strings like <pre><code class=\"language-html\">...</code></pre>, <pre><code class=\"language-css\">...</code></pre>, <pre><code class=\"language-python\">...</code></pre>, <pre><code class=\"language-javascript\">...</code></pre>, <pre><code class=\"language-golang\">...</code></pre>. Please use python code.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testreplace_code_block:\n def test_replace_code_block_1(self):\n assert replace_code_block('```html ```') == '<pre><code class=\"language-html\"></code></pre>'\n", "problem": "How to replace a string containing content like ```html ```, ```css ```, ```python ```, ```javascript ```, ```golang ``` with strings like <pre><code class=\"language-html\">...</code></pre>, <pre><code class=\"language-css\">...</code></pre>, <pre><code class=\"language-python\">...</code></pre>, <pre><code class=\"language-javascript\">...</code></pre>, <pre><code class=\"language-golang\">...</code></pre>. Please use python code.", "testcases": "import pytest\n\nimport re\n\nclass Testreplace_code_block:\n def test_replace_code_block_2(self):\n assert replace_code_block('```css 1```') == '<pre><code class=\"language-css\">1</code></pre>'\n def test_replace_code_block_3(self):\n assert replace_code_block('```python```') == '<pre><code class=\"language-python\"></code></pre>'\n def test_replace_code_block_4(self):\n assert replace_code_block('```javascript __main__```') == '<pre><code class=\"language-javascript\">__main__</code></pre>'\n def test_replace_code_block_5(self):\n assert replace_code_block('```golang \\'\\'```') == '<pre><code class=\"language-golang\">\\'\\'</code></pre>'\n def test_replace_code_block_6(self):\n assert replace_code_block('```html css python``` ```javascript ``````golang') == '<pre><code class=\"language-html\">css python</code></pre> <pre><code class=\"language-javascript\"></code></pre>```golang'\n def test_replace_code_block_7(self):\n assert replace_code_block('') == ''\n def test_replace_code_block_8(self):\n assert replace_code_block('```htmlhtml```') == '```htmlhtml```'\n def test_replace_code_block_9(self):\n assert replace_code_block('```html```') == '<pre><code class=\"language-html\"></code></pre>'\n def test_replace_code_block_10(self):\n assert replace_code_block('html pythonpython golanggolang') == 'html pythonpython golanggolang'", "setup_code": "", "reference_solution": "```python\n\nimport re\n\ndef replace_code_block(text):\n # 定义一个字典,将代码块标记映射到相应的HTML类\n languages = {\n \"html\": \"language-html\",\n \"css\": \"language-css\",\n \"python\": \"language-python\",\n \"javascript\": \"language-javascript\",\n \"golang\": \"language-golang\"\n }\n\n # 对于每种语言,使用正则表达式查找和替换相应的代码块\n for lang, html_class in languages.items():\n # 构建正则表达式模式\n pattern = rf\"```{lang}\\b\\s*(.*?)\\s*```\"\n # 替换文本\n replacement = rf'<pre><code class=\"{html_class}\">\\1</code></pre>'\n # 应用替换\n text = re.sub(pattern, replacement, text, flags=re.DOTALL)\n\n return text\n\n\n\n```", "classification": "Front-End"}
{"_id": 193, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \ndo u remeber i asked questions about calculating ET penman montith with excel and u suggest python would be easier?\n\nso im not good with coding environment can you tell me step by step how can calculate ET with python?\n\nor could you plz write me a code ?\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testcalculate_et:\n def test_calculate_et_1(self):\n assert np.isclose(calculate_et(0.5, 100, 20, 0.5, 25, 2, 50, 30), 57.25573474907341, atol=1e-5)\n\n", "problem": "do u remeber i asked questions about calculating ET penman montith with excel and u suggest python would be easier?\n\nso im not good with coding environment can you tell me step by step how can calculate ET with python?\n\nor could you plz write me a code ?", "testcases": "import pytest\nimport numpy as np\n\nclass Testcalculate_et:\n def test_calculate_et_2(self):\n assert np.isclose(calculate_et(0.7, 150, 30, 0.6, 30, 3, 60, 40), 73.850780893989, atol=1e-5)\n\n def test_calculate_et_3(self):\n assert np.isclose(calculate_et(0.6, 120, 25, 0.7, 28, 2.5, 55, 35), 67.49718353071117, atol=1e-5)\n\n def test_calculate_et_4(self):\n assert np.isclose(calculate_et(0.8, 180, 35, 0.8, 32, 3.5, 70, 45), 99.48486561488258, atol=1e-5)\n\n def test_calculate_et_5(self):\n assert np.isclose(calculate_et(0.9, 200, 40, 0.9, 35, 4, 80, 50), 123.78849721706865, atol=1e-5)\n\n def test_calculate_et_6(self):\n assert np.isclose(calculate_et(1, 220, 45, 1, 38, 4.5, 90, 55), 149.34498055254454, atol=1e-5)\n\n def test_calculate_et_7(self):\n assert np.isclose(calculate_et(0, 0, 0, 0, 0, 0, 0, 0), 0, atol=1e-5)\n\n def test_calculate_et_8(self):\n assert np.isclose(calculate_et(1, 1, 1, 1, 1, 1, 1, 1), 0, atol=1e-5)\n\n def test_calculate_et_9(self):\n assert np.isclose(calculate_et(100, 100, 100, 100, 100, 100, 100, 100), 0, atol=1e-5)\n\n def test_calculate_et_10(self):\n assert np.isclose(calculate_et(-1, -1, -1, -1, -1, -1, -1, -1), 0, atol=1e-5)\n\n", "setup_code": "", "reference_solution": "```python\n\ndef calculate_et(delta, rn, g, gamma, t, u2, es, ea):\n numerator = 0.408 * delta * (rn - g) + gamma * (900 / (t + 273)) * u2 * (es - ea)\n denominator = delta + gamma * (1 + 0.34 * u2)\n if denominator == 0:\n return 0\n et = numerator / denominator\n\n print(et)\n return et\n\n\n```", "classification": "Data Science"}
{"_id": 194, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nHow to determine if there are strong or em tags under the p tag text in python etree?\n <p>\n 3131\n <strong>AAAA</strong>\n <strong>BBB</strong>\n <strong>CCC</strong>\n </p>\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testhas_strong_or_em:\n def test_has_strong_or_em_1(self):\n html = \"\"\"\n <p>\n 3131\n <strong>AAAA</strong>\n <strong>BBB</strong>\n <strong>CCC</strong>\n </p>\n \"\"\"\n root = etree.fromstring(html)\n assert has_strong_or_em(root) == True\n\n", "problem": "How to determine if there are strong or em tags under the p tag text in python etree?\n <p>\n 3131\n <strong>AAAA</strong>\n <strong>BBB</strong>\n <strong>CCC</strong>\n </p>", "testcases": "import pytest\n\nfrom lxml import etree\n\nclass Testhas_strong_or_em:\n def test_has_strong_or_em_2(self):\n html = \"\"\"\n <p>\n 3131\n <em>AAAA</em>\n <em>BBB</em>\n <em>CCC</em>\n </p>\n \"\"\"\n root = etree.fromstring(html)\n assert has_strong_or_em(root) == True\n\n def test_has_strong_or_em_3(self):\n html = \"\"\"\n <p>\n 3131\n <strong>AAAA</strong>\n <em>BBB</em>\n <strong>CCC</strong>\n </p>\n \"\"\"\n root = etree.fromstring(html)\n assert has_strong_or_em(root) == True\n\n def test_has_strong_or_em_4(self):\n html = \"\"\"\n <p>\n 3131\n </p>\n \"\"\"\n root = etree.fromstring(html)\n assert has_strong_or_em(root) == False\n\n def test_has_strong_or_em_5(self):\n html = \"\"\"\n <p>\n 3131\n <div>AAAA</div>\n <div>BBB</div>\n <div>CCC</div>\n </p>\n \"\"\"\n root = etree.fromstring(html)\n assert has_strong_or_em(root) == False\n\n def test_has_strong_or_em_6(self):\n html = \"\"\"\n <p>\n 3131\n <strong></strong>\n <em></em>\n </p>\n \"\"\"\n root = etree.fromstring(html)\n assert has_strong_or_em(root) == True\n\n def test_has_strong_or_em_7(self):\n html = \"\"\"\n <p>\n 3131\n <strong>AAAA</strong>\n </p>\n \"\"\"\n root = etree.fromstring(html)\n assert has_strong_or_em(root) == True\n\n def test_has_strong_or_em_8(self):\n html = \"\"\"\n <p>\n 3131\n <em>AAAA</em>\n </p>\n \"\"\"\n root = etree.fromstring(html)\n assert has_strong_or_em(root) == True\n\n def test_has_strong_or_em_9(self):\n html = \"\"\"\n <p>\n 3131\n <strong>AAAA</strong>\n <em>BBB</em>\n </p>\n \"\"\"\n root = etree.fromstring(html)\n assert has_strong_or_em(root) == True\n\n def test_has_strong_or_em_10(self):\n html = \"\"\"\n <p>\n 3131\n <strong>AAAA</strong>\n <strong>BBB</strong>\n <em>CCC</em>\n </p>\n \"\"\"\n root = etree.fromstring(html)\n assert has_strong_or_em(root) == True\n", "setup_code": "", "reference_solution": "```python\n\nfrom lxml import etree\n\nhtml = \"\"\"\n<p>\n 3131\n <strong>AAAA</strong>\n <strong>BBB</strong>\n <strong>CCC</strong>\n</p>\n\"\"\"\n\nroot = etree.fromstring(html)\n\ndef has_strong_or_em(tag):\n if tag.find('strong') is not None or tag.find('em') is not None:\n return True\n return False\n\nfor p in root.iter('p'):\n if has_strong_or_em(p):\n print(\"P tag has strong or em tag\")\n else:\n print(\"P tag does not have strong or em tag\")\n\n\n```", "classification": "Front-End"}
{"_id": 195, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nHow to flatten the dictionary format in rows of pandas table, with each key-value pair occupying one row? This dictionary might be nested, connect keys at different levels through \".\"\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testflatten_dict_to_rows:\n def test_flatten_dict_to_rows_1(self):\n dt = {'A': ['foo', 'bar'], 'B': [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}]}\n result = flatten_dict_to_rows(dt)\n expected = pd.DataFrame({'Key': {0: 'A', 1: 'B'}, 'Value': {0: ['foo', 'bar'], 1: [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}]}})\n pd.testing.assert_frame_equal(result, expected)\n\n", "problem": "How to flatten the dictionary format in rows of pandas table, with each key-value pair occupying one row? This dictionary might be nested, connect keys at different levels through \".\"", "testcases": "import pytest\n\nimport pandas as pd\n\nclass Testflatten_dict_to_rows:\n def test_flatten_dict_to_rows_2(self):\n dt = {'A': ['foo', 'bar', 'baz'], 'B': {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}}\n result = flatten_dict_to_rows(dt)\n expected = pd.DataFrame({'Key': {0: 'A', 1: 'B.a', 2: 'B.b', 3: 'B.c', 4: 'B.d', 5: 'B.e', 6: 'B.f'}, 'Value': {0: ['foo', 'bar', 'baz'], 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6}})\n pd.testing.assert_frame_equal(result, expected)\n\n def test_flatten_dict_to_rows_3(self):\n dt = {'A': ['foo'], 'B': {'a': 1, 'b': [2, 3]}}\n result = flatten_dict_to_rows(dt)\n expected = pd.DataFrame({'Key': {0: 'A', 1: 'B.a', 2: 'B.b'}, 'Value': {0: ['foo'], 1: 1, 2: [2, 3]}})\n pd.testing.assert_frame_equal(result, expected)\n\n def test_flatten_dict_to_rows_4(self):\n dt = {'A': {'A.1': 2, 'A.2': {'A.3': 'A.3.1'}}, 'B': {'a': 1}, 'C': {'b': 2}}\n result = flatten_dict_to_rows(dt)\n expected = pd.DataFrame({'Key': {0: 'A.A.1', 1: 'A.A.2.A.3', 2: 'B.a', 3: 'C.b'}, 'Value': {0: 2, 1: 'A.3.1', 2: 1, 3: 2}})\n pd.testing.assert_frame_equal(result, expected)\n\n def test_flatten_dict_to_rows_5(self):\n dt = {'A': ['foo', 'bar'], 'B': {'a': [1, {'a': 3, 'b': 4}]}}\n result = flatten_dict_to_rows(dt)\n expected = pd.DataFrame({'Key': {0: 'A', 1: 'B.a'}, 'Value': {0: ['foo', 'bar'], 1: [1, {'a': 3, 'b': 4}]}})\n pd.testing.assert_frame_equal(result, expected)\n\n def test_flatten_dict_to_rows_6(self):\n dt = {'A': ['foo', 'bar'], 'B': {\"C\": [{'a': 1, 'b': 2}, {'c': 3, 'd': 4, 'e': 5}]}}\n result = flatten_dict_to_rows(dt)\n expected = pd.DataFrame({'Key': {0: 'A', 1: 'B.C'}, 'Value': {0: ['foo', 'bar'], 1: [{'a': 1, 'b': 2}, {'c': 3, 'd': 4, 'e': 5}]}})\n pd.testing.assert_frame_equal(result, expected)\n\n def test_flatten_dict_to_rows_7(self):\n dt = {'A': [], 'B': []}\n result = flatten_dict_to_rows(dt)\n expected = pd.DataFrame({'Key': {0: 'A', 1: 'B'}, 'Value': {0: [], 1: []}})\n pd.testing.assert_frame_equal(result, expected)\n\n def test_flatten_dict_to_rows_8(self):\n dt = {'A': ['foo'], 'B': [{}]}\n result = flatten_dict_to_rows(dt)\n expected = pd.DataFrame({'Key': {0: 'A', 1: 'B'}, 'Value': {0: ['foo'], 1: [{}]}})\n pd.testing.assert_frame_equal(result, expected)\n\n def test_flatten_dict_to_rows_9(self):\n dt = {'A': ['foo'], 'C': {}}\n result = flatten_dict_to_rows(dt)\n expected = pd.DataFrame({'Key': {0: 'A', 1: 'C'}, 'Value': {0: ['foo'], 1: {}}})\n pd.testing.assert_frame_equal(result, expected)\n\n def test_flatten_dict_to_rows_10(self):\n dt = {}\n result = flatten_dict_to_rows(dt)\n expected = pd.DataFrame({'Key': {}, 'Value': {}})\n pd.testing.assert_frame_equal(result, expected, check_dtype=False, check_index_type=False)", "setup_code": "", "reference_solution": "```python\n\nimport pandas as pd\n\ndef flatten_dict_to_rows(d):\n def flatten_dict(d, parent_key='', sep='.'):\n items = []\n for k, v in d.items():\n new_key = f\"{parent_key}{sep}{k}\" if parent_key else k\n if isinstance(v, dict):\n if not v:\n items.append((new_key, {}))\n else:\n items.extend(flatten_dict(v, new_key, sep=sep).items())\n else:\n items.append((new_key, v))\n return dict(items)\n\n flat_dict = flatten_dict(d)\n\n # Convert the flattened dictionary to a pandas DataFrame\n df = pd.DataFrame(list(flat_dict.items()), columns=['Key', 'Value'])\n print(df.to_dict())\n return df\n\n\n```", "classification": "Data Science"}
{"_id": 196, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \n21. Given a MAC address, determine whether this MAC address is within a given MAC address range. If it is, output TRUE, otherwise output FALSE. For example:\nInput 1: B4:AD:A3:31:£2:44, B4:AB:A3:31:£2:44-84:AE:A3:31:E2:44 Output: TRUE\nInput 2: B4:AD:A3:31:£2:44, B4:AD:A3:31:£2:46-B4:AD:A3:31:E2:4A Output: FALSE\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testis_mac_in_range:\n\n def test_is_mac_in_range_1(self):\n assert is_mac_in_range('B4:AD:A3:31:E2:44', 'B4:AB:A3:31:E2:44-84:AE:A3:31:E2:44') == False\n\n", "problem": "21. Given a MAC address, determine whether this MAC address is within a given MAC address range. If it is, output TRUE, otherwise output FALSE. For example:\nInput 1: B4:AD:A3:31:£2:44, B4:AB:A3:31:£2:44-84:AE:A3:31:E2:44 Output: TRUE\nInput 2: B4:AD:A3:31:£2:44, B4:AD:A3:31:£2:46-B4:AD:A3:31:E2:4A Output: FALSE", "testcases": "\n\nclass Testis_mac_in_range:\n def test_is_mac_in_range_2(self):\n assert is_mac_in_range('B4:AD:A3:31:E2:44', 'B4:AD:A3:31:E2:46-B4:AD:A3:31:E2:4A') == False\n\n def test_is_mac_in_range_3(self):\n assert is_mac_in_range('00:00:00:00:00:00', '00:00:00:00:00:00-FF:FF:FF:FF:FF:FF') == True\n\n def test_is_mac_in_range_4(self):\n assert is_mac_in_range('FF:FF:FF:FF:FF:FF', '00:00:00:00:00:00-FF:FF:FF:FF:FF:FF') == True\n\n def test_is_mac_in_range_5(self):\n assert is_mac_in_range('00:00:00:00:00:01', '00:00:00:00:00:00-00:00:00:00:00:02') == True\n\n def test_is_mac_in_range_6(self):\n assert is_mac_in_range('00:00:00:00:00:03', '00:00:00:00:00:00-00:00:00:00:00:02') == False\n\n def test_is_mac_in_range_7(self):\n assert is_mac_in_range('00:00:00:00:00:00', '00:00:00:00:00:01-00:00:00:00:00:02') == False\n\n def test_is_mac_in_range_8(self):\n assert is_mac_in_range('00:00:00:00:00:02', '00:00:00:00:00:01-00:00:00:00:00:02') == True\n\n def test_is_mac_in_range_9(self):\n assert is_mac_in_range('00:00:00:00:00:00', '00:00:00:00:00:00-00:00:00:00:00:00') == True\n\n def test_is_mac_in_range_10(self):\n assert is_mac_in_range('FF:FF:FF:FF:FF:FF', '00:00:00:00:00:00-00:00:00:00:00:00') == False", "setup_code": "", "reference_solution": "```python\n\ndef is_mac_in_range(mac, mac_range):\n def mac_to_hex(mac_str):\n return mac_str.replace(':', '').replace('-', '').upper()\n\n # 解析MAC地址范围\n start_mac_str, end_mac_str = mac_range.split('-')\n start_mac = int(mac_to_hex(start_mac_str), 16)\n end_mac = int(mac_to_hex(end_mac_str), 16)\n mac_val = int(mac_to_hex(mac), 16)\n\n # 判断MAC地址是否在范围内\n return start_mac <= mac_val <= end_mac\n\n\n```", "classification": "Software Engineering"}
{"_id": 197, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nWrite a python code that directly estimates a 18650 lithium-ion battery capacity in Amp hour from a fractional order model with 2 constant phase elements and 3 resistors.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testfractional_order_model:\n def test_fractional_order_model_1(self):\n time_data = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])\n current_data = np.array([0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0])\n popt, pcov = curve_fit(fractional_order_model, time_data, current_data, bounds=(0, [1.0, 1.0, 1.0, 1.0, 1.0, 1.0]))\n assert round(popt[0], 2) == 0\n\n", "problem": "Write a python code that directly estimates a 18650 lithium-ion battery capacity in Amp hour from a fractional order model with 2 constant phase elements and 3 resistors.", "testcases": "import pytest\n\nimport numpy as np\nfrom scipy.optimize import curve_fit\n\nclass Testfractional_order_model:\n def test_fractional_order_model_2(self):\n time_data = np.array([0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20])\n current_data = np.array([0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0])\n popt, pcov = curve_fit(fractional_order_model, time_data, current_data, bounds=(0, [2.0, 2.0, 2.0, 2.0, 2.0, 2.0]))\n assert round(popt[0], 2) == 1.21\n\n def test_fractional_order_model_3(self):\n time_data = np.array([0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30])\n current_data = np.array([0, 0.3, 0.6, 0.9, 1.2, 1.5, 1.8, 2.1, 2.4, 2.7, 3.0])\n popt, pcov = curve_fit(fractional_order_model, time_data, current_data, bounds=(0, [3.0, 3.0, 3.0, 3.0, 3.0, 3.0]))\n assert round(popt[0], 2) == 1.95\n\n def test_fractional_order_model_4(self):\n time_data = np.array([0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40])\n current_data = np.array([0, 0.4, 0.8, 1.2, 1.6, 2.0, 2.4, 2.8, 3.2, 3.6, 4.0])\n popt, pcov = curve_fit(fractional_order_model, time_data, current_data, bounds=(0, [4.0, 4.0, 4.0, 4.0, 4.0, 4.0]))\n assert round(popt[0], 2) == 2.64\n\n def test_fractional_order_model_5(self):\n time_data = np.array([0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50])\n current_data = np.array([0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0])\n popt, pcov = curve_fit(fractional_order_model, time_data, current_data, bounds=(0, [5.0, 5.0, 5.0, 5.0, 5.0, 5.0]))\n assert round(popt[0], 2) == 3.33\n\n def test_fractional_order_model_6(self):\n time_data = np.array([0, 6, 12, 18, 24, 30, 36, 42, 48, 54, 60])\n current_data = np.array([0, 0.6, 1.2, 1.8, 2.4, 3.0, 3.6, 4.2, 4.8, 5.4, 6.0])\n popt, pcov = curve_fit(fractional_order_model, time_data, current_data, bounds=(0, [6.0, 6.0, 6.0, 6.0, 6.0, 6.0]))\n assert round(popt[0], 2) == 4.0\n\n def test_fractional_order_model_7(self):\n time_data = np.array([0, 7, 14, 21, 28, 35, 42, 49, 56, 63, 70])\n current_data = np.array([0, 0.7, 1.4, 2.1, 2.8, 3.5, 4.2, 4.9, 5.6, 6.3, 7.0])\n popt, pcov = curve_fit(fractional_order_model, time_data, current_data, bounds=(0, [7.0, 7.0, 7.0, 7.0, 7.0, 7.0]))\n assert round(popt[0], 2) == 4.67\n\n def test_fractional_order_model_8(self):\n time_data = np.array([0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80])\n current_data = np.array([0, 0.8, 1.6, 2.4, 3.2, 4.0, 4.8, 5.6, 6.4, 7.2, 8.0])\n popt, pcov = curve_fit(fractional_order_model, time_data, current_data, bounds=(0, [8.0, 8.0, 8.0, 8.0, 8.0, 8.0]))\n assert round(popt[0], 2) == 5.34\n\n def test_fractional_order_model_9(self):\n time_data = np.array([0, 9, 18, 27, 36, 45, 54, 63, 72, 81, 90])\n current_data = np.array([0, 0.9, 1.8, 2.7, 3.6, 4.5, 5.4, 6.3, 7.2, 8.1, 9.0])\n popt, pcov = curve_fit(fractional_order_model, time_data, current_data, bounds=(0, [9.0, 9.0, 9.0, 9.0, 9.0, 9.0]))\n assert round(popt[0], 2) == 6.01\n\n def test_fractional_order_model_10(self):\n time_data = np.array([0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100])\n current_data = np.array([0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0])\n popt, pcov = curve_fit(fractional_order_model, time_data, current_data, bounds=(0, [10.0, 10.0, 10.0, 10.0, 10.0, 10.0]))\n assert round(popt[0], 2) == 6.68\n", "setup_code": "", "reference_solution": "```python\n\nimport numpy as np\nfrom scipy.optimize import curve_fit\n\n# Define the fractional order model with 2 constant phase elements and 3 resistors\ndef fractional_order_model(t, Q, R1, R2, R3, n1, n2):\n return Q * (1 - (1 / (R1 * (t ** n1) + 1)) - (1 / (R2 * (t ** n2) + 1)) - (1 / R3))\n\n# # Sample time and current data\n# time_data = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])\n# current_data = np.array([0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0])\n#\n# # Fit the model to the data\n# popt, pcov = curve_fit(fractional_order_model, time_data, current_data, bounds=(0, [1.0, 1.0, 1.0, 1.0, 1.0, 1.0]))\n# print(len(popt))\n# # The estimated battery capacity in Amp hour is the first parameter of the model\n# estimated_capacity_Ah = popt[0]\n#\n# print(\"Estimated battery capacity: {:.2f} Ah\".format(estimated_capacity_Ah))\n\n\n```", "classification": "Software Engineering"}
{"_id": 198, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nPython solution: Suppose the quadratic function p(x)=ax^2+bx+c passes through the points (x_i,y_i) for i=1, 2, 3. Find the values of a, b, and c.\nFor example, if it passes through these three points (-1,1), (0,-1), (2,7), a system of linear equations can be obtained. The solve function in numpy.linalg can be used to solve the equation.\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testsolve_quadratic:\n def test_solve_quadratic_1(self):\n points = [(0,0),(1,1),(2,4)]\n assert np.allclose(solve_quadratic(points), [1, 0, 0])\n\n", "problem": "Python solution: Suppose the quadratic function p(x)=ax^2+bx+c passes through the points (x_i,y_i) for i=1, 2, 3. Find the values of a, b, and c.\nFor example, if it passes through these three points (-1,1), (0,-1), (2,7), a system of linear equations can be obtained. The solve function in numpy.linalg can be used to solve the equation.", "testcases": "import pytest\n\nimport numpy as np\n\nclass Testsolve_quadratic:\n def test_solve_quadratic_2(self):\n points = [(1,1),(2,4),(3,9)]\n assert np.allclose(solve_quadratic(points), [1, 0, 0])\n\n def test_solve_quadratic_3(self):\n points = [(-1,1),(0,-1),(2,7)]\n assert np.allclose(solve_quadratic(points), [2, 0, -1])\n\n def test_solve_quadratic_4(self):\n points = [(0,0),(1,3),(2,12)]\n assert np.allclose(solve_quadratic(points), [3, 0, 0])\n\n def test_solve_quadratic_5(self):\n points = [(1,6),(2,11),(3,18)]\n assert np.allclose(solve_quadratic(points), [1, 2, 3])\n\n def test_solve_quadratic_6(self):\n points = [(2,14),(3,21),(4,30)]\n assert np.allclose(solve_quadratic(points), [1, 2, 6])\n\n def test_solve_quadratic_7(self):\n points = [(0,0),(1,0),(2,0)]\n assert np.allclose(solve_quadratic(points), [0, 0, 0])\n\n def test_solve_quadratic_8(self):\n points = [(1,1),(2,1),(3,1)]\n assert np.allclose(solve_quadratic(points), [0, 0, 1])\n\n def test_solve_quadratic_9(self):\n points = [(0,0),(0,0),(0,0)]\n with pytest.raises(np.linalg.LinAlgError):\n solve_quadratic(points)\n\n def test_solve_quadratic_10(self):\n points = [(1,1),(1,1),(1,1)]\n with pytest.raises(np.linalg.LinAlgError):\n solve_quadratic(points)", "setup_code": "", "reference_solution": "```python\n\nimport numpy as np\n\ndef solve_quadratic(points):\n # Create matrix A using a list comprehension\n A = np.array([[x**2, x, 1] for x, y in points])\n # Create vector b\n b = np.array([y for x, y in points])\n # Use numpy.linalg.solve to solve for [a, b, c]\n coefficients = np.linalg.solve(A, b)\n\n return coefficients\n\n```", "classification": "Algorithm and Data Structure"}
{"_id": 199, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nwrite a funciton that get 4 strings indication 2 ip ranges and tell me if these ip ranges overlap or not\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testcheck_ip_overlap:\n def test_check_ip_overlap_1(self):\n assert check_ip_overlap('192.168.1.0/24', '192.168.2.0/24') == False\n\n", "problem": "write a funciton that get 4 strings indication 2 ip ranges and tell me if these ip ranges overlap or not", "testcases": "import pytest\n\nimport ipaddress\n\nclass Testcheck_ip_overlap:\n def test_check_ip_overlap_2(self):\n assert check_ip_overlap('192.168.1.0/24', '192.168.1.0/24') == True\n\n def test_check_ip_overlap_3(self):\n assert check_ip_overlap('10.0.0.0/8', '10.0.0.0/16') == True\n\n def test_check_ip_overlap_4(self):\n assert check_ip_overlap('172.16.0.0/12', '192.168.0.0/16') == False\n\n def test_check_ip_overlap_5(self):\n assert check_ip_overlap('172.16.0.0/12', '172.16.0.0/16') == True\n\n def test_check_ip_overlap_6(self):\n assert check_ip_overlap('10.0.0.0/8', '172.16.0.0/12') == False\n\n def test_check_ip_overlap_7(self):\n assert check_ip_overlap('0.0.0.0/0', '192.168.1.0/24') == True\n\n def test_check_ip_overlap_8(self):\n assert check_ip_overlap('0.0.0.0/0', '0.0.0.0/0') == True\n\n def test_check_ip_overlap_9(self):\n assert check_ip_overlap('255.255.255.255/32', '255.255.255.255/32') == True\n\n def test_check_ip_overlap_10(self):\n assert check_ip_overlap('255.255.255.255/32', '0.0.0.0/0') == True", "setup_code": "", "reference_solution": "```python\n\nimport ipaddress\n\ndef check_ip_overlap(ip_range1, ip_range2):\n ip_net1 = ipaddress.ip_network(ip_range1)\n ip_net2 = ipaddress.ip_network(ip_range2)\n\n return ip_net1.overlaps(ip_net2)\n\n\n\n```", "classification": "Algorithm and Data Structure"}
{"_id": 200, "prompt": "Your task is to generate python code to solve the following problem. The generated code must be placed between the ```python and ```, and only one code block is allowed: \nI want to write a python program that rename the files of a folder . \nplease remove all letters and keep the numbers\n\nYou need to follow the function names or class names in the test cases. The generated code should not contain any test cases: \nclass Testrename_files_in_folder:\n def test_rename_files_in_folder_1(self, tmpdir):\n p = tmpdir.mkdir(\"sub\").join(\"file123abc.txt\")\n p.write(\"content\")\n rename_files_in_folder(str(tmpdir) + '/sub/')\n assert os.path.isfile(str(tmpdir) + '/sub/123.txt')\n\n", "problem": "I want to write a python program that rename the files of a folder . \nplease remove all letters and keep the numbers", "testcases": "import pytest\n\nimport os\nimport re\n\nclass Testrename_files_in_folder:\n def test_rename_files_in_folder_2(self, tmpdir):\n p = tmpdir.mkdir(\"sub\").join(\"file456def.txt\")\n p.write(\"content\")\n rename_files_in_folder(str(tmpdir) + '/sub/')\n assert os.path.isfile(str(tmpdir) + '/sub/456.txt')\n\n def test_rename_files_in_folder_3(self, tmpdir):\n p = tmpdir.mkdir(\"sub\").join(\"file789ghi.txt\")\n p.write(\"content\")\n rename_files_in_folder(str(tmpdir) + '/sub/')\n assert os.path.isfile(str(tmpdir) + '/sub/789.txt')\n\n def test_rename_files_in_folder_4(self, tmpdir):\n p = tmpdir.mkdir(\"sub\").join(\"file101112jkl.txt\")\n p.write(\"content\")\n rename_files_in_folder(str(tmpdir) + '/sub/')\n assert os.path.isfile(str(tmpdir) + '/sub/101112.txt')\n\n def test_rename_files_in_folder_5(self, tmpdir):\n p = tmpdir.mkdir(\"sub\").join(\"file131415mno.txt\")\n p.write(\"content\")\n rename_files_in_folder(str(tmpdir) + '/sub/')\n assert os.path.isfile(str(tmpdir) + '/sub/131415.txt')\n\n def test_rename_files_in_folder_6(self, tmpdir):\n p = tmpdir.mkdir(\"sub\").join(\"file161718pqr.txt\")\n p.write(\"content\")\n rename_files_in_folder(str(tmpdir) + '/sub/')\n assert os.path.isfile(str(tmpdir) + '/sub/161718.txt')\n\n def test_rename_files_in_folder_7(self, tmpdir):\n p = tmpdir.mkdir(\"sub\").join(\"file.txt\")\n p.write(\"content\")\n rename_files_in_folder(str(tmpdir) + '/sub/')\n assert os.path.isfile(str(tmpdir) + '/sub/.txt')\n\n def test_rename_files_in_folder_8(self, tmpdir):\n p = tmpdir.mkdir(\"sub\").join(\"file123.txt\")\n p.write(\"content\")\n rename_files_in_folder(str(tmpdir) + '/sub/')\n assert os.path.isfile(str(tmpdir) + '/sub/123.txt')\n\n def test_rename_files_in_folder_9(self, tmpdir):\n p = tmpdir.mkdir(\"sub\").join(\"file_1.txt\")\n p.write(\"content\")\n rename_files_in_folder(str(tmpdir) + '/sub/')\n assert os.path.isfile(str(tmpdir) + '/sub/_1.txt')\n\n def test_rename_files_in_folder_10(self, tmpdir):\n p = tmpdir.mkdir(\"sub\").join(\"file1234567890.abc-1.txt\")\n p.write(\"content\")\n rename_files_in_folder(str(tmpdir) + '/sub/')\n assert os.path.isfile(str(tmpdir) + '/sub/1234567890.-1.txt')", "setup_code": "", "reference_solution": "```python\n\nimport os\nimport re\n\ndef rename_files_in_folder(folder_path):\n for filename in os.listdir(folder_path):\n file_type = filename.split('.')[-1]\n new_filename = re.sub(\"[A-Za-z]\", \"\", filename[:-len(file_type)]) + file_type\n os.rename(os.path.join(folder_path, filename), os.path.join(folder_path, new_filename))\n\n# Call the function with the path to the folder\n# rename_files_in_folder('/path/to/your/folder')\n\n\n```", "classification": "Operation System"}