Appearance
question:**Problem Statement**: You are tasked with managing configuration settings for a macOS application. These configurations need to be stored in a property list (plist) file and read back when needed. The configuration includes various data types such as strings, lists, integers, floats, booleans, dictionaries, and datetime objects. Write a Python function `manage_configurations(action, config=None, filepath=None)` that performs the following operations based on the `action` parameter: 1. **"save"**: Saves the given configuration dictionary `config` to a plist file specified by `filepath`. 2. **"load"**: Loads and returns the configuration from the plist file specified by `filepath`. **Function Signature**: ```python import plistlib from datetime import datetime from typing import Union, Dict, Any def manage_configurations(action: str, config: Union[Dict[str, Any], None] = None, filepath: Union[str, None] = None) -> Union[Dict[str, Any], None]: pass ``` **Parameters**: - `action` (str): A string that can be either "save" or "load". - `config` (dict): A dictionary containing configuration settings (only needed for "save" action). - `filepath` (str): Path to the plist file (needed for both actions). **Returns**: - For "load" action, return the configuration dictionary loaded from the plist file. - For "save" action, return `None`. **Constraints**: - If `action` is "save", `config` and `filepath` must be provided. - If `action` is "load", `filepath` must be provided. - The `config` dictionary can contain the following types of values: strings, integers, floats, booleans, lists, dictionaries (with string keys), bytes, bytearray, and datetime.datetime objects. - Handle file I/O errors gracefully. - Handle plist parsing and generation errors gracefully. **Example**: ```python # Example usage: config_to_save = { 'app_name': 'SampleApp', 'version': 1.0, 'features': ['feature1', 'feature2'], 'settings': { 'volume': 75, 'theme': 'dark' }, 'last_updated': datetime.now() } # Save configuration to file manage_configurations("save", config=config_to_save, filepath="config.plist") # Load configuration from file loaded_config = manage_configurations("load", filepath="config.plist") print(loaded_config) ``` Design your function to efficiently handle the saving and loading operations while ensuring proper error handling for different edge cases, such as missing parameters or invalid file formats.
answer:import plistlib from datetime import datetime from typing import Union, Dict, Any def manage_configurations(action: str, config: Union[Dict[str, Any], None] = None, filepath: Union[str, None] = None) -> Union[Dict[str, Any], None]: try: if action == "save": if config is None or filepath is None: raise ValueError("Both 'config' and 'filepath' must be provided for 'save' action.") with open(filepath, 'wb') as file: plistlib.dump(config, file) return None elif action == "load": if filepath is None: raise ValueError("'filepath' must be provided for 'load' action.") with open(filepath, 'rb') as file: return plistlib.load(file) else: raise ValueError("Invalid action. Expected 'save' or 'load'.") except (FileNotFoundError, PermissionError) as e: print(f"Error accessing file: {e}") return None except plistlib.InvalidFileException as e: print(f"Error parsing plist file: {e}") return None
question:# Seaborn Boxplot Coding Assessment You are given a dataset loaded from Seaborn's built-in datasets. Your task is to use this dataset to showcase your proficiency with the Seaborn library by implementing a function that generates a customized boxplot. **Requirements**: 1. Load the "titanic" dataset. 2. Create a horizontal boxplot for the "age" column. 3. Group the boxplot by the "class" column. 4. Add a hue based on the "sex" column. 5. Customize the boxplot so that: - The boxes have a notch. - Outliers are shown with a "+" marker. - The boxes have a semi-transparent blue face color (rgba(0, 0, 1, 0.5)). - The median line is red and has a linewidth of 2. 6. Use Matplotlib to add a vertical line at age = 40. **Input**: - None (The function does not take any input parameters). **Output**: - The function should display the generated boxplot using Matplotlib. **Function Signature**: ```python def customized_titanic_boxplot(): # Your implementation here ``` **Constraints**: - Ensure that the face color of the boxes is set correctly without affecting other elements. **Performance Requirements**: - The code should run efficiently without requiring excessive computations. # Example Calling the function `customized_titanic_boxplot()` should display the customized boxplot as specified. ```python customized_titanic_boxplot() ``` **Hints**: - Refer to Seaborn and Matplotlib documentation if needed. - Ensure your plot is appropriately labeled and aesthetically appealing. Good luck!
answer:import seaborn as sns import matplotlib.pyplot as plt def customized_titanic_boxplot(): # Load the Titanic dataset from seaborn titanic = sns.load_dataset('titanic') # Create a horizontal boxplot for the "age" column grouped by "class" and with hue based on "sex" boxplot = sns.boxplot( x='age', y='class', hue='sex', data=titanic, notch=True, showcaps=True, flierprops={"marker": "+"}, boxprops={"facecolor": (0, 0, 1, 0.5)}, medianprops={"color": "red", "linewidth": 2} ) # Add a vertical line at age = 40 using Matplotlib plt.axvline(x=40, color='black', linestyle='--') # Display the plot plt.show()
question:# Task You have been provided with a Python application tracking system that logs events and exceptions in a simplistic manner. Your task is to enhance this system utilizing functionalities from the `sys` module, particularly focusing on custom exception handling and profiling. # Requirements 1. **Custom Exception Handler**: Implement a custom exception handler that logs uncaught exceptions to a file named `error_log.txt`. The log should include: - The exception type. - The exception value. - The traceback. 2. **Profiling Function**: Implement a profiling function that logs the time duration of function calls of all the functions within your script to `profile_log.txt`. The log should include: - The function name. - The time taken for each function call. # Constraints - Use the `sys.excepthook` for exception handling. - Use the `sys.setprofile` for profiling function calls. - Your implementation should handle nested function calls gracefully. - Ensure that your profiling does not add significant overhead to the function execution times. # Input No direct input. The system should handle exceptions and profiling automatically when functions are executed. # Output - `error_log.txt` containing logged uncaught exceptions. - `profile_log.txt` containing profiling information of function calls. # Example A simple Python script using your enhanced system might look like: ```python import time def function_a(): time.sleep(1) function_b() def function_b(): time.sleep(2) raise ValueError("An example error") # This should log both profiling and uncaught exceptions if __name__ == "__main__": function_a() ``` The `error_log.txt` should contain information similar to: ``` Exception type: <class 'ValueError'> Exception value: An example error Traceback (most recent call last): File "script.py", line XX, in <module> function_a() File "script.py", line YY, in function_a function_b() File "script.py", line ZZ, in function_b raise ValueError("An example error") ValueError: An example error ``` The `profile_log.txt` should contain information similar to: ``` Function: function_a, Duration: 1.001234s Function: function_b, Duration: 2.002345s ``` # Implementation Please provide your implementation below: ```python import sys import time import traceback ERROR_LOG_FILE = 'error_log.txt' PROFILE_LOG_FILE = 'profile_log.txt' def custom_excepthook(exc_type, exc_value, exc_traceback): with open(ERROR_LOG_FILE, 'a') as log_file: log_file.write(f"Exception type: {exc_type}n") log_file.write(f"Exception value: {exc_value}n") log_file.write("".join(traceback.format_tb(exc_traceback))) log_file.write(f"{exc_value}nn") sys.excepthook = custom_excepthook def profile_func(frame, event, arg): if event == 'call': frame.f_locals['__start_time__'] = time.time() elif event == 'return': start_time = frame.f_locals.get('__start_time__', None) if start_time is not None: duration = time.time() - start_time with open(PROFILE_LOG_FILE, 'a') as log_file: log_file.write(f"Function: {frame.f_code.co_name}, Duration: {duration:.6f}sn") sys.setprofile(profile_func) # Example Functions to demonstrate the profiling and exception handling def function_a(): time.sleep(1) function_b() def function_b(): time.sleep(2) raise ValueError("An example error") if __name__ == "__main__": function_a() ```
answer:import sys import time import traceback ERROR_LOG_FILE = 'error_log.txt' PROFILE_LOG_FILE = 'profile_log.txt' def custom_excepthook(exc_type, exc_value, exc_traceback): with open(ERROR_LOG_FILE, 'a') as log_file: log_file.write(f"Exception type: {exc_type}n") log_file.write(f"Exception value: {exc_value}n") log_file.write("".join(traceback.format_tb(exc_traceback))) log_file.write(f"{exc_value}nn") sys.excepthook = custom_excepthook def profile_func(frame, event, arg): if event == 'call': frame.f_locals['__start_time__'] = time.time() elif event == 'return': start_time = frame.f_locals.get('__start_time__', None) if start_time is not None: duration = time.time() - start_time with open(PROFILE_LOG_FILE, 'a') as log_file: log_file.write(f"Function: {frame.f_code.co_name}, Duration: {duration:.6f}sn") sys.setprofile(profile_func) # Example Functions to demonstrate the profiling and exception handling def function_a(): time.sleep(1) function_b() def function_b(): time.sleep(2) raise ValueError("An example error") if __name__ == "__main__": function_a()
question:Objective Your task is to implement an asynchronous echo server using the `asynchat` module. The server should be able to handle multiple client connections, receiving messages and echoing them back to the sender. Requirements 1. Create a subclass of `asynchat.async_chat` called `EchoHandler` that handles the reception and echoing of messages. 2. Implement the `collect_incoming_data` and `found_terminator` methods to buffer incoming messages and detect when a complete message has been received. 3. Use the `set_terminator` method to set a newline character (`"n"`) as the message terminator. 4. The server should run indefinitely, accepting new client connections and handling their messages concurrently. Expected Input and Output - **Input**: Messages from clients sent to the server. - **Output**: Each message received by the server should be echoed back to the respective client. Constraints - The server should handle arbitrary lengths of messages. - The server should be able to handle multiple clients simultaneously. Performance Requirements - Ensure the server remains responsive and can manage multiple client connections efficiently. Additional Details - You may use the following standard Python modules: `socket`, `asyncore`, `asynchat`. - Write your code to handle any potential exceptions and ensure the server closes connections gracefully. Example Here is an example to help you get started: ```python import asynchat import asyncore import socket class EchoHandler(asynchat.async_chat): def __init__(self, sock): asynchat.async_chat.__init__(self, sock=sock) self.set_terminator(b'n') self.ibuffer = [] def collect_incoming_data(self, data): self.ibuffer.append(data) def found_terminator(self): message = b''.join(self.ibuffer).decode('utf-8') print(f'Received: {message}') self.push(message.encode('utf-8') + b'n') self.ibuffer = [] class EchoServer(asyncore.dispatcher): def __init__(self, host, port): asyncore.dispatcher.__init__(self) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.set_reuse_addr() self.bind((host, port)) self.listen(5) def handle_accept(self): pair = self.accept() if pair is not None: sock, addr = pair print(f'Incoming connection from {addr}') EchoHandler(sock) def main(): server = EchoServer('localhost', 8080) asyncore.loop() if __name__ == '__main__': main() ``` This implementation sets up a basic echo server. You will need to integrate the necessary methods and ensure the server handles clients as specified.
answer:import asynchat import asyncore import socket class EchoHandler(asynchat.async_chat): def __init__(self, sock): super().__init__(sock=sock) self.set_terminator(b'n') self.ibuffer = [] def collect_incoming_data(self, data): self.ibuffer.append(data) def found_terminator(self): # Combine all chunks of data received message = b''.join(self.ibuffer).decode('utf-8') print(f'Received: {message}') # Echo the message back to the client self.push(message.encode('utf-8') + b'n') # Reset buffer for the next message self.ibuffer = [] class EchoServer(asyncore.dispatcher): def __init__(self, host, port): super().__init__() self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.set_reuse_addr() self.bind((host, port)) self.listen(5) def handle_accept(self): # Accept the incoming connection pair = self.accept() if pair is not None: sock, addr = pair print(f'Incoming connection from {addr}') EchoHandler(sock) def main(): server = EchoServer('localhost', 8080) asyncore.loop() if __name__ == '__main__': main()