import java.util.ArrayList;
public class ShoppingCart {
    private int selectedItemIndex = -1;
    public void selectItem(int index) {
        this.selectedItemIndex = index;
    }
    public int getSelectedItemIndex() {
        return selectedItemIndex;
    }
    public static void main(String[] args) {
        checkFunctionality();
    }
    public static void checkFunctionality() {
        ShoppingCart cart = new ShoppingCart();
        assert cart.getSelectedItemIndex() == -1 : "没有商品被选择时，应该返回-1。";
        cart.selectItem(2);
        assert cart.getSelectedItemIndex() == 2 : "选择了索引为2的商品，应该返回2。";
        cart.selectItem(5);
        assert cart.getSelectedItemIndex() == 5 : "更改选择到索引为5的商品，应该返回5。";
        System.out.println("所有测试通过！");
    }
}

Please write a Java method to handle the selection status of items in a shopping cart. When a user selects an item, the position (index) of the item will be recorded. If the user has not selected any items, the index value will be -1. You need to implement a method that returns the index of the currently selected item. If no item is selected, return -1.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.ArrayList;
public class ShoppingCart {
    private int selectedItemIndex = -1;
    public void selectItem(int index) {
    }
    public int getSelectedItemIndex() {
    }
}
```

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class ShoppingCartTest {
    @Test
    public void testInitialSelectedItemIndex() {
        ShoppingCart cart = new ShoppingCart();
        assertEquals(-1, cart.getSelectedItemIndex());
    }
    @Test
    public void testSelectItem() {
        ShoppingCart cart = new ShoppingCart();
        cart.selectItem(2);
        assertEquals(2, cart.getSelectedItemIndex());
    }
    @Test
    public void testChangeSelectedItem() {
        ShoppingCart cart = new ShoppingCart();
        cart.selectItem(2);
        cart.selectItem(5);
        assertEquals(5, cart.getSelectedItemIndex());
    }
    @Test
    public void testSelectItemNegativeIndex() {
        ShoppingCart cart = new ShoppingCart();
        cart.selectItem(-3);
        assertEquals(-3, cart.getSelectedItemIndex());
    }
    @Test
    public void testSelectItemZeroIndex() {
        ShoppingCart cart = new ShoppingCart();
        cart.selectItem(0);
        assertEquals(0, cart.getSelectedItemIndex());
    }
}


import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class LineCounter {
    public static int countLines(String filePath) throws IOException {
        int lines = 0;
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            while (reader.readLine() != null) {
                lines++;
            }
        }
        return lines;
    }
    public static void main(String[] args) {
        File tempFile = null;
        try {
            tempFile = File.createTempFile("testFile", ".txt");
            try (FileWriter writer = new FileWriter(tempFile)) {
                writer.write("第一行文本\n第二行文本\n第三行文本");
            }
            int lineCount = countLines(tempFile.getAbsolutePath());
            System.out.println("文件中的行数为: " + lineCount);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (tempFile != null) {
                tempFile.delete();
            }
        }
    }
}

Please write a Java program to demonstrate how to use `BufferedReader` to read the contents of a text file line by line. Ensure that your program can handle exceptions and properly close resources after reading the file. Furthermore, your program should be able to count and print the number of lines contained in the file.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class LineCounter {
    public static int countLines(String filePath) throws IOException {
    }
}
```

Question: Write a piece of python code to achieve the following function.
Find the maximum perfect square number that is less than the nth Fibonacci number.
The function's name is max_square_number, and the input is an integer n.

Answer:
```python
def max_square_number(n):
 if n <= 2:
 return 0 # For the first two numbers in the Fibonacci sequence, no complete square numbers can be used.

 fibs = [0, 1] # Store the first two numbers of the Fibonacci sequence
 squares = [] # Store the list of perfect square numbers

 max_square = 0
 i = 2

 while i <= n:
 fibs.append(fibs[i-1] + fibs[i-2]) # Calculate the next Fibonacci number
 i += 1

 fib = fibs[-1]
 perfect_squares = [i**2 for i in range(1, int(math.sqrt(fib)) + 1)]
 max_square = max(filter(lambda x: x < fib, perfect_squares))
 return max_square
```

----------------

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import org.junit.Test;
import static org.junit.Assert.*;
public class LineCounterTest {
    @Test
    public void testCountLinesWithThreeLines() throws IOException {
        File tempFile = null;
        try {
            tempFile = File.createTempFile("testFile", ".txt");
            try (FileWriter writer = new FileWriter(tempFile)) {
                writer.write("第一行文本\n第二行文本\n第三行文本");
            }
            int lineCount = LineCounter.countLines(tempFile.getAbsolutePath());
            assertEquals(3, lineCount);
        } finally {
            if (tempFile != null) {
                tempFile.delete();
            }
        }
    }
    @Test
    public void testCountLinesWithEmptyFile() throws IOException {
        File tempFile = null;
        try {
            tempFile = File.createTempFile("testFile", ".txt");
            int lineCount = LineCounter.countLines(tempFile.getAbsolutePath());
            assertEquals(0, lineCount);
        } finally {
            if (tempFile != null) {
                tempFile.delete();
            }
        }
    }
    @Test
    public void testCountLinesWithOneLine() throws IOException {
        File tempFile = null;
        try {
            tempFile = File.createTempFile("testFile", ".txt");
            try (FileWriter writer = new FileWriter(tempFile)) {
                writer.write("只有一行文本");
            }
            int lineCount = LineCounter.countLines(tempFile.getAbsolutePath());
            assertEquals(1, lineCount);
        } finally {
            if (tempFile != null) {
                tempFile.delete();
            }
        }
    }
    @Test(expected = IOException.class)
    public void testCountLinesWithNonexistentFile() throws IOException {
        LineCounter.countLines("nonexistentFile.txt");
    }
    @Test
    public void testCountLinesWithMultipleNewLines() throws IOException {
        File tempFile = null;
        try {
            tempFile = File.createTempFile("testFile", ".txt");
            try (FileWriter writer = new FileWriter(tempFile)) {
                writer.write("\n\n\n");
            }
            int lineCount = LineCounter.countLines(tempFile.getAbsolutePath());
            assertEquals(3, lineCount);
        } finally {
            if (tempFile != null) {
                tempFile.delete();
            }
        }
    }
}


import java.lang.IllegalArgumentException;
public class PermissionNotifier {
    public void notifyPermissionChange(int permissionCode, String appName) throws IllegalArgumentException {
        if (permissionCode < 0 || appName == null || appName.isEmpty()) {
            throw new IllegalArgumentException("非法的权限代码或应用名称");
        }
    }
    public static void main(String[] args) {
        PermissionNotifier notifier = new PermissionNotifier();
        try {
            notifier.notifyPermissionChange(100, "SampleApp");
            System.out.println("权限变更通知成功。");
        } catch (IllegalArgumentException e) {
            System.out.println("捕获到非法参数异常：" + e.getMessage());
        }
        try {
            notifier.notifyPermissionChange(-1, "InvalidApp");
        } catch (IllegalArgumentException e) {
            System.out.println("捕获到非法参数异常：" + e.getMessage());
        }
    }
}

Please write a Java method that simulates a simplified permission change notification system. When an application's operational permissions change, the corresponding listeners need to be notified. Specifically, you need to implement a class named `PermissionNotifier` that includes a method called `notifyPermissionChange`. This method takes two parameters: an integer `permissionCode` representing the permission code, and a string `appName` representing the application name. If the permission code or application name is invalid, the method should throw an `IllegalArgumentException`.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.lang.IllegalArgumentException;
public class PermissionNotifier {
    public void notifyPermissionChange(int permissionCode, String appName) throws IllegalArgumentException {
    }
}
```

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import java.lang.IllegalArgumentException;
public class PermissionNotifierTest {
    @Test
    public void testNotifyPermissionChange_ValidInputs() {
        PermissionNotifier notifier = new PermissionNotifier();
        assertDoesNotThrow(() -> notifier.notifyPermissionChange(100, "ValidApp"));
    }
    @Test
    public void testNotifyPermissionChange_InvalidPermissionCode() {
        PermissionNotifier notifier = new PermissionNotifier();
        assertThrows(IllegalArgumentException.class, () -> notifier.notifyPermissionChange(-1, "App"));
    }
    @Test
    public void testNotifyPermissionChange_NullAppName() {
        PermissionNotifier notifier = new PermissionNotifier();
        assertThrows(IllegalArgumentException.class, () -> notifier.notifyPermissionChange(100, null));
    }
    @Test
    public void testNotifyPermissionChange_EmptyAppName() {
        PermissionNotifier notifier = new PermissionNotifier();
        assertThrows(IllegalArgumentException.class, () -> notifier.notifyPermissionChange(100, ""));
    }
    @Test
    public void testNotifyPermissionChange_ZeroPermissionCode() {
        PermissionNotifier notifier = new PermissionNotifier();
        assertDoesNotThrow(() -> notifier.notifyPermissionChange(0, "AppWithZeroPermissionCode"));
    }
}


import java.util.Scanner;
public class SimpleCalculator {
    public void calculate(double num1, double num2, String operation) {
        switch (operation) {
            case "add":
                System.out.println("结果: " + (num1 + num2));
                break;
            case "subtract":
                System.out.println("结果: " + (num1 - num2));
                break;
            case "multiply":
                System.out.println("结果: " + (num1 * num2));
                break;
            case "divide":
                if (num2 == 0) {
                    System.out.println("错误: 除数不能为0");
                } else {
                    System.out.println("结果: " + (num1 / num2));
                }
                break;
            default:
                System.out.println("错误: 不支持的运算类型");
        }
    }
    public static void main(String[] args) {
        SimpleCalculator calculator = new SimpleCalculator();
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入第一个数:");
        double num1 = scanner.nextDouble();
        System.out.println("请输入第二个数:");
        double num2 = scanner.nextDouble();
        scanner.nextLine();
        System.out.println("请输入运算类型（add, subtract, multiply, divide）:");
        String operation = scanner.nextLine();
        calculator.calculate(num1, num2, operation);
    }
}

Please write a Java program to implement a simple calculator functionality. The calculator should perform addition, subtraction, multiplication, and division operations based on user input. The specific requirements are as follows:

- The program should include a class named `SimpleCalculator`.
- The class should contain a method named `calculate`, which accepts three parameters: two `double` type numbers `num1` and `num2`, and a `String` type parameter `operation` that indicates the type of operation to be performed ("add", "subtract", "multiply", "divide").
- Based on the value of `operation`, the `calculate` method should perform the corresponding operation and print the result.
- If `operation` is not one of these four operations, the program should print an error message.
- Ensure that in the case of division, if `num2` is 0, an error message should be printed to avoid division by zero.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.Scanner;
public class SimpleCalculator {
    public void calculate(double num1, double num2, String operation) {
    }
}
```

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class SimpleCalculatorTest {
    @Test
    void testAddition() {
        SimpleCalculator calculator = new SimpleCalculator();
        double num1 = 5.0;
        double num2 = 3.0;
        String operation = "add";
        calculator.calculate(num1, num2, operation);
    }
    @Test
    void testSubtraction() {
        SimpleCalculator calculator = new SimpleCalculator();
        double num1 = 5.0;
        double num2 = 3.0;
        String operation = "subtract";
        calculator.calculate(num1, num2, operation);
    }
    @Test
    void testMultiplication() {
        SimpleCalculator calculator = new SimpleCalculator();
        double num1 = 5.0;
        double num2 = 3.0;
        String operation = "multiply";
        calculator.calculate(num1, num2, operation);
    }
    @Test
    void testDivision() {
        SimpleCalculator calculator = new SimpleCalculator();
        double num1 = 6.0;
        double num2 = 3.0;
        String operation = "divide";
        calculator.calculate(num1, num2, operation);
    }
    @Test
    void testDivisionByZero() {
        SimpleCalculator calculator = new SimpleCalculator();
        double num1 = 6.0;
        double num2 = 0.0;
        String operation = "divide";
        calculator.calculate(num1, num2, operation);
    }
    @Test
    void testUnsupportedOperation() {
        SimpleCalculator calculator = new SimpleCalculator();
        double num1 = 6.0;
        double num2 = 3.0;
        String operation = "modulus";
        calculator.calculate(num1, num2, operation);
    }
}


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Collections;
import java.util.Comparator;
public class StringCounter {
    public List<Map.Entry<String, Integer>> countAndSortStrings(List<Map.Entry<String, Integer>> entries) {
        HashMap<String, Integer> countMap = new HashMap<>();
        for (Map.Entry<String, Integer> entry : entries) {
            String key = entry.getKey();
            Integer value = entry.getValue();
            countMap.put(key, countMap.getOrDefault(key, 0) + value);
        }
        List<Map.Entry<String, Integer>> sortedList = new ArrayList<>(countMap.entrySet());
        Collections.sort(sortedList, new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                return o1.getKey().compareTo(o2.getKey());
            }
        });
        return sortedList;
    }
    public static void main(String[] args) {
        List<Map.Entry<String, Integer>> entries = new ArrayList<>();
        entries.add(new HashMap.SimpleEntry<>("apple", 2));
        entries.add(new HashMap.SimpleEntry<>("banana", 3));
        entries.add(new HashMap.SimpleEntry<>("apple", 1));
        StringCounter counter = new StringCounter();
        List<Map.Entry<String, Integer>> result = counter.countAndSortStrings(entries);
        for (Map.Entry<String, Integer> entry : result) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}

Please implement a function that can count the occurrences of each unique string in a dataset and output the results in the natural order of the strings. Ensure that your function can handle a list containing strings and their corresponding counts, and output the statistical results in the format of strings and counts. Additionally, the output strings should be sorted in their natural order.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Collections;
import java.util.Comparator;
public class StringCounter {
    public List<Map.Entry<String, Integer>> countAndSortStrings(List<Map.Entry<String, Integer>> entries) {
    }
}
```

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Collections;
import java.util.Comparator;
import org.junit.Test;
import static org.junit.Assert.*;
public class StringCounterTest {
    @Test
    public void testCountAndSortStrings_singleEntry() {
        List<Map.Entry<String, Integer>> entries = new ArrayList<>();
        entries.add(new HashMap.SimpleEntry<>("apple", 2));
        StringCounter counter = new StringCounter();
        List<Map.Entry<String, Integer>> result = counter.countAndSortStrings(entries);
        assertEquals(1, result.size());
        assertEquals("apple", result.get(0).getKey());
        assertEquals(Integer.valueOf(2), result.get(0).getValue());
    }
    @Test
    public void testCountAndSortStrings_multipleEntriesSameKey() {
        List<Map.Entry<String, Integer>> entries = new ArrayList<>();
        entries.add(new HashMap.SimpleEntry<>("apple", 2));
        entries.add(new HashMap.SimpleEntry<>("apple", 1));
        StringCounter counter = new StringCounter();
        List<Map.Entry<String, Integer>> result = counter.countAndSortStrings(entries);
        assertEquals(1, result.size());
        assertEquals("apple", result.get(0).getKey());
        assertEquals(Integer.valueOf(3), result.get(0).getValue());
    }
    @Test
    public void testCountAndSortStrings_multipleEntriesDifferentKeys() {
        List<Map.Entry<String, Integer>> entries = new ArrayList<>();
        entries.add(new HashMap.SimpleEntry<>("banana", 3));
        entries.add(new HashMap.SimpleEntry<>("apple", 1));
        StringCounter counter = new StringCounter();
        List<Map.Entry<String, Integer>> result = counter.countAndSortStrings(entries);
        assertEquals(2, result.size());
        assertEquals("apple", result.get(0).getKey());
        assertEquals(Integer.valueOf(1), result.get(0).getValue());
        assertEquals("banana", result.get(1).getKey());
        assertEquals(Integer.valueOf(3), result.get(1).getValue());
    }
    @Test
    public void testCountAndSortStrings_emptyList() {
        List<Map.Entry<String, Integer>> entries = new ArrayList<>();
        StringCounter counter = new StringCounter();
        List<Map.Entry<String, Integer>> result = counter.countAndSortStrings(entries);
        assertTrue(result.isEmpty());
    }
    @Test
    public void testCountAndSortStrings_mixedEntries() {
        List<Map.Entry<String, Integer>> entries = new ArrayList<>();
        entries.add(new HashMap.SimpleEntry<>("banana", 3));
        entries.add(new HashMap.SimpleEntry<>("apple", 1));
        entries.add(new HashMap.SimpleEntry<>("banana", 2));
        StringCounter counter = new StringCounter();
        List<Map.Entry<String, Integer>> result = counter.countAndSortStrings(entries);
        assertEquals(2, result.size());
        assertEquals("apple", result.get(0).getKey());
        assertEquals(Integer.valueOf(1), result.get(0).getValue());
        assertEquals("banana", result.get(1).getKey());
        assertEquals(Integer.valueOf(5), result.get(1).getValue());
    }
}


import java.util.HashMap;
import java.util.Map;
public class BookManager {
    static class Book {
        String id;
        String title;
        String author;
        public Book(String id, String title, String author) {
            this.id = id;
            this.title = title;
            this.author = author;
        }
        @Override
        public String toString() {
            return "Book{" +
                    "id='" + id + '\'' +
                    ", title='" + title + '\'' +
                    ", author='" + author + '\'' +
                    '}';
        }
    }
    public static void updateBook(Book book, String fieldMask) {
        String[] fieldsToUpdate = fieldMask.split(",");
        Map<String, String> updates = new HashMap<>();
        for (String field : fieldsToUpdate) {
            String[] keyValue = field.split("=");
            if (keyValue.length == 2) {
                updates.put(keyValue[0].trim(), keyValue[1].trim());
            }
        }
        if (updates.containsKey("title")) {
            book.title = updates.get("title");
        }
        if (updates.containsKey("author")) {
            book.author = updates.get("author");
        }
    }
    public static void main(String[] args) {
        Book book = new Book("1", "Old Title", "Old Author");
        System.out.println("Before update: " + book);
        updateBook(book, "title=New Title, author=New Author");
        System.out.println("After update: " + book);
    }
}

Please write a Java program to implement the book update function in a simple library management system. In this system, each book has a unique ID, title, and author name. You need to implement a method that accepts a book object and an update mask (FieldMask), and then updates the book information based on the fields specified by the update mask. The update mask is a string containing the names of the fields to be updated, separated by commas. If the update mask is empty, no fields are updated.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.HashMap;
import java.util.Map;
public class BookManager {
    static class Book {
        String id;
        String title;
        String author;
        public Book(String id, String title, String author) {
        }
        @Override
        public String toString() {
            return "Book{" +
                    "id='" + id + '\'' +
                    ", title='" + title + '\'' +
                    ", author='" + author + '\'' +
                    '}';
        }
    }
    public static void updateBook(Book book, String fieldMask) {
    }
}
```

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class BookManagerTest {
    @Test
    public void testUpdateTitleAndAuthor() {
        BookManager.Book book = new BookManager.Book("1", "Old Title", "Old Author");
        BookManager.updateBook(book, "title=New Title, author=New Author");
        assertEquals("New Title", book.title);
        assertEquals("New Author", book.author);
    }
    @Test
    public void testUpdateTitleOnly() {
        BookManager.Book book = new BookManager.Book("1", "Old Title", "Old Author");
        BookManager.updateBook(book, "title=New Title");
        assertEquals("New Title", book.title);
        assertEquals("Old Author", book.author);
    }
    @Test
    public void testUpdateAuthorOnly() {
        BookManager.Book book = new BookManager.Book("1", "Old Title", "Old Author");
        BookManager.updateBook(book, "author=New Author");
        assertEquals("Old Title", book.title);
        assertEquals("New Author", book.author);
    }
    @Test
    public void testUpdateNoChanges() {
        BookManager.Book book = new BookManager.Book("1", "Old Title", "Old Author");
        BookManager.updateBook(book, "");
        assertEquals("Old Title", book.title);
        assertEquals("Old Author", book.author);
    }
    @Test
    public void testUpdateWithInvalidMask() {
        BookManager.Book book = new BookManager.Book("1", "Old Title", "Old Author");
        BookManager.updateBook(book, "title=New Title, invalidField=invalid");
        assertEquals("New Title", book.title);
        assertEquals("Old Author", book.author);
    }
}


import java.util.Scanner;
public class RightAlignedTriangle {
    public static String generatePattern(int height) {
        StringBuilder pattern = new StringBuilder();
        for (int row = 0; row < height; row++) {
            for (int space = 0; space < height - row - 1; space++) {
                pattern.append(" ");
            }
            for (int star = 0; star <= row; star++) {
                pattern.append("*");
            }
            pattern.append(System.lineSeparator());
        }
        return pattern.toString();
    }
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入三角形的高度：");
        int height = scanner.nextInt();
        String trianglePattern = generatePattern(height);
        System.out.println(trianglePattern);
    }
    public static boolean checkPattern(int height, String expectedPattern) {
        String generatedPattern = generatePattern(height);
        return generatedPattern.equals(expectedPattern);
    }
}

Please write a Java program to generate a right-aligned triangle pattern. The height of the triangle is determined by user input, with each row of the pattern composed of `*` characters, and the number of characters increasing gradually in each row. For example, if the user inputs a height of 4, the output pattern should be as follows:

```
   *
  **
 ***
****
```

Please ensure your program meets the following requirements:
- Use the Java programming language.
- The program should include a class named `RightAlignedTriangle` and a method named `generatePattern`.
- The `generatePattern` method should accept an integer parameter `height`, which represents the height of the triangle, and return a string that contains the entire triangle pattern.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.Scanner;
public class RightAlignedTriangle {
    public static String generatePattern(int height) {
    }
    public static boolean checkPattern(int height, String expectedPattern) {
    }
}
```

import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
public class RightAlignedTriangleTest {
    @Test
    void generatePattern_heightZero_shouldReturnEmptyString() {
        int height = 0;
        String expectedPattern = "";
        String actualPattern = RightAlignedTriangle.generatePattern(height);
        assertEquals(expectedPattern, actualPattern);
    }
    @Test
    void generatePattern_heightOne_shouldReturnSingleAsterisk() {
        int height = 1;
        String expectedPattern = "*\n";
        String actualPattern = RightAlignedTriangle.generatePattern(height);
        assertEquals(expectedPattern, actualPattern);
    }
    @Test
    void generatePattern_heightThree_shouldReturnTriangle() {
        int height = 3;
        String expectedPattern = "  *\n **\n***\n";
        String actualPattern = RightAlignedTriangle.generatePattern(height);
        assertEquals(expectedPattern, actualPattern);
    }
    @Test
    void checkPattern_correctPattern_shouldReturnTrue() {
        int height = 3;
        String expectedPattern = "  *\n **\n***\n";
        assertTrue(RightAlignedTriangle.checkPattern(height, expectedPattern));
    }
    @Test
    void checkPattern_incorrectPattern_shouldReturnFalse() {
        int height = 3;
        String incorrectPattern = "  *\n **\n*** \n";
        assertFalse(RightAlignedTriangle.checkPattern(height, incorrectPattern));
    }
}


import java.util.Arrays;
class Book {
    boolean isBorrowed;
    public Book(boolean isBorrowed) {
        this.isBorrowed = isBorrowed;
    }
    public void setBorrowed(boolean isBorrowed) {
        this.isBorrowed = isBorrowed;
    }
    public boolean isBorrowed() {
        return this.isBorrowed;
    }
}
class Library {
    Book[] books;
    public Library(Book[] books) {
        this.books = books;
    }
    public void resetBooksStatus() {
        for (Book book : books) {
            book.setBorrowed(false);
        }
    }
}
public class Main {
    public static void main(String[] args) {
        Book[] books = {
            new Book(true),
            new Book(false),
            new Book(true),
            new Book(true)
        };
        Library library = new Library(books);
        library.resetBooksStatus();
        check(books);
    }
    public static void check(Book[] books) {
        for (Book book : books) {
            if (book.isBorrowed()) {
                System.out.println("错误：存在未正确重置的图书。");
                return;
            }
        }
        System.out.println("所有图书的状态已正确重置为未借出。");
    }
}

Please write a Java program that implements a function in a simple book management system: reset the status of all books to not borrowed. In this system, each book has a status indicating whether it is borrowed. We use a `Book` class to represent each book, which contains a boolean member variable `isBorrowed` that indicates the borrowing status of the book (`true` means borrowed, `false` means not borrowed). You need to write a class named `Library`, which contains a method `resetBooksStatus` that resets the status of all books in the inventory to not borrowed.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.Arrays;
class Book {
    boolean isBorrowed;
    public Book(boolean isBorrowed) {
    }
    public void setBorrowed(boolean isBorrowed) {
    }
    public boolean isBorrowed() {
    }
}
class Library {
    Book[] books;
    public Library(Book[] books) {
    }
    public void resetBooksStatus() {
    }
}
```

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class BookTest {
    @Test
    public void testSetBorrowed() {
        Book book = new Book(false);
        book.setBorrowed(true);
        Assertions.assertTrue(book.isBorrowed());
    }
    @Test
    public void testIsBorrowed() {
        Book book = new Book(true);
        Assertions.assertTrue(book.isBorrowed());
    }
    @Test
    public void testConstructor() {
        Book book = new Book(false);
        Assertions.assertFalse(book.isBorrowed());
    }
}
class LibraryTest {
    @Test
    public void testResetBooksStatus() {
        Book[] books = {
            new Book(true),
            new Book(true),
            new Book(true)
        };
        Library library = new Library(books);
        library.resetBooksStatus();
        for (Book book : books) {
            Assertions.assertFalse(book.isBorrowed());
        }
    }
    @Test
    public void testResetBooksStatusWithMixedStatus() {
        Book[] books = {
            new Book(true),
            new Book(false),
            new Book(true),
            new Book(false)
        };
        Library library = new Library(books);
        library.resetBooksStatus();
        for (Book book : books) {
            Assertions.assertFalse(book.isBorrowed());
        }
    }
}


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
public class SongSelector {
    private HashMap<String, List<String>> genreToSongsMap;
    private Random random;
    public SongSelector() {
        genreToSongsMap = new HashMap<>();
        random = new Random();
    }
    public void addSong(String genre, String song) {
        genreToSongsMap.computeIfAbsent(genre, k -> new ArrayList<>()).add(song);
    }
    public String getRandomSongFromGenre(String genre) {
        List<String> songs = genreToSongsMap.get(genre);
        if (songs == null || songs.isEmpty()) {
            return null;
        }
        int index = random.nextInt(songs.size());
        return songs.get(index);
    }
    public static void main(String[] args) {
        SongSelector selector = new SongSelector();
        selector.addSong("Pop", "Song A");
        selector.addSong("Pop", "Song B");
        selector.addSong("Rock", "Song C");
        System.out.println("Random Pop Song: " + selector.getRandomSongFromGenre("Pop"));
        System.out.println("Random Rock Song: " + selector.getRandomSongFromGenre("Rock"));
        System.out.println("Random Jazz Song: " + selector.getRandomSongFromGenre("Jazz"));
    }
}

Assume you are developing a music player application, and you need to implement a feature that randomly selects a song from a given collection of songs to play. Each song belongs to a specific genre (like Pop, Rock, Jazz, etc.), and users can choose a genre. The application will then randomly pick a song from that genre to play.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
public class SongSelector {
    private HashMap<String, List<String>> genreToSongsMap;
    private Random random;
    public SongSelector() {
    }
    public void addSong(String genre, String song) {
    }
    public String getRandomSongFromGenre(String genre) {
    }
}
```

import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class SongSelectorTest {
    private SongSelector songSelector;
    @Before
    public void setUp() {
        songSelector = new SongSelector();
    }
    @Test
    public void testAddSong() {
        songSelector.addSong("Pop", "Song A");
        String song = songSelector.getRandomSongFromGenre("Pop");
        assertNotNull(song);
    }
    @Test
    public void testGetRandomSongFromGenreWithSingleSong() {
        songSelector.addSong("Rock", "Song C");
        String song = songSelector.getRandomSongFromGenre("Rock");
        assertEquals("Song C", song);
    }
    @Test
    public void testGetRandomSongFromGenreWithMultipleSongs() {
        songSelector.addSong("Pop", "Song A");
        songSelector.addSong("Pop", "Song B");
        String song = songSelector.getRandomSongFromGenre("Pop");
        assertTrue(song.equals("Song A") || song.equals("Song B"));
    }
    @Test
    public void testGetRandomSongFromGenreWithNoSongs() {
        String song = songSelector.getRandomSongFromGenre("Jazz");
        assertNull(song);
    }
    @Test
    public void testGetRandomSongFromEmptyGenre() {
        songSelector.addSong("Classical", "Song D");
        songSelector.getRandomSongFromGenre("Classical");
        String song = songSelector.getRandomSongFromGenre("EmptyGenre");
        assertNull(song);
    }
}


import java.util.ArrayList;
import java.util.List;
public class DataNotifier {
    private List<Object> dataList;
    private List<Object> initDataList() {
        return new ArrayList<>();
    }
    public void addElementsAndNotify(List<Object> newElements) {
        if (dataList == null) {
            dataList = initDataList();
        }
        if (newElements == null) {
            newElements = new ArrayList<>();
        }
        if (newElements.isEmpty()) {
            return;
        }
        dataList.addAll(newElements);
        notifyDataChanged();
    }
    private void notifyDataChanged() {
        System.out.println("数据已更改。");
    }
    public static void main(String[] args) {
        DataNotifier notifier = new DataNotifier();
        List<Object> elementsToAdd = new ArrayList<>();
        elementsToAdd.add("Java");
        elementsToAdd.add("Python");
        notifier.addElementsAndNotify(elementsToAdd);
        notifier.addElementsAndNotify(null);
        List<Object> emptyList = new ArrayList<>();
        notifier.addElementsAndNotify(emptyList);
    }
}

Please write a Java method to add a series of elements to a custom data collection and notify when the data has changed afterwards. The method should meet the following requirements:

1. If the passed collection is `null`, a new empty collection should be created.
2. If the passed collection is empty, no action should be performed.
3. After adding the elements, a method should be called to notify that the data has changed.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.ArrayList;
import java.util.List;
public class DataNotifier {
    private List<Object> dataList;
    private List<Object> initDataList() {
    }
    public void addElementsAndNotify(List<Object> newElements) {
    }
    private void notifyDataChanged() {
    }
}
```

import org.junit.Test;
import org.junit.Before;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
public class DataNotifierTest {
    private DataNotifier dataNotifier;
    @Before
    public void setUp() {
        dataNotifier = new DataNotifier();
    }
    @Test
    public void testAddElementsAndNotify_WithNonNullElements() {
        List<Object> elementsToAdd = new ArrayList<>();
        elementsToAdd.add("Java");
        elementsToAdd.add("Python");
        dataNotifier.addElementsAndNotify(elementsToAdd);
    }
    @Test
    public void testAddElementsAndNotify_WithNullElements() {
        dataNotifier.addElementsAndNotify(null);
    }
    @Test
    public void testAddElementsAndNotify_WithEmptyList() {
        List<Object> emptyList = new ArrayList<>();
        dataNotifier.addElementsAndNotify(emptyList);
    }
    @Test
    public void testAddElementsAndNotify_NoPriorInitialization() {
        List<Object> elementsToAdd = new ArrayList<>();
        elementsToAdd.add("Java");
        elementsToAdd.add("Python");
        dataNotifier.addElementsAndNotify(elementsToAdd);
    }
    @Test
    public void testAddElementsAndNotify_MultipleCalls() {
        List<Object> firstBatch = new ArrayList<>();
        firstBatch.add("Java");
        List<Object> secondBatch = new ArrayList<>();
        secondBatch.add("Python");
        dataNotifier.addElementsAndNotify(firstBatch);
        dataNotifier.addElementsAndNotify(secondBatch);
    }
}


import java.util.HashMap;
import java.util.Map;
public class BookLoanManager {
    private Map<Long, Long> bookBorrowTimes;
    public BookLoanManager() {
        bookBorrowTimes = new HashMap<>();
    }
    public void setBorrowTime(Long bookId, Long borrowTime) {
        bookBorrowTimes.put(bookId, borrowTime);
    }
    public Long getLastBorrowedTime(Long bookId) {
        return bookBorrowTimes.getOrDefault(bookId, null);
    }
    public static void main(String[] args) {
        BookLoanManager manager = new BookLoanManager();
        manager.setBorrowTime(1001L, 1625140800000L);
        manager.setBorrowTime(1002L, 1625227200000L);
        check(manager.getLastBorrowedTime(1001L) == 1625140800000L, "书籍1001的借阅时间检查失败");
        check(manager.getLastBorrowedTime(1002L) == 1625227200000L, "书籍1002的借阅时间检查失败");
        check(manager.getLastBorrowedTime(1003L) == null, "书籍1003的借阅时间检查失败");
    }
    private static void check(boolean condition, String message) {
        if (!condition) {
            throw new AssertionError(message);
        }
    }
}

Please write a Java program to manage the borrowing information of books in a library. Specifically, you need to implement a method that receives a book ID as a parameter and returns the last borrowing time of the book. If the book has never been borrowed, it should return null.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.HashMap;
import java.util.Map;
public class BookLoanManager {
    private Map<Long, Long> bookBorrowTimes;
    public BookLoanManager() {
    }
    public void setBorrowTime(Long bookId, Long borrowTime) {
    }
    public Long getLastBorrowedTime(Long bookId) {
    }
}
```

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class BookLoanManagerTest {
    private BookLoanManager manager;
    @BeforeEach
    public void setUp() {
        manager = new BookLoanManager();
    }
    @Test
    public void testSetAndGetBorrowTime() {
        manager.setBorrowTime(1001L, 1625140800000L);
        Long borrowTime = manager.getLastBorrowedTime(1001L);
        assertEquals(1625140800000L, borrowTime);
    }
    @Test
    public void testGetLastBorrowedTime_NotSet() {
        Long borrowTime = manager.getLastBorrowedTime(1003L);
        assertNull(borrowTime);
    }
    @Test
    public void testSetBorrowTime_Overwrite() {
        manager.setBorrowTime(1001L, 1625140800000L);
        manager.setBorrowTime(1001L, 1625301600000L);
        Long borrowTime = manager.getLastBorrowedTime(1001L);
        assertEquals(1625301600000L, borrowTime);
    }
    @Test
    public void testMultipleBooksBorrowTimes() {
        manager.setBorrowTime(1001L, 1625140800000L);
        manager.setBorrowTime(1002L, 1625227200000L);
        assertEquals(1625140800000L, manager.getLastBorrowedTime(1001L));
        assertEquals(1625227200000L, manager.getLastBorrowedTime(1002L));
    }
    @Test
    public void testGetLastBorrowedTime_WithBorrowTimeSetToNull() {
        manager.setBorrowTime(1004L, null);
        assertNull(manager.getLastBorrowedTime(1004L));
    }
}


import java.util.HashMap;
import java.util.Map;
public class WeekdayFinder {
    public static String getWeekdayName(int num) {
        Map<Integer, String> weekDays = new HashMap<>();
        weekDays.put(1, "星期一");
        weekDays.put(2, "星期二");
        weekDays.put(3, "星期三");
        weekDays.put(4, "星期四");
        weekDays.put(5, "星期五");
        weekDays.put(6, "星期六");
        weekDays.put(7, "星期日");
        return weekDays.getOrDefault(num, "无效输入");
    }
    public static void main(String[] args) {
        assert "星期一".equals(getWeekdayName(1));
        assert "星期二".equals(getWeekdayName(2));
        assert "星期三".equals(getWeekdayName(3));
        assert "星期四".equals(getWeekdayName(4));
        assert "星期五".equals(getWeekdayName(5));
        assert "星期六".equals(getWeekdayName(6));
        assert "星期日".equals(getWeekdayName(7));
        assert "无效输入".equals(getWeekdayName(8));
        assert "无效输入".equals(getWeekdayName(0));
        System.out.println("所有测试用例都通过了！");
    }
}

Please write a Java method that takes an integer parameter `num` and returns the corresponding day of the week based on the value of that parameter. If the value of `num` is between 1 and 7, return "Monday" to "Sunday" respectively; if the value of `num` is outside this range, return "Invalid input".
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.HashMap;
import java.util.Map;
public class WeekdayFinder {
    public static String getWeekdayName(int num) {
    }
}
```

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class WeekdayFinderTest {
    @Test
    public void testWeekdayMonday() {
        assertEquals("星期一", WeekdayFinder.getWeekdayName(1));
    }
    @Test
    public void testWeekdayTuesday() {
        assertEquals("星期二", WeekdayFinder.getWeekdayName(2));
    }
    @Test
    public void testWeekdayWednesday() {
        assertEquals("星期三", WeekdayFinder.getWeekdayName(3));
    }
    @Test
    public void testWeekdaySaturday() {
        assertEquals("星期六", WeekdayFinder.getWeekdayName(6));
    }
    @Test
    public void testInvalidInput() {
        assertEquals("无效输入", WeekdayFinder.getWeekdayName(0));
    }
}


import java.io.File;
import java.io.FileNotFoundException;
public class DirectoryExplorer {
        public static void exploreDirectory(File directory) throws FileNotFoundException {
        if (!directory.exists()) {
            throw new FileNotFoundException("目录不存在: " + directory.getAbsolutePath());
        }
        File[] fileEntries = directory.listFiles();
        if (fileEntries != null) {
            for (File fileEntry : fileEntries) {
                if (fileEntry.isDirectory()) {
                    exploreDirectory(fileEntry);
                } else {
                    System.out.println(fileEntry.getName());
                }
            }
        }
    }
    public static void main(String[] args) {
        try {
            File startingDirectory = new File("path/to/start/directory");
            exploreDirectory(startingDirectory);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

Please write a Java program that can traverse all files and subdirectories in a specified directory and print out the names of all files. If a subdirectory is encountered, the files under that subdirectory should be recursively traversed. Ensure that the program can correctly handle empty directories and nonexistent directories.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.io.File;
import java.io.FileNotFoundException;
public class DirectoryExplorer {
    public static void exploreDirectory(File directory) throws FileNotFoundException {
    }
}
```

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.File;
import java.io.FileNotFoundException;
public class DirectoryExplorerTest {
    @Test
    public void testDirectoryNotExist() {
        File nonExistingDirectory = new File("non/existent/path");
        assertThrows(FileNotFoundException.class, () -> {
            DirectoryExplorer.exploreDirectory(nonExistingDirectory);
        });
    }
    @Test
    public void testEmptyDirectory() throws FileNotFoundException {
        File emptyDirectory = new File("path/to/empty/directory");
        if (!emptyDirectory.exists()) {
            emptyDirectory.mkdirs();
        }
        DirectoryExplorer.exploreDirectory(emptyDirectory);
    }
    @Test
    public void testDirectoryWithFiles() throws FileNotFoundException {
        File directoryWithFiles = new File("path/to/directory/with/files");
        if (!directoryWithFiles.exists()) {
            directoryWithFiles.mkdirs();
        }
        File file1 = new File(directoryWithFiles, "file1.txt");
        File file2 = new File(directoryWithFiles, "file2.txt");
        try {
            file1.createNewFile();
            file2.createNewFile();
        } catch (Exception e) {
            e.printStackTrace();
        }
        DirectoryExplorer.exploreDirectory(directoryWithFiles);
    }
    @Test
    public void testNestedDirectories() throws FileNotFoundException {
        File nestedDirectory = new File("path/to/nested/directory");
        if (!nestedDirectory.exists()) {
            nestedDirectory.mkdirs();
        }
        File subDirectory = new File(nestedDirectory, "subdirectory");
        if (!subDirectory.exists()) {
            subDirectory.mkdirs();
        }
        File file = new File(subDirectory, "file.txt");
        try {
            file.createNewFile();
        } catch (Exception e) {
            e.printStackTrace();
        }
        DirectoryExplorer.exploreDirectory(nestedDirectory);
    }
    @Test
    public void testDirectoryWithMixedContent() throws FileNotFoundException {
        File mixedDirectory = new File("path/to/mixed/content");
        if (!mixedDirectory.exists()) {
            mixedDirectory.mkdirs();
        }
        File subDirectory1 = new File(mixedDirectory, "subdirectory1");
        if (!subDirectory1.exists()) {
            subDirectory1.mkdirs();
        }
        File subDirectory2 = new File(mixedDirectory, "subdirectory2");
        if (!subDirectory2.exists()) {
            subDirectory2.mkdirs();
        }
        File file1 = new File(subDirectory1, "file1.txt");
        File file2 = new File(subDirectory2, "file2.txt");
        try {
            file1.createNewFile();
            file2.createNewFile();
        } catch (Exception e) {
            e.printStackTrace();
        }
        DirectoryExplorer.exploreDirectory(mixedDirectory);
    }
}


import java.util.Arrays;
class NeuralLayer {
    float[][] weights;
    float[][] biases;
    float[][] dWeights;
    float[][] dBiases;
    float[][] weightMomentums;
    float[][] biasMomentums;
    float[][] weightVelocities;
    float[][] biasVelocities;
    public NeuralLayer(int inputSize, int size) {
        weights = new float[size][inputSize];
        biases = new float[size][1];
        for (float[] row : weights) {
            Arrays.fill(row, 0.1f);
        }
        for (float[] row : biases) {
            Arrays.fill(row, 0.1f);
        }
    }
    public void updateWeightsAndBiases(float learningRate, float beta1, float beta2, float epsilon, int iteration) {
        if (weightMomentums == null) {
            weightMomentums = new float[weights.length][weights[0].length];
            biasMomentums = new float[biases.length][biases[0].length];
            weightVelocities = new float[weights.length][weights[0].length];
            biasVelocities = new float[biases.length][biases[0].length];
        }
        for (int i = 0; i < weights.length; i++) {
            for (int j = 0; j < weights[0].length; j++) {
                weightMomentums[i][j] = beta1 * weightMomentums[i][j] + (1 - beta1) * dWeights[i][j];
                float weightMomentumsCorrected = weightMomentums[i][j] / (1 - (float)Math.pow(beta1, iteration + 1));
                weightVelocities[i][j] = beta2 * weightVelocities[i][j] + (1 - beta2) * (dWeights[i][j] * dWeights[i][j]);
                float weightVelocitiesCorrected = weightVelocities[i][j] / (1 - (float)Math.pow(beta2, iteration + 1));
                weights[i][j] -= learningRate * weightMomentumsCorrected / (Math.sqrt(weightVelocitiesCorrected) + epsilon);
            }
        }
        for (int i = 0; i < biases.length; i++) {
            for (int j = 0; j < biases[0].length; j++) {
                biasMomentums[i][j] = beta1 * biasMomentums[i][j] + (1 - beta1) * dBiases[i][j];
                float biasMomentumsCorrected = biasMomentums[i][j] / (1 - (float)Math.pow(beta1, iteration + 1));
                biasVelocities[i][j] = beta2 * biasVelocities[i][j] + (1 - beta2) * (dBiases[i][j] * dBiases[i][j]);
                float biasVelocitiesCorrected = biasVelocities[i][j] / (1 - (float)Math.pow(beta2, iteration + 1));
                biases[i][j] -= learningRate * biasMomentumsCorrected / (Math.sqrt(biasVelocitiesCorrected) + epsilon);
            }
        }
    }
}
public class AdamOptimizerExample {
    public static void main(String[] args) {
        NeuralLayer layer = new NeuralLayer(3, 2);
        layer.dWeights = new float[][]{{0.1f, 0.2f, 0.3f}, {0.4f, 0.5f, 0.6f}};
        layer.dBiases = new float[][]{{0.1f}, {0.2f}};
        layer.updateWeightsAndBiases(0.01f, 0.9f, 0.999f, 1e-8f, 1);
        System.out.println("Updated Weights:");
        for (float[] row : layer.weights) {
            System.out.println(Arrays.toString(row));
        }
        System.out.println("Updated Biases:");
        for (float[] row : layer.biases) {
            System.out.println(Arrays.toString(row));
        }
    }
}

Please implement a Java method that updates parameters in a neural network using the Adam optimization algorithm. Given a neural network layer object, which contains weights, biases, and their gradients (dWeights and dBiases), as well as momentum and velocity for the Adam algorithm, you need to update the weights and biases of this layer according to the Adam algorithm. Note that you should first check if the storage space for momentum and velocity has been initialized; if not, you need to initialize them to zero matrices of the same shape as the weights and biases. Additionally, ensure your method can handle different learning rates, beta1, beta2, and epsilon values.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.Arrays;
class NeuralLayer {
    float[][] weights;
    float[][] biases;
    float[][] dWeights;
    float[][] dBiases;
    float[][] weightMomentums;
    float[][] biasMomentums;
    float[][] weightVelocities;
    float[][] biasVelocities;
    public NeuralLayer(int inputSize, int size) {
    }
    public void updateWeightsAndBiases(float learningRate, float beta1, float beta2, float epsilon, int iteration) {
    }
}
```

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class NeuralLayerTest {
    @Test
    void testInitialization() {
        NeuralLayer layer = new NeuralLayer(3, 2);
        for (float[] row : layer.weights) {
            for (float value : row) {
                assertEquals(0.1f, value);
            }
        }
        for (float[] row : layer.biases) {
            for (float value : row) {
                assertEquals(0.1f, value);
            }
        }
    }
    @Test
    void testUpdateWeightsAndBiases() {
        NeuralLayer layer = new NeuralLayer(3, 2);
        layer.dWeights = new float[][]{{0.1f, 0.2f, 0.3f}, {0.4f, 0.5f, 0.6f}};
        layer.dBiases = new float[][]{{0.1f}, {0.2f}};
        layer.updateWeightsAndBiases(0.01f, 0.9f, 0.999f, 1e-8f, 1);
        assertNotNull(layer.weights);
        assertNotNull(layer.biases);
    }
    @Test
    void testUpdateWeightsAndBiasesMultipleIterations() {
        NeuralLayer layer = new NeuralLayer(3, 2);
        layer.dWeights = new float[][]{{0.1f, 0.2f, 0.3f}, {0.4f, 0.5f, 0.6f}};
        layer.dBiases = new float[][]{{0.1f}, {0.2f}};
        for (int i = 1; i <= 5; i++) {
            layer.updateWeightsAndBiases(0.01f, 0.9f, 0.999f, 1e-8f, i);
        }
        assertNotNull(layer.weights);
        assertNotNull(layer.biases);
    }
    @Test
    void testInitialMomentumAndVelocitiesAreNull() {
        NeuralLayer layer = new NeuralLayer(3, 2);
        assertNull(layer.weightMomentums);
        assertNull(layer.biasMomentums);
        assertNull(layer.weightVelocities);
        assertNull(layer.biasVelocities);
    }
    @Test
    void testMomentumAndVelocitiesAfterUpdate() {
        NeuralLayer layer = new NeuralLayer(3, 2);
        layer.dWeights = new float[][]{{0.1f, 0.2f, 0.3f}, {0.4f, 0.5f, 0.6f}};
        layer.dBiases = new float[][]{{0.1f}, {0.2f}};
        layer.updateWeightsAndBiases(0.01f, 0.9f, 0.999f, 1e-8f, 1);
        assertNotNull(layer.weightMomentums);
        assertNotNull(layer.biasMomentums);
        assertNotNull(layer.weightVelocities);
        assertNotNull(layer.biasVelocities);
    }
}


import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class StudentUpdateService {
    private static Map<Integer, StudentEntity> studentDatabase = new HashMap<>();
    static {
        studentDatabase.put(1, new StudentEntity(1, "张三", new Date()));
        studentDatabase.put(2, new StudentEntity(2, "李四", new Date()));
    }
    public static Callback updateStudent(StudentEntity studentEntity) {
        Date now = new Date();
        for (StudentEntity entity : studentDatabase.values()) {
            if (entity.getName().equals(studentEntity.getName()) && !entity.getId().equals(studentEntity.getId())) {
                return Callback.error("学生姓名已经存在!");
            }
        }
        studentEntity.setUpdateTime(now);
        studentDatabase.put(studentEntity.getId(), studentEntity);
        return Callback.success(true);
    }
    public static void main(String[] args) {
        Callback result1 = updateStudent(new StudentEntity(3, "王五", null));
        System.out.println(result1.getMessage());
        Callback result2 = updateStudent(new StudentEntity(2, "张三", null));
        System.out.println(result2.getMessage());
    }
}
class StudentEntity {
    private Integer id;
    private String name;
    private Date updateTime;
    public StudentEntity(Integer id, String name, Date updateTime) {
        this.id = id;
        this.name = name;
        this.updateTime = updateTime;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Date getUpdateTime() {
        return updateTime;
    }
    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }
}
class Callback {
    private boolean success;
    private String message;
    private Callback(boolean success, String message) {
        this.success = success;
        this.message = message;
    }
    public static Callback success(boolean success) {
        return new Callback(success, "更新成功!");
    }
    public static Callback error(String message) {
        return new Callback(false, message);
    }
    public boolean isSuccess() {
        return success;
    }
    public String getMessage() {
        return message;
    }
}

Please write a Java method to update student information. The method accepts a student entity as a parameter. If the student's name already exists in the database, it does not update the information and returns an error message; if the student's name does not exist, it updates the student information and records the update time. After a successful update, it returns a success message.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class StudentUpdateService {
    private static Map<Integer, StudentEntity> studentDatabase = new HashMap<>();
    static {
    }
    public static Callback updateStudent(StudentEntity studentEntity) {
    }
}
class StudentEntity {
    private Integer id;
    private String name;
    private Date updateTime;
    public StudentEntity(Integer id, String name, Date updateTime) {
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
    }
    public Date getUpdateTime() {
        return updateTime;
    }
    public void setUpdateTime(Date updateTime) {
    }
}
class Callback {
    private boolean success;
    private String message;
    private Callback(boolean success, String message) {
    }
    public static Callback success(boolean success) {
    }
    public static Callback error(String message) {
    }
    public boolean isSuccess() {
        return success;
    }
    public String getMessage() {
        return message;
    }
}
```

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import java.util.Date;
public class StudentUpdateServiceTest {
    @Test
    public void testUpdateStudent_Success_NewStudent() {
        StudentEntity newStudent = new StudentEntity(3, "王五", null);
        Callback result = StudentUpdateService.updateStudent(newStudent);
        assertTrue(result.isSuccess());
        assertEquals("更新成功!", result.getMessage());
    }
    @Test
    public void testUpdateStudent_Error_NameExists() {
        StudentEntity newStudent = new StudentEntity(2, "张三", null);
        Callback result = StudentUpdateService.updateStudent(newStudent);
        assertFalse(result.isSuccess());
        assertEquals("学生姓名已经存在!", result.getMessage());
    }
    @Test
    public void testUpdateStudent_Success_UpdateExistingStudent() {
        StudentEntity existingStudent = new StudentEntity(1, "张三", null);
        Callback result = StudentUpdateService.updateStudent(existingStudent);
        assertTrue(result.isSuccess());
        assertEquals("更新成功!", result.getMessage());
        assertNotNull(existingStudent.getUpdateTime());
    }
    @Test
    public void testUpdateStudent_Success_UpdateDifferentName() {
        StudentEntity newStudent = new StudentEntity(2, "刘备", null);
        Callback result = StudentUpdateService.updateStudent(newStudent);
        assertTrue(result.isSuccess());
        assertEquals("更新成功!", result.getMessage());
    }
    @Test
    public void testUpdateStudent_Success_AddAnotherStudent() {
        StudentEntity newStudent = new StudentEntity(4, "赵六", null);
        Callback result = StudentUpdateService.updateStudent(newStudent);
        assertTrue(result.isSuccess());
        assertEquals("更新成功!", result.getMessage());
    }
}


import java.util.HashMap;
import java.util.Map;
public class DatabaseConfigGenerator {
    public Map<String, String> generateHibernateConfig() {
        HashMap<String, String> config = new HashMap<>();
        config.put("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
        config.put("hibernate.physical_naming_strategy", "org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy");
        return config;
    }
    public static void main(String[] args) {
        DatabaseConfigGenerator configGenerator = new DatabaseConfigGenerator();
        Map<String, String> config = configGenerator.generateHibernateConfig();
        boolean correct = "org.hibernate.dialect.MySQL5Dialect".equals(config.get("hibernate.dialect")) &&
                          "org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy".equals(config.get("hibernate.physical_naming_strategy"));
        System.out.println("配置信息生成" + (correct ? "正确" : "错误"));
    }
}

Please write a Java method that generates database configuration information. This configuration information will be used to configure the Hibernate framework to accommodate specific database dialects and naming strategies. Ensure that your method returns a `Map` object containing the database dialect and naming strategy. To simplify the problem, we only need to focus on the following two configuration items:

1. Database Dialect (`hibernate.dialect`), assuming we are using the MySQL5 dialect.
2. Naming Strategy (`hibernate.naming.physical_strategy`), assuming we are using the physical naming strategy provided by the Spring framework.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.HashMap;
import java.util.Map;
public class DatabaseConfigGenerator {
    public Map<String, String> generateHibernateConfig() {
    }
}
```

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import java.util.Map;
import java.util.HashMap;
public class DatabaseConfigGeneratorTest {
    @Test
    public void testGenerateHibernateConfig_NotNull() {
        DatabaseConfigGenerator configGenerator = new DatabaseConfigGenerator();
        Map<String, String> config = configGenerator.generateHibernateConfig();
        assertNotNull(config, "Config map should not be null");
    }
    @Test
    public void testGenerateHibernateConfig_ContainsDialect() {
        DatabaseConfigGenerator configGenerator = new DatabaseConfigGenerator();
        Map<String, String> config = configGenerator.generateHibernateConfig();
        assertEquals("org.hibernate.dialect.MySQL5Dialect", config.get("hibernate.dialect"), "Config should contain correct hibernate.dialect");
    }
    @Test
    public void testGenerateHibernateConfig_ContainsNamingStrategy() {
        DatabaseConfigGenerator configGenerator = new DatabaseConfigGenerator();
        Map<String, String> config = configGenerator.generateHibernateConfig();
        assertEquals("org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy", config.get("hibernate.physical_naming_strategy"), "Config should contain correct hibernate.physical_naming_strategy");
    }
    @Test
    public void testGenerateHibernateConfig_MapSize() {
        DatabaseConfigGenerator configGenerator = new DatabaseConfigGenerator();
        Map<String, String> config = configGenerator.generateHibernateConfig();
        assertEquals(2, config.size(), "Config map should contain exactly 2 entries");
    }
    @Test
    public void testGenerateHibernateConfig_NoExtraKeys() {
        DatabaseConfigGenerator configGenerator = new DatabaseConfigGenerator();
        Map<String, String> config = configGenerator.generateHibernateConfig();
        assertTrue(config.containsKey("hibernate.dialect") && config.containsKey("hibernate.physical_naming_strategy"), "Config should only contain specific keys");
    }
}


import java.util.ArrayList;
public class EvenNumbersFilter {
    public static int[] filterEvenNumbers(int[] numbers) {
        ArrayList<Integer> evenNumbersList = new ArrayList<>();
        for (int number : numbers) {
            if (number % 2 == 0) {
                evenNumbersList.add(number);
            }
        }
        int[] evenNumbers = new int[evenNumbersList.size()];
        for (int i = 0; i < evenNumbersList.size(); i++) {
            evenNumbers[i] = evenNumbersList.get(i);
        }
        return evenNumbers;
    }
    public static void main(String[] args) {
        int[] inputNumbers = {1, 2, 3, 4, 5, 6};
        int[] expectedOutput = {2, 4, 6};
        int[] actualOutput = filterEvenNumbers(inputNumbers);
        boolean isCorrect = expectedOutput.length == actualOutput.length;
        for (int i = 0; i < expectedOutput.length && isCorrect; i++) {
            if (expectedOutput[i] != actualOutput[i]) {
                isCorrect = false;
            }
        }
        if (isCorrect) {
            System.out.println("解决方案正确！");
        } else {
            System.out.println("解决方案不正确。");
        }
    }
}

Please write a Java program that implements a method which takes an integer array as input and returns a new array containing all the even numbers from the input array. Ensure that your code is self-contained and includes all necessary import statements.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.ArrayList;
public class EvenNumbersFilter {
    public static int[] filterEvenNumbers(int[] numbers) {
    }
}
```

import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
public class EvenNumbersFilterTest {
    @Test
    public void testFilterEvenNumbers_withMixedNumbers() {
        int[] inputNumbers = {1, 2, 3, 4, 5, 6};
        int[] expectedOutput = {2, 4, 6};
        assertArrayEquals(expectedOutput, EvenNumbersFilter.filterEvenNumbers(inputNumbers));
    }
    @Test
    public void testFilterEvenNumbers_withAllEvenNumbers() {
        int[] inputNumbers = {2, 4, 6, 8, 10};
        int[] expectedOutput = {2, 4, 6, 8, 10};
        assertArrayEquals(expectedOutput, EvenNumbersFilter.filterEvenNumbers(inputNumbers));
    }
    @Test
    public void testFilterEvenNumbers_withAllOddNumbers() {
        int[] inputNumbers = {1, 3, 5, 7, 9};
        int[] expectedOutput = {};
        assertArrayEquals(expectedOutput, EvenNumbersFilter.filterEvenNumbers(inputNumbers));
    }
    @Test
    public void testFilterEvenNumbers_withNoNumbers() {
        int[] inputNumbers = {};
        int[] expectedOutput = {};
        assertArrayEquals(expectedOutput, EvenNumbersFilter.filterEvenNumbers(inputNumbers));
    }
    @Test
    public void testFilterEvenNumbers_withNegativeNumbers() {
        int[] inputNumbers = {-3, -2, -1, 0, 1, 2};
        int[] expectedOutput = {-2, 0, 2};
        assertArrayEquals(expectedOutput, EvenNumbersFilter.filterEvenNumbers(inputNumbers));
    }
}


import java.util.HashMap;
import java.util.Map;
public class LibraryService {
    private Map<String, Boolean> bookCatalog = new HashMap<>();
    public LibraryService() {
        bookCatalog.put("B001", false);
        bookCatalog.put("B002", false);
        bookCatalog.put("B003", false);
    }
    public String borrowBookById(String bookId) {
        Boolean isBorrowed = bookCatalog.get(bookId);
        if (isBorrowed == null) {
            return "错误：书籍ID不存在。";
        } else if (isBorrowed) {
            return "书籍已被借出。";
        } else {
            bookCatalog.put(bookId, true);
            return "书籍成功借出。";
        }
    }
    public static void main(String[] args) {
        LibraryService libraryService = new LibraryService();
        System.out.println(libraryService.borrowBookById("B001"));
        System.out.println(libraryService.borrowBookById("B004"));
        System.out.println(libraryService.borrowBookById("B001"));
    }
}

Please write a Java method to handle the borrowing of books in a library. When a user wants to borrow a book, the method will update the status of the book based on the book's ID to indicate that the book has been borrowed. If the operation is successful, return a string message indicating the book has been successfully borrowed; otherwise, return an error message.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.HashMap;
import java.util.Map;
public class LibraryService {
    private Map<String, Boolean> bookCatalog = new HashMap<>();
    public LibraryService() {
    }
    public String borrowBookById(String bookId) {
    }
}
```

import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class LibraryServiceTest {
    private LibraryService libraryService;
    @BeforeEach
    void setUp() {
        libraryService = new LibraryService();
    }
    @Test
    void testBorrowBookById_Success() {
        String result = libraryService.borrowBookById("B001");
        assertEquals("书籍成功借出。", result);
    }
    @Test
    void testBorrowBookById_BookDoesNotExist() {
        String result = libraryService.borrowBookById("B004");
        assertEquals("错误：书籍ID不存在。", result);
    }
    @Test
    void testBorrowBookById_AlreadyBorrowed() {
        libraryService.borrowBookById("B002");
        String result = libraryService.borrowBookById("B002");
        assertEquals("书籍已被借出。", result);
    }
    @Test
    void testBorrowBookById_Null() {
        String result = libraryService.borrowBookById("B003");
        assertEquals("书籍成功借出。", result);
    }
    @Test
    void testBorrowBookById_SuccessWithDifferentBookId() {
        String result = libraryService.borrowBookById("B003");
        assertEquals("书籍成功借出。", result);
    }
}


import java.util.Arrays;
import java.util.List;
public class SimpleCalculator {
    public double add(double a, double b) {
        return a + b;
    }
    public double subtract(double a, double b) {
        return a - b;
    }
    public double multiply(double a, double b) {
        return a * b;
    }
    public double divide(double a, double b) {
        if (b == 0) {
            return Double.NaN;
        }
        return a / b;
    }
    public static void main(String[] args) {
        SimpleCalculator calculator = new SimpleCalculator();
        List<Double> results = Arrays.asList(
                calculator.add(5, 3),
                calculator.subtract(10, 4),
                calculator.multiply(2, 3),
                calculator.divide(8, 2),
                calculator.divide(5, 0)
        );
        System.out.println("计算结果：" + results);
    }
}

Please write a Java program to implement a simple calculator class `SimpleCalculator`. This class should be able to perform basic arithmetic operations: addition, subtraction, multiplication, and division. Each operation should be implemented through a method that accepts two `double` type parameters and returns a `double` type result. Ensure that the division method can handle the case of a zero divisor, in which case it should return `Double.NaN`.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.Arrays;
import java.util.List;
public class SimpleCalculator {
    public double add(double a, double b) {
    }
    public double subtract(double a, double b) {
    }
    public double multiply(double a, double b) {
    }
    public double divide(double a, double b) {
    }
}
```

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class SimpleCalculatorTest {
    @Test
    public void testAdd() {
        SimpleCalculator calculator = new SimpleCalculator();
        assertEquals(8.0, calculator.add(5, 3));
        assertEquals(14.0, calculator.add(10, 4));
    }
    @Test
    public void testSubtract() {
        SimpleCalculator calculator = new SimpleCalculator();
        assertEquals(6.0, calculator.subtract(10, 4));
        assertEquals(1.0, calculator.subtract(5, 4));
    }
    @Test
    public void testMultiply() {
        SimpleCalculator calculator = new SimpleCalculator();
        assertEquals(6.0, calculator.multiply(2, 3));
        assertEquals(0.0, calculator.multiply(0, 5));
    }
    @Test
    public void testDivide() {
        SimpleCalculator calculator = new SimpleCalculator();
        assertEquals(4.0, calculator.divide(8, 2));
        assertTrue(Double.isNaN(calculator.divide(5, 0)));
    }
    @Test
    public void testDivideByZero() {
        SimpleCalculator calculator = new SimpleCalculator();
        assertTrue(Double.isNaN(calculator.divide(5, 0)));
        assertTrue(Double.isNaN(calculator.divide(-5, 0)));
    }
}


import java.lang.Math;
public class Rectangle {
    private double length;
    private double width;
    public Rectangle(double length, double width) {
        this.length = length;
        this.width = width;
    }
    public double calculateArea() {
        return length * width;
    }
    public static void main(String[] args) {
        Rectangle rect1 = new Rectangle(5.0, 4.0);
        Rectangle rect2 = new Rectangle(7.5, 3.5);
        System.out.println("矩形1的面积: " + rect1.calculateArea());
        System.out.println("矩形2的面积: " + rect2.calculateArea());
    }
}

Write a Java program to calculate the area of a rectangle. Ensure that your program meets the following requirements:

- Your program should include a class named `Rectangle`.
- In the `Rectangle` class, there should be two attributes: `length` and `width`, which are used to store the length and width of the rectangle, respectively.
- The class should have a constructor that accepts two parameters (length and width) and initializes the object accordingly.
- The class should include a method named `calculateArea`, which calculates and returns the area of the rectangle.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.lang.Math;
public class Rectangle {
    private double length;
    private double width;
    public Rectangle(double length, double width) {
    }
    public double calculateArea() {
    }
}
```

import org.junit.Test;
import static org.junit.Assert.*;
public class RectangleTest {
    @Test
    public void testCalculateAreaPositiveNumbers() {
        Rectangle rect = new Rectangle(5.0, 4.0);
        assertEquals(20.0, rect.calculateArea(), 0.0001);
    }
    @Test
    public void testCalculateAreaZeroLength() {
        Rectangle rect = new Rectangle(0, 4.0);
        assertEquals(0.0, rect.calculateArea(), 0.0001);
    }
    @Test
    public void testCalculateAreaZeroWidth() {
        Rectangle rect = new Rectangle(5.0, 0);
        assertEquals(0.0, rect.calculateArea(), 0.0001);
    }
    @Test
    public void testCalculateAreaNegativeNumbers() {
        Rectangle rect = new Rectangle(-5.0, 4.0);
        assertEquals(-20.0, rect.calculateArea(), 0.0001);
    }
    @Test
    public void testCalculateAreaDecimalNumbers() {
        Rectangle rect = new Rectangle(7.5, 3.5);
        assertEquals(26.25, rect.calculateArea(), 0.0001);
    }
}


import java.util.HashMap;
public class StudentScoreManager {
    private HashMap<String, Integer> studentScores;
    public StudentScoreManager() {
        studentScores = new HashMap<>();
    }
    public void addStudentScore(String name, int score) {
        studentScores.put(name, score);
    }
    public int getStudentScore(String name) {
        return studentScores.getOrDefault(name, -1);
    }
    public static void main(String[] args) {
        StudentScoreManager manager = new StudentScoreManager();
        manager.addStudentScore("张三", 90);
        manager.addStudentScore("李四", 85);
        System.out.println("张三的分数是：" + manager.getStudentScore("张三"));
        System.out.println("李四的分数是：" + manager.getStudentScore("李四"));
        System.out.println("王五的分数是：" + manager.getStudentScore("王五"));
    }
}

Please design a simple student information management system. This system should allow users to store students' names and their scores, and be able to query their scores by the students' names.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.HashMap;
public class StudentScoreManager {
    private HashMap<String, Integer> studentScores;
    public StudentScoreManager() {
    }
    public void addStudentScore(String name, int score) {
    }
    public int getStudentScore(String name) {
    }
}
```

import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class StudentScoreManagerTest {
    private StudentScoreManager manager;
    @BeforeEach
    public void setUp() {
        manager = new StudentScoreManager();
    }
    @Test
    public void testAddStudentScoreAndRetrieve() {
        manager.addStudentScore("张三", 90);
        assertEquals(90, manager.getStudentScore("张三"));
    }
    @Test
    public void testGetStudentScoreForNonexistentStudent() {
        assertEquals(-1, manager.getStudentScore("王五"));
    }
    @Test
    public void testUpdateStudentScore() {
        manager.addStudentScore("李四", 85);
        manager.addStudentScore("李四", 95);
        assertEquals(95, manager.getStudentScore("李四"));
    }
    @Test
    public void testAddMultipleStudentScores() {
        manager.addStudentScore("张三", 90);
        manager.addStudentScore("李四", 85);
        assertEquals(90, manager.getStudentScore("张三"));
        assertEquals(85, manager.getStudentScore("李四"));
    }
    @Test
    public void testNegativeScore() {
        manager.addStudentScore("赵六", -10);
        assertEquals(-10, manager.getStudentScore("赵六"));
    }
}


import java.util.HashMap;
public class SafeAddToMap {
    public static void safeAdd(HashMap<String, String> map, String key, String value) {
        try {
            map.put(key, value);
        } catch (Exception e) {
        }
    }
    public static void main(String[] args) {
        HashMap<String, String> myMap = new HashMap<>();
        safeAdd(myMap, "key1", "value1");
        safeAdd(myMap, "key2", "value2");
        System.out.println(myMap);
    }
}

Please write a Java method that safely adds key-value pairs to a `HashMap`. If any exceptions are encountered during the addition process, the method should catch and ignore them, ensuring the continuation of the program.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.HashMap;
public class SafeAddToMap {
    public static void safeAdd(HashMap<String, String> map, String key, String value) {
    }
}
```

import java.util.HashMap;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
public class SafeAddToMapTest {
    @Test
    public void testSafeAdd_NormalCase() {
        HashMap<String, String> map = new HashMap<>();
        SafeAddToMap.safeAdd(map, "testKey", "testValue");
        assertEquals("testValue", map.get("testKey"));
    }
    @Test
    public void testSafeAdd_NullKey() {
        HashMap<String, String> map = new HashMap<>();
        SafeAddToMap.safeAdd(map, null, "testValue");
        assertEquals("testValue", map.get(null));
    }
    @Test
    public void testSafeAdd_NullValue() {
        HashMap<String, String> map = new HashMap<>();
        SafeAddToMap.safeAdd(map, "testKey", null);
        assertNull(map.get("testKey"));
    }
    @Test
    public void testSafeAdd_NullMap() {
        HashMap<String, String> map = null;
        assertDoesNotThrow(() -> SafeAddToMap.safeAdd(map, "testKey", "testValue"));
    }
    @Test
    public void testSafeAdd_DuplicateKey() {
        HashMap<String, String> map = new HashMap<>();
        SafeAddToMap.safeAdd(map, "testKey", "initialValue");
        SafeAddToMap.safeAdd(map, "testKey", "newValue");
        assertEquals("newValue", map.get("testKey"));
    }
}


import java.util.ArrayList;
import java.util.List;
class UserInfoUpdater {
    static class UserInfo {
        String productName;
        int productQuantity;
        String shippedId;
        List<Integer> shippedInfo;
        int airNumber;
        List<Integer> airInformation;
        public UserInfo(String productName, int productQuantity, String shippedId, List<Integer> shippedInfo, int airNumber, List<Integer> airInformation) {
            this.productName = productName;
            this.productQuantity = productQuantity;
            this.shippedId = shippedId;
            this.shippedInfo = shippedInfo;
            this.airNumber = airNumber;
            this.airInformation = airInformation;
        }
    }
    public static List<UserInfo> updateUserInfo(List<UserInfo> users) {
        for (UserInfo user : users) {
            user.productName = user.productName.toUpperCase();
            user.productQuantity += 10;
            user.shippedId += "A";
            user.shippedInfo.set(user.shippedInfo.size() - 1, user.shippedInfo.get(user.shippedInfo.size() - 1) + 10);
            user.airNumber += 100;
            user.airInformation.set(user.airInformation.size() - 1, user.airInformation.get(user.airInformation.size() - 1) + 10);
        }
        return users;
    }
    public static void main(String[] args) {
        List<UserInfo> users = new ArrayList<>();
        users.add(new UserInfo("laptop", 20, "ID123", List.of(1, 2, 3), 500, List.of(100, 200, 300)));
        users.add(new UserInfo("tablet", 15, "ID456", List.of(4, 5, 6), 600, List.of(400, 500, 600)));
        users = updateUserInfo(users);
        for (UserInfo user : users) {
            System.out.println("ProductName: " + user.productName + ", ProductQuantity: " + user.productQuantity + ", ShippedId: " + user.shippedId + ", LastShippedInfo: " + user.shippedInfo.get(user.shippedInfo.size() - 1) + ", AirNumber: " + user.airNumber + ", LastAirInformation: " + user.airInformation.get(user.airInformation.size() - 1));
        }
    }
}

Please design a Java program to handle a series of update operations on user information. Given a set of user information, you need to update this information according to the following steps:

1. Convert all users' product names to uppercase.
2. Increase all users' product quantities by 10.
3. Append "A" to all users' shipment IDs.
4. Increase the last shipment info array value of all users by 10.
5. Increase all users' flight numbers by 100.
6. Increase the last flight info array value of all users by 10.
7. Extract the last flight info array value of all users.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.ArrayList;
import java.util.List;
class UserInfoUpdater {
    static class UserInfo {
        String productName;
        int productQuantity;
        String shippedId;
        List<Integer> shippedInfo;
        int airNumber;
        List<Integer> airInformation;
        public UserInfo(String productName, int productQuantity, String shippedId, List<Integer> shippedInfo, int airNumber, List<Integer> airInformation) {
        }
    }
    public static List<UserInfo> updateUserInfo(List<UserInfo> users) {
        return users;
    }
}
```

import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class UserInfoUpdaterTest {
    @Test
    void testUpdateUserInfoIncrementsProductQuantity() {
        List<UserInfoUpdater.UserInfo> users = new ArrayList<>();
        users.add(new UserInfoUpdater.UserInfo("laptop", 20, "ID123", Arrays.asList(1, 2, 3), 500, Arrays.asList(100, 200, 300)));
        List<UserInfoUpdater.UserInfo> updatedUsers = UserInfoUpdater.updateUserInfo(users);
        assertEquals(30, updatedUsers.get(0).productQuantity);
    }
    @Test
    void testUpdateUserInfoConvertsProductNameToUpperCase() {
        List<UserInfoUpdater.UserInfo> users = new ArrayList<>();
        users.add(new UserInfoUpdater.UserInfo("laptop", 20, "ID123", Arrays.asList(1, 2, 3), 500, Arrays.asList(100, 200, 300)));
        List<UserInfoUpdater.UserInfo> updatedUsers = UserInfoUpdater.updateUserInfo(users);
        assertEquals("LAPTOP", updatedUsers.get(0).productName);
    }
    @Test
    void testUpdateUserInfoAppendsToShippedId() {
        List<UserInfoUpdater.UserInfo> users = new ArrayList<>();
        users.add(new UserInfoUpdater.UserInfo("laptop", 20, "ID123", Arrays.asList(1, 2, 3), 500, Arrays.asList(100, 200, 300)));
        List<UserInfoUpdater.UserInfo> updatedUsers = UserInfoUpdater.updateUserInfo(users);
        assertEquals("ID123A", updatedUsers.get(0).shippedId);
    }
    @Test
    void testUpdateUserInfoIncrementsLastElementOfShippedInfo() {
        List<UserInfoUpdater.UserInfo> users = new ArrayList<>();
        users.add(new UserInfoUpdater.UserInfo("laptop", 20, "ID123", Arrays.asList(1, 2, 3), 500, Arrays.asList(100, 200, 300)));
        List<UserInfoUpdater.UserInfo> updatedUsers = UserInfoUpdater.updateUserInfo(users);
        assertEquals(13, updatedUsers.get(0).shippedInfo.get(2));
    }
    @Test
    void testUpdateUserInfoIncrementsAirNumber() {
        List<UserInfoUpdater.UserInfo> users = new ArrayList<>();
        users.add(new UserInfoUpdater.UserInfo("laptop", 20, "ID123", Arrays.asList(1, 2, 3), 500, Arrays.asList(100, 200, 300)));
        List<UserInfoUpdater.UserInfo> updatedUsers = UserInfoUpdater.updateUserInfo(users);
        assertEquals(600, updatedUsers.get(0).airNumber);
    }
    @Test
    void testUpdateUserInfoIncrementsLastElementOfAirInformation() {
        List<UserInfoUpdater.UserInfo> users = new ArrayList<>();
        users.add(new UserInfoUpdater.UserInfo("laptop", 20, "ID123", Arrays.asList(1, 2, 3), 500, Arrays.asList(100, 200, 300)));
        List<UserInfoUpdater.UserInfo> updatedUsers = UserInfoUpdater.updateUserInfo(users);
        assertEquals(310, updatedUsers.get(0).airInformation.get(2));
    }
}


import java.util.List;
import java.util.ArrayList;
class User {
    private String name;
    private List<Book> collection;
    public User(String name) {
        this.name = name;
        this.collection = new ArrayList<>();
    }
    public void addBookToCollection(Book book) {
        if (!collection.contains(book)) {
            collection.add(book);
        }
    }
    public List<Book> getCollection() {
        return collection;
    }
    public void setCollection(List<Book> collection) {
        this.collection = collection;
    }
}
class Book {
    private String title;
    public Book(String title) {
        this.title = title;
    }
    public String getTitle() {
        return title;
    }
}
class CollectionManager {
    public void deleteBookFromCollection(User user, Book book) {
        List<Book> collection = user.getCollection();
        if (collection.contains(book)) {
            collection.remove(book);
            user.setCollection(collection);
        }
    }
}
public class Main {
    public static void main(String[] args) {
        User user = new User("张三");
        Book book1 = new Book("Java编程思想");
        Book book2 = new Book("Effective Java");
        user.addBookToCollection(book1);
        user.addBookToCollection(book2);
        CollectionManager manager = new CollectionManager();
        manager.deleteBookFromCollection(user, book1);
        if (!user.getCollection().contains(book1) && user.getCollection().contains(book2)) {
            System.out.println("测试通过");
        } else {
            System.out.println("测试失败");
        }
    }
}

Assuming you are developing a book management system, which includes a feature that allows users to remove books from their collection list. Describe how you would implement this functionality. The functionality receives two parameters: one is a user object, and the other is the book object to be removed from the collection. You need to find the book from the user's collection list and remove it. If the book does not exist in the user's collection list, no action should be taken.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.List;
import java.util.ArrayList;
class User {
    private String name;
    private List<Book> collection;
    public User(String name) {
    }
    public void addBookToCollection(Book book) {
    }
    public List<Book> getCollection() {
        return null;
    }
    public void setCollection(List<Book> collection) {
    }
}
class Book {
    private String title;
    public Book(String title) {
    }
    public String getTitle() {
        return null;
    }
}
class CollectionManager {
    public void deleteBookFromCollection(User user, Book book) {
    }
}
```

import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.ArrayList;
class UserTest {
    private User user;
    private Book book1;
    private Book book2;
    @BeforeEach
    void setUp() {
        user = new User("张三");
        book1 = new Book("Java编程思想");
        book2 = new Book("Effective Java");
    }
    @Test
    void testAddBookToCollection() {
        user.addBookToCollection(book1);
        assertTrue(user.getCollection().contains(book1));
    }
    @Test
    void testGetCollection() {
        user.addBookToCollection(book1);
        user.addBookToCollection(book2);
        List<Book> collection = user.getCollection();
        assertEquals(2, collection.size());
        assertTrue(collection.contains(book1));
        assertTrue(collection.contains(book2));
    }
    @Test
    void testSetCollection() {
        List<Book> newCollection = new ArrayList<>();
        newCollection.add(book1);
        user.setCollection(newCollection);
        assertEquals(newCollection, user.getCollection());
    }
}
class CollectionManagerTest {
    private User user;
    private Book book1;
    private Book book2;
    private CollectionManager manager;
    @BeforeEach
    void setUp() {
        user = new User("张三");
        book1 = new Book("Java编程思想");
        book2 = new Book("Effective Java");
        manager = new CollectionManager();
        user.addBookToCollection(book1);
        user.addBookToCollection(book2);
    }
    @Test
    void testDeleteBookFromCollection() {
        manager.deleteBookFromCollection(user, book1);
        assertFalse(user.getCollection().contains(book1));
    }
    @Test
    void testDeleteBookFromCollectionNotInList() {
        Book book3 = new Book("Java核心技术卷I");
        manager.deleteBookFromCollection(user, book3);
        assertTrue(user.getCollection().contains(book1));
        assertTrue(user.getCollection().contains(book2));
    }
    @Test
    void testDeleteBookFromEmptyCollection() {
        User newUser = new User("李四");
        manager.deleteBookFromCollection(newUser, book1);
        assertTrue(newUser.getCollection().isEmpty());
    }
}


import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class CustomThreadPoolCreator {
    public ThreadPoolExecutor createCustomThreadPool(int corePoolSize, int maxPoolSize, int queueCapacity, String namePrefix) {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
            corePoolSize,
            maxPoolSize,
            60L, TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(queueCapacity),
            new CustomThreadFactory(namePrefix),
            new ThreadPoolExecutor.CallerRunsPolicy());
        return executor;
    }
    static class CustomThreadFactory implements java.util.concurrent.ThreadFactory {
        private final String namePrefix;
        private int threadId = 1;
        public CustomThreadFactory(String namePrefix) {
            this.namePrefix = namePrefix;
        }
        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r, namePrefix + "-thread-" + threadId++);
            return t;
        }
    }
    public static void main(String[] args) {
        CustomThreadPoolCreator creator = new CustomThreadPoolCreator();
        ThreadPoolExecutor executor = creator.createCustomThreadPool(2, 4, 10, "TestPool");
        executor.execute(() -> System.out.println(Thread.currentThread().getName() + " is running"));
        executor.shutdown();
    }
}

Please design a Java method to create a custom thread pool. This thread pool should be able to dynamically set its core thread count, maximum thread count, queue capacity, and thread name prefix based on incoming parameters. Additionally, when the thread pool reaches its maximum capacity, there should be a strategy to handle new tasks.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class CustomThreadPoolCreator {
    public ThreadPoolExecutor createCustomThreadPool(int corePoolSize, int maxPoolSize, int queueCapacity, String namePrefix) {
    }
    static class CustomThreadFactory implements java.util.concurrent.ThreadFactory {
        private final String namePrefix;
        private int threadId = 1;
        public CustomThreadFactory(String namePrefix) {
        }
        @Override
        public Thread newThread(Runnable r) {
        }
    }
}
```

import org.junit.Before;
import org.junit.Test;
import java.util.concurrent.ThreadPoolExecutor;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class CustomThreadPoolCreatorTest {
    private CustomThreadPoolCreator creator;
    @Before
    public void setUp() {
        creator = new CustomThreadPoolCreator();
    }
    @Test
    public void testCreateCustomThreadPool_CorePoolSize() {
        ThreadPoolExecutor executor = creator.createCustomThreadPool(2, 4, 10, "TestPool");
        assertEquals(2, executor.getCorePoolSize());
    }
    @Test
    public void testCreateCustomThreadPool_MaxPoolSize() {
        ThreadPoolExecutor executor = creator.createCustomThreadPool(2, 4, 10, "TestPool");
        assertEquals(4, executor.getMaximumPoolSize());
    }
    @Test
    public void testCreateCustomThreadPool_QueueCapacity() {
        ThreadPoolExecutor executor = creator.createCustomThreadPool(2, 4, 10, "TestPool");
        assertEquals(10, executor.getQueue().remainingCapacity());
    }
    @Test
    public void testCreateCustomThreadPool_NamePrefix() {
        ThreadPoolExecutor executor = creator.createCustomThreadPool(2, 4, 10, "TestPool");
        executor.execute(() -> {
            String threadName = Thread.currentThread().getName();
            assertEquals(true, threadName.startsWith("TestPool-thread-"));
        });
    }
    @Test
    public void testCreateCustomThreadPool_NotNullExecutor() {
        ThreadPoolExecutor executor = creator.createCustomThreadPool(2, 4, 10, "TestPool");
        assertNotNull(executor);
    }
}