query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are given a code snippet that is part of a function to deserialize a binary tree from a string representation. The function takes a string `data` as input and returns the root of the deserialized binary tree. The input string `data` represents the level order traversal of the binary tree, where each node's value is...
```python import collections class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def deserialize(data): deserial = data.split(',') root = TreeNode(-1) bfs = collections.deque([(root, "RIGHT")]) while len(deser...
magicoder
python
You are tasked with creating a SwiftUI view for managing user permissions within a messaging app. The view should display a list of user permissions for a specific channel and allow the user to toggle each permission on or off. The permissions include "Read Messages," "Send Messages," and "Manage Channel." Your task i...
```swift import SwiftUI struct UserPermissionView: View { let channelId: String @State private var readMessagesEnabled = false @State private var sendMessagesEnabled = false @State private var manageChannelEnabled = false var body: some View { List { Toggle("Read Messages", isO...
magicoder
swift
You are tasked with implementing a function that calculates the total number of valid paths from the top-left corner to the bottom-right corner of a grid. The grid is represented as a 2D array, where each cell contains a non-negative integer representing the cost to traverse that cell. You can only move right or down a...
```python def count_min_cost_paths(grid): m, n = len(grid), len(grid[0]) dp = [[0] * n for _ in range(m)] dp[0][0] = 1 for i in range(1, m): dp[i][0] = dp[i-1][0] if grid[i][0] == grid[i-1][0] else 0 for j in range(1, n): dp[0][j] = dp[0][j-1] if grid[0][j] == grid[0][j-1] else 0 ...
magicoder
python
You are tasked with simulating a customer service system using a discrete event simulation approach. The system consists of a single counter where customers arrive, spend some time discussing their needs, and then leave. Your goal is to implement a simulation that models the behavior of customers arriving at the counte...
```python import random class Customer: def __init__(self, name): self.name = name def set_checkpoint(self, checkpoint): print(f"{self.name} - {checkpoint}") def waits(self, time): return time def releases(self, resource): print(f"{self.name} - Released {resource}") ...
magicoder
python
You are given a string `str` containing only lowercase English letters. Your task is to write a function that takes the string as input and returns the count of each distinct character in the string, along with the character itself. The function should output the counts and characters in the order they appear in the st...
```python def countDistinctCharacters(s): char_count = {} for char in s: if char in char_count: char_count[char] += 1 else: char_count[char] = 1 result = [] for char, count in char_count.items(): result.append(f"{char} {count}") return result...
magicoder
python
You are tasked with implementing a simplified version of an online shopping system. The system consists of three classes: `Order`, `OrderItem`, and `Customer`. The `Order` class represents a customer's order and contains a unique `orderId`, a `couponCode` (if applicable), and a list of `OrderItem` objects. The `OrderIt...
```java import java.util.ArrayList; import java.util.List; public class Order { private Long orderId; private String couponCode; private List<OrderItem> orderItems; private Customer customer; public Order(Long orderId, String couponCode, Customer customer) { this.orderId = orderId; ...
magicoder
java
You are tasked with implementing a custom serialization and deserialization process for a specific data structure. The data structure in question is a vector of unsigned messages, and you are required to create a custom serializer and deserializer for this data structure using the Serde library in Rust. Your task is t...
```rust use serde::{Serialize, Deserialize, Serializer, Deserializer}; use serde::ser::SerializeSeq; use serde::de::{Deserialize, Deserializer, Visitor, SeqAccess, Error}; // Define the UnsignedMessage struct #[derive(Debug, Serialize, Deserialize)] struct UnsignedMessage { // Define the fields of UnsignedMessage ...
magicoder
rust
You are tasked with creating a class that manages the storage and broadcasting of parameters in a web application. The class should handle the saving of parameters and the broadcasting of a new parameter event to the application's listeners. You are provided with a code snippet that represents a method within a PHP cl...
```php class Parametro { public $id; public $name; public $value; public function __construct($data) { $this->name = $data['name']; $this->value = $data['value']; } public function save() { // Implementation to save the parameter to the storage // Example: $this...
magicoder
php
You are tasked with creating a Rust program to manage a connection pool for a MySQL database. The program should utilize the `mysql` and `r2d2` crates to establish a connection pool and execute a query on the database. Your task is to complete the `main` function by implementing the following steps: 1. Create a struct...
```rust extern crate mysql; extern crate r2d2; extern crate r2d2_mysql; use mysql::OptsBuilder; use r2d2_mysql::MysqlConnectionManager; use r2d2::Pool; struct DatabaseConfig { username: Option<String>, database: Option<String>, } impl DatabaseConfig { fn new(username: Option<String>, database: Option<Str...
magicoder
rust
You are tasked with creating a neural network model using PyTorch to classify images of handwritten digits from the MNIST dataset. The goal is to build a simple feedforward neural network and train it to achieve high accuracy in classifying the digits. The MNIST dataset consists of 28x28 pixel grayscale images of handw...
```python import torch import torch.nn as nn import torch.optim as optim import torchvision import torchvision.transforms as transforms from torch.utils.data import DataLoader from torchvision.datasets import MNIST from tests.utils import jitVsGlow # Define the neural network architecture class SimpleNN(nn.Module): ...
magicoder
python
You are tasked with creating a Python class that represents a media part in a database. The class should inherit from the `Model` class and define the necessary attributes to interact with a database using the `peewee` ORM. Your task is to complete the `MediaPart` class by adding the required attributes and methods to...
```python from peewee import Model, CharField, IntegerField, DateTimeField, PostgresqlDatabase # Define the database connection db = PostgresqlDatabase('your_database_name', user='your_username', password='your_password', host='your_host') class MediaPart(Model): name = CharField() type = CharField() size...
magicoder
python
You are tasked with creating a Python function that processes a given directory and returns a list of all the Python files present in that directory and its subdirectories. You should use the `os` module to navigate the file system and the `ntpath` module to handle file paths. Additionally, you need to import the `Coll...
```python import os import ntpath from src.models import CollabWebService as Ws def find_python_files(directory_path): python_files = [] for root, dirs, files in os.walk(directory_path): for file in files: if file.endswith(".py"): file_path = os.path.join(root, file) ...
magicoder
python
You are tasked with simulating a simplified event handling mechanism in a multi-threaded environment. The provided code snippet is a part of this simulation. The `assert!(event.0 != 0);` statement ensures that the event handle `event` is valid and not null. The `SetEvent(event).ok()?;` line sets the event object `eve...
```rust use winapi::um::winbase::{SetEvent, WaitForSingleObject}; use winapi::um::winnt::HANDLE; use winapi::um::winbase::WAIT_OBJECT_0; fn simulate_event_handling(event: HANDLE) -> bool { assert!(event.0 != 0); if let Ok(_) = unsafe { SetEvent(event) } { let result = unsafe { WaitForSingleObject(even...
magicoder
rust
You are tasked with implementing a function to parse a given license file and extract the license information from it. The license file is in the format of a comment block at the beginning of a source code file, similar to the provided code snippet. The license information is enclosed within the comment block and conta...
```python import re def parseLicense(source_code): match = re.search(r'/\*(.*?)\*/', source_code, re.DOTALL) if match: license_text = match.group(1) url_match = re.search(r'http[s]?:\/\/\S+', license_text) permissions_match = re.search(r'WITHOUT\s+WARRANTIES\s+OR\s+CONDITIONS\s+OF\s+ANY...
magicoder
python
You are tasked with creating a Python function that reads longitude and latitude coordinates from a Keyhole Markup Language (KML) file containing a single path. The function should utilize the `fastkml` library to parse the KML file and extract the coordinates. Write a function `kml2latlon(ifile)` that takes a single ...
```python def kml2latlon(ifile): """Read lon lat from kml file with single path""" from fastkml import kml, geometry with open(ifile, 'rt') as myfile: doc = myfile.read() k = kml.KML() k.from_string(doc) features = list(k.features()) placemarks = list(features[0].features()) co...
magicoder
python
You are tasked with creating a Python script to monitor the status of a Mosquitto MQTT broker and send an alert if the broker goes offline. Mosquitto is an open-source message broker that implements the MQTT protocol. The code snippet provided is a command to start the Mosquitto broker using a specific configuration fi...
```python import psutil import smtplib from email.message import EmailMessage import time def send_alert(): msg = EmailMessage() msg.set_content("The Mosquitto broker is offline!") msg['Subject'] = "Mosquitto Broker Alert" msg['From'] = "your_email@example.com" msg['To'] = "recipient_email@example....
magicoder
python
You are tasked with creating a Python program to manage a quiz application. The program should allow users to register and manage quizzes, questions, answers, labels, and submissions. Your task is to implement the necessary classes and methods to achieve this functionality. You need to create the following classes: 1....
```python class Quiz: def __init__(self, title, description): self.title = title self.description = description self.questions = [] def add_question(self, question): self.questions.append(question) class Question: def __init__(self, text): self.text = text s...
magicoder
python
You are tasked with implementing a Python function that constructs a specific geometric shape based on the given input. The function should be able to construct either a hollow square or a diamond based on the input parameters. The shape construction should be done using the asterisk (*) character. The function should ...
```python def construct_shape(shape_type, size): if shape_type == "hollow_square": if size < 3: return "Invalid input" else: shape = "" for i in range(size): if i == 0 or i == size - 1: shape += "*" * size + "\n" ...
magicoder
python
You are given a list of integers representing the scores of participants in a competition. The task is to determine the minimum number of participants who scored at least the k-th highest score. Write a function `min_participants_scored_kth_highest` that takes in the number of participants `n`, the value of `k`, and th...
```python from typing import List def min_participants_scored_kth_highest(n: int, k: int, v: List[int]) -> int: v = sorted(v, reverse=True) # Sort the scores in descending order kth_highest_score = v[k-1] # Get the k-th highest score count_kth_highest_or_more = k + v[k:].count(kth_highest_score) # Count...
magicoder
python
You are tasked with implementing a function that takes a list of file paths and returns the longest common prefix among them. The function should handle both absolute and relative paths, and should return an empty string if there is no common prefix. You are given the following code snippet as a starting point: ```py...
```python import os def find_longest_common_prefix(paths): if not paths: return "" # Normalize paths to handle both Unix and Windows style paths normalized_paths = [os.path.normpath(path) for path in paths] # Split paths into components path_components = [path.split(os.sep) for path in no...
magicoder
python
You are tasked with implementing a custom error handling mechanism for a Rust application. The provided code snippet showcases a macro for defining custom error types and their corresponding error messages. Your goal is to create a similar macro and use it to define custom error types for a hypothetical web server appl...
```rust macro_rules! CustomError { ($error:ident { $($field:ident : $field_type:ty),* } = $message:expr) => { pub struct $error { $(pub $field: $field_type),* } impl $error { pub fn new($($field: $field_type),*) -> Self { $error { ...
magicoder
rust
You are tasked with creating a function that retrieves item data for a specific user from a datasource and returns it in a specific format. The function uses asynchronous operations and middleware for handling API responses and errors. Write a function `getItemData` that takes two parameters: 1. `userId` (string) - th...
```javascript const getItemData = async (userId, authorizer) => { try { const res = await postItemDatasource.getByUserId(authorizer.principalId); console.log('res::', JSON.stringify(res)); return { items: res }; } catch (error) { // Handle error using middleware return apiGatewayHandleErrors(e...
magicoder
javascript
You are tasked with implementing a class that handles the export of image data to the EXR format, a high-dynamic-range (HDR) image file format. The EXR format supports various compression types, and your class should provide the flexibility to choose the compression method when exporting the image data. You are provid...
```typescript import { EXRImageExporter, ZIPS_COMPRESSION, ZIP_COMPRESSION, NO_COMPRESSION } from './EXRImageExporter'; class EXRImageExporter { constructor() { // Initialize necessary properties } exportImage(imageData: Uint8Array, compressionType: number, exportPath: string): void { if (compressionTyp...
magicoder
typescript
You are tasked with creating a program to manage a library's book inventory. The program should allow users to add new books, remove existing books, and display the current list of books. Each book will have a title, author, and unique identification number. Additionally, the program should be able to search for a book...
```python class Book: def __init__(self, title, author, book_id): self.title = title self.author = author self.id = book_id def __str__(self): return f"Book ID: {self.id}, Title: {self.title}, Author: {self.author}" class Library: def __init__(self): self.books = [...
magicoder
python
You are tasked with implementing a function to draw pixels to an SDL_Texture and then render the texture using SDL. The function should take a PSF (PC Screen Font) file, load it, draw the pixels to an SDL_Texture, and return the texture. Additionally, the function should handle scaling the texture as needed before rend...
```cpp #include "Font/LoadPSF.hpp" #include <SDL.h> #include <iostream> SDL_Texture* DrawPSF(const char* psfFilePath, SDL_Renderer* renderer, int scale) { // Load the PSF file PSFFont psfFont = LoadPSF(psfFilePath); // Calculate the dimensions of the font characters int charWidth = psfFont.header->wi...
magicoder
cpp
You are tasked with implementing a Java class that filters issues based on keywords. The class `IssueContainsKeywordsPredicate` takes a list of keywords and checks if an issue contains all the keywords in the list. Your task is to complete the implementation of the `IssueContainsKeywordsPredicate` class and write a met...
```java public class IssueContainsKeywordsPredicate { private List<String> keywords; public IssueContainsKeywordsPredicate(List<String> keywords) { this.keywords = keywords; } public boolean test(Issue issue) { for (String keyword : keywords) { if (!issue.getDescription().c...
magicoder
java
You are working on a satellite data processing system that processes files with specific naming conventions. Each file name contains information about the data it holds. The file name format is as follows: "MOD13Q1.AYYYYDDD.hHV.VVV.YYYYMMDDHHMMSS.hdf", where: - "MOD13Q1" is the product name. - "A" is a constant charact...
```python import re def parse_filename(filename: str) -> dict: pattern = r"MOD13Q1\.A(\d{4})(\d{3})\.h(\d{2})v(\d{2})\.(\d{3})\.(\d{13})\.hdf" match = re.match(pattern, filename) if match: return { "product_name": "MOD13Q1", "year": int(match.group(1)), "day_of_y...
magicoder
python
You are tasked with designing a system for managing tables in a database. The provided code snippet is a simplified representation of an asynchronous function in Rust, which adds a table to the database and triggers a compaction process. Your task is to create a function that simulates the behavior of the `add_table` f...
```rust use tokio::time::{sleep, Duration}; use tokio::task; struct TableDesc { // Structure representing the details of the table to be added } struct VersionDesc { // Structure representing the version description after adding the table } struct Database { // Structure representing the database } impl...
magicoder
rust
You are tasked with creating a Python program to detect and count the number of objects in a series of grayscale images using a pre-trained Haar cascade classifier. The program should load the cascade classifier from a file, iterate through a directory of sample images, and for each image, detect the objects using the ...
```python import cv2 import os # Load the cascade classifier from a file num_cascade = cv2.CascadeClassifier('haar_cascade/cascade.xml') # Initialize a counter to keep track of the total number of objects detected total_objects = 0 # Iterate through the sample images for image in os.listdir('samples'): # Read th...
magicoder
python
You are working on a project that involves interfacing with a C library from Rust. The C library provides functions for managing a client connection. You need to create a Rust wrapper around these C functions to manage the client connection in a safe and idiomatic way. You are given the following C code snippet that d...
```rust use std::ffi::CString; use std::ptr; #[repr(C)] struct CClient { // C Client struct definition } extern "C" { fn hedera_client_create(address: *const std::os::raw::c_char, out: *mut *mut CClient) -> std::os::raw::c_int; fn hedera_client_close(client: *mut CClient); } pub struct Client { c_cli...
magicoder
rust
You are tasked with creating a script to manage AWS IAM instance profiles and roles. Your script should include functions to create, delete, and manage instance profiles and roles. The script should interact with the AWS CLI to perform these operations. Your script should include the following functions: 1. `create_in...
```bash #!/bin/bash create_instance_profile_and_role() { local INSTANCE_PROFILE="$1" local ROLE_NAME="$2" local TRUST_POLICY="$3" local PERMISSIONS_POLICY="$4" echo "Creating instance profile $INSTANCE_PROFILE and role $ROLE_NAME ..." aws iam create-instance-profile --instance-profile-name "$I...
magicoder
shell
You are tasked with creating a program to analyze and manipulate fields within a Java class using reflection. Reflection is a powerful feature in Java that allows programs to inspect and modify classes, interfaces, fields, and methods at runtime. Your task is to implement a Java program that utilizes reflection to retr...
```java import java.lang.reflect.Field; import java.util.Arrays; public class FieldSpy { private String hobby; public static void main(String[] args) throws NoSuchFieldException { Field f1 = FieldSpy.class.getDeclaredField("hobby"); System.out.println("Type of field 'hobby': " + f1.getType().g...
magicoder
java
You are tasked with creating a priority management system for a task management application using NestJS and Mongoose. The system should allow users to define and manage different priority levels for their tasks. Your task is to implement the PriorityService class, which will be responsible for interacting with the da...
```typescript import { Injectable } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { Model } from 'mongoose'; import { PassportModule } from '@nestjs/passport'; import { Priority } from './priority.interface'; import { CreatePriorityDto } from './create-priority.dto'; @Injectable() expor...
magicoder
typescript
You are tasked with implementing a program to parse and process a JSON file containing information about different environment variants. Each variant is represented as a JSON object with the following structure: ```json { "env-variant": "No-op start", "score": 15177.10 } ``` The "env-variant" field represents...
```python import json def calculate_average_score(json_file): try: with open(json_file, 'r') as file: data = json.load(file) if not data: return 0 total_score = sum(variant["score"] for variant in data) average_score = total_score / len(data) ...
magicoder
python
You are tasked with implementing a function to find the nearest neighbor of a given image file within a set of reference images. The function should take the image file, a reference path containing the reference images, and a list of reference file names as input. The goal is to compare the given image with the referen...
```python import os from PIL import Image import numpy as np def calculate_distance(image1, image2): # Implement the distance metric calculation between two images # For example, you can use pixel-wise mean squared error or structural similarity index (SSIM) def find_nearest_neighbor(image, reference_path, re...
magicoder
python
You are working on a research project involving statistical simulations, and you need to create visualizations for the results. The code snippet provided includes calls to three functions: `make_power_figures`, `make_null_figures`, and `make_EW_figures`. These functions are responsible for generating different types of...
```python import os import matplotlib.pyplot as plt def make_power_figures(colors, results_dir): # Create power figures using the specified colors for i, color in enumerate(colors): # Generate power figure using color fig, ax = plt.subplots() ax.set_facecolor('lightgray') # Set backgro...
magicoder
python
You are tasked with creating a Python program that processes a text file containing a list of student names and their corresponding test scores. Each line in the file represents a student's name followed by their test score, separated by a comma. Your program needs to read this file, calculate the average test score fo...
```python # Open the input file specified by the file_path variable in read mode with open(file_path, "r") as f: lines = f.readlines() # Read all lines from the file # Create a dictionary to store student names and their test scores student_scores = {} # Process each line in the file for line in lines: data ...
magicoder
python
You are tasked with creating a script to automate the process of retrieving access tokens and material counts from the WeChat API. The provided code snippet is a part of this automation process. Your task is to complete the script by writing a Bash function that takes the WeChat app ID and app secret as input and retur...
```bash #!/bin/bash # Function to retrieve material count from WeChat API get_material_count() { app_id=$1 app_secret=$2 # Construct the URL to obtain the access token get_access_token="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${app_id}&secret=${app_secret}" # Use the cons...
magicoder
shell
You are tasked with creating a Python module that manages datasets for a machine learning project. The module should include classes for specific datasets and a backend for data processing. Your task is to design the module structure and ensure that it adheres to best practices for Python package organization. Your mo...
```python # backend.py class Backend: # Define the Backend class for data processing pass # dataset_ycb.py class YCB: # Define the YCB dataset class pass # dataset_generic.py class GenericDataset: # Define the GenericDataset class pass # __init__.py from .backend import Backend from .dataset_...
magicoder
python
You are tasked with analyzing and refactoring a set of Laravel routes to ensure proper resource nesting and route naming conventions. The given code snippet contains a set of routes defined in a Laravel application. Your goal is to identify any issues with the route definitions and refactor them to adhere to best pract...
Refactored routes adhering to the guidelines: ```php Route::resource('citas', 'CitasController'); Route::resource('citas.contactos', 'ContactosController')->shallow(); Route::get('citas/{cita}/contactos/add', ['uses' => 'CitasController@addContactos', 'as' => 'citas.contactos.add']); Route::patch('citas/{cita}/contacto...
magicoder
php
You are given a list `postorder` containing the postorder traversal of a binary tree. Your task is to construct the binary tree and return its root node. The postorder traversal of a binary tree follows the order: left, right, root. You need to implement the following function: ```python class TreeNode: def __ini...
```python class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def buildTree(postorder: List[int]) -> TreeNode: if not postorder: return None root_val = postorder.pop() root = TreeNode(root_val) # Find...
magicoder
python
You are tasked with implementing a function that simulates a basic stack data structure. The stack should support the following operations: push, pop, and peek. The push operation adds an element to the top of the stack, the pop operation removes the top element from the stack and returns it, and the peek operation ret...
```python class Stack: def __init__(self): self.stack = [] def push(self, x): self.stack.append(x) def pop(self): if self.stack: return self.stack.pop() return None def peek(self): if self.stack: return self.stack[-1] return None...
magicoder
python
You are tasked with implementing a builder pattern for a forecasting application. The provided code snippet is a part of the builder pattern implementation for configuring forecast parameters. Your task is to complete the implementation of the `ForecastBuilder` struct by adding methods to set the start date and end dat...
```rust pub struct ForecastBuilder { inner: ForecastParams, } impl ForecastBuilder { pub fn new() -> Self { ForecastBuilder { inner: ForecastParams::default(), } } pub fn set_start_date(mut self, input: Option<String>) -> Self { if let Some(start_date) = input { ...
magicoder
rust
You are tasked with creating a program that simulates a simple banking system. The program should be able to handle multiple accounts, allowing users to deposit, withdraw, and check their balance. Each account should have a unique account number and be associated with the account holder's name. The program should also ...
```python class Account: def __init__(self, account_number, account_holder, initial_balance): if initial_balance < 0: raise ValueError("Initial balance cannot be negative") self.account_number = account_number self.account_holder = account_holder self.balance = initial_ba...
magicoder
python
You are tasked with implementing a Time-Based One-Time Password (TOTP) generator in Rust. TOTP is a type of two-factor authentication that uses a time-based algorithm to generate a one-time password. The code snippet provided includes module declarations for `totp` and `hotp`, and re-exports the `HOTP` and `TOTP` struc...
```rust extern crate hmacsha1; extern crate base32; extern crate chrono; use hmacsha1::hmac_sha1; use base32; use chrono::prelude::*; const T0: i64 = 0; const T: i64 = 30; const DIGITS: usize = 6; pub struct TOTP { secret_key: Vec<u8>, time_step: i64, } impl TOTP { pub fn new(secret_key: &str, time_step...
magicoder
rust
You are tasked with creating a custom UIAlertController subclass in Swift. Your custom alert controller should have the following features: - It should have a designated initializer that takes a title, message, preferredStyle, action button title, cancel button title, and action procedures as parameters. - The action b...
```swift import UIKit class CustomAlertController: UIAlertController { private var actionProc: (() -> Void)? private var cancelProc: (() -> Void)? init(title: String?, message: String?, preferredStyle: UIAlertController.Style, actionButtonTitle: String, cancelButtonTitle: String, actionProc: @escaping () ...
magicoder
swift
You are tasked with implementing a function to generate a secure invoice key using the given input parameters. The function should take in a keychain mask, invoice transaction arguments, and a boolean flag indicating whether to use a test random number generator (RNG). The keychain mask is an optional reference to a se...
```rust fn generate_secure_invoice_key( keychain_mask: Option<&SecretKey>, args: &IssueInvoiceTxArgs, use_test_rng: bool, ) -> SecureInvoiceKey { if let Some(mask) = keychain_mask { derive_key_from_mask(mask) } else { if use_test_rng { generate_key_with_test_rng(args) ...
magicoder
rust
You are tasked with creating a unit test for a simple function that calculates the factorial of a given positive integer. The function should be tested using the XCTest framework in Swift. The code snippet provided is a part of a test case class and includes the tearDown method and a placeholder testExample method. Yo...
```swift func testExample() { // Test case 1: Factorial of 0 should be 1 XCTAssertEqual(factorial(0), 1, "Factorial of 0 should be 1") // Test case 2: Factorial of 1 should be 1 XCTAssertEqual(factorial(1), 1, "Factorial of 1 should be 1") // Test case 3: Factorial of 5 should be 120 X...
magicoder
swift
You are tasked with implementing a function that processes a linked list and returns the last node with a specific value. The linked list is represented by the following structure: ```c struct ListNode { int val; struct ListNode *next; }; ``` You need to implement the following function: ```c struct ListNode...
```c struct ListNode *findLastNodeWithValue(struct ListNode *head, int value) { struct ListNode *result = NULL; struct ListNode *current = head; while (current != NULL) { if (current->val == value) { result = current; } current = current->next; } return ...
magicoder
c
You are tasked with implementing a Python class that encodes data and writes it to the file system. The class should inherit from two existing classes and provide a specific functionality for writing content to a file system. Implement a Python class called `FileSystemContentEncoder` that inherits from `AmendmentNodeE...
```python class FileSystemContentEncoder(AmendmentNodeEncoder, FSWriteContent): def encode_and_write(self, data): encoded_data = self.encode(data) # Using AmendmentNodeEncoder's encode method with open(self.path, 'w') as file: file.write(encoded_data) # Writing encoded data to the file...
magicoder
python
You are tasked with creating a program that simulates the behavior of a simplified shell command execution. Your program should take a list of commands and their arguments, along with the current working directory, and execute the commands sequentially, updating the working directory as necessary. You are given the f...
```javascript function executeCommands(commands, initialDirectory) { let currentDirectory = initialDirectory; for (const { command, args } of commands) { if (command === 'tmp.copy') { const [source, destination] = args; // Implement logic to copy source to destination ...
magicoder
javascript
You are tasked with creating a Python script to automate the installation of required packages on a Linux system. Your script should read a list of packages from a file and execute the installation commands for each package using the `apt-get` package manager. Additionally, the script should handle potential errors tha...
```python import subprocess def install_packages_from_file(file_path: str) -> None: with open(file_path, 'r') as file: packages = file.read().splitlines() for package in packages: command = f'sudo apt-get install -y {package}' try: subprocess.run(command, shell=True, ch...
magicoder
python
You are tasked with implementing a token management system for a web application. The system should handle the creation and deletion of personal access tokens for users. You are provided with a code snippet from a PHP class that demonstrates the deletion of a user's current access token and the generation of a response...
```php class TokenManager { private $user; private $token; public function __construct($user, $token) { $this->user = $user; $this->token = $token; } public function createAccessToken(): string { // Generate a new personal access token for the user and store it in t...
magicoder
php
You are tasked with implementing a Python function that performs a character rotation on a given string. The rotation involves shifting each character in the string by a specified number of positions in the alphabet. For instance, rotating 'abc' by 1 position results in 'bcd', and rotating 'abc' by -1 position results ...
```python def rotate(input_string: str, shift: int) -> str: result = "" for char in input_string: if char.isalpha(): base = ord('A') if char.isupper() else ord('a') result += chr((ord(char) - base + shift) % 26 + base) else: result += char return result ``...
magicoder
python
You are tasked with implementing a simplified version of a future-based asynchronous task executor in Rust. The provided code snippet is a part of the implementation of the `poll` method for a custom `Executor` struct. The `poll` method is used to drive the execution of asynchronous tasks to completion. Your task is t...
```rust use std::future::Future; use std::task::{Context, Poll}; use std::pin::Pin; enum BuilderState<F: Future<Output = ()>> { Building, Executing(Pin<Box<F>>), } struct Executor<F: Future<Output = ()>> { state: BuilderState<F>, } impl<F: Future<Output = ()>> Executor<F> { fn new() -> Self { ...
magicoder
rust
You are tasked with creating a Python function that processes video data to identify matching attributes between two video objects. The function should take in two arguments: `self` representing the first video object and `video` representing the second video object. The function should return a set of matching attribu...
```python def identify_matching_attributes(self, video): matches = set() # Check for matching imdb_id if self.imdb_id and video.imdb_id and self.imdb_id == video.imdb_id: matches.add('imdb_id') # Process and compare name attribute using guessit and guess_matches processed_name = guessit(se...
magicoder
python
You are tasked with implementing a Swift data structure for managing user sessions within a travel app. The provided code snippet outlines the initialization of a session state object, which encapsulates various properties related to the user's interaction with the app. Your goal is to design and implement the `Session...
```swift struct SessionState { var map: MapState var trip: Trip? var selectedOrderId: Order.ID? var places: PlacesSummary? var placesPresentation: PlacesPresentation var selectedPlace: Place? var addPlace: AddPlace? var history: History? var tab: TabSelection var publishableKey: ...
magicoder
swift
You are tasked with creating a custom button component for a web application using React and styled-components. The button component should have the ability to adjust its opacity based on a `disabled` prop and display text with specific styling. Your task is to implement the `Button` and `ButtonText` styled-components...
```jsx import React from 'react'; import styled from 'styled-components'; const Button = styled.button` opacity: ${({ disabled }) => (disabled ? 0.5 : 1)}; /* Add additional styling for the button component if needed */ `; const Text = styled.span` font-size: ${({ theme }) => theme.metrics.largeSize}px; color...
magicoder
jsx
You are tasked with implementing a priority queue using a custom class called `CustomPriorityQueue`. The `CustomPriorityQueue` class should support the following operations: 1. `put(item, priority)`: Add an item to the queue with a specified priority. 2. `get()`: Remove and return the item with the highest priority. 3....
```python # CustomPriorityQueue class implementation using min-heap data structure class CustomPriorityQueue: def __init__(self): self.queue = [] def put(self, item, priority): self.queue.append((item, priority)) self._sift_up(len(self.queue) - 1) def get(self): if not self...
magicoder
python
You are tasked with implementing a file upload handler class in PHP. The class should support multiple drivers for handling file uploads, such as local storage, cloud storage, or custom handlers. Your goal is to complete the implementation of the `UploadHandler` class by adding the necessary methods to support differen...
```php class UploadHandler { // ... other methods and properties /** * Call a custom upload handler. * * @param string|null $driver * @return mixed */ public function handler($driver = null) { return $this->driver($driver); } /** * Handle file uploads to ...
magicoder
php
You are tasked with implementing a Python class that simulates a simple banking system. The class should allow for the creation of multiple bank accounts, as well as the ability to deposit and withdraw funds from these accounts. Your task is to create a `BankAccount` class with the following specifications: - The clas...
```python class BankAccount: def __init__(self, account_holder, initial_balance=0): self.account_holder = account_holder self.balance = initial_balance def deposit(self, amount): self.balance += amount def withdraw(self, amount): if self.balance >= amount: self....
magicoder
python
You are tasked with implementing a custom enumerable type in C#. Your custom enumerable type should mimic the behavior of the built-in `IEnumerable` interface and provide the ability to iterate over a collection of elements. Your task is to create a class that satisfies the requirements of the `IEnumerable` interface a...
```csharp using System; using System.Collections; public class CustomEnumerable : IEnumerable { private int[] elements; public CustomEnumerable(int[] elements) { this.elements = elements; } public IEnumerator GetEnumerator() { return new CustomEnumerator(elements); } } pu...
magicoder
csharp
You are tasked with implementing a Python class method that calculates the node weights for initializing the use of the Personalized PageRank algorithm. The Personalized PageRank algorithm is a variant of the classic PageRank algorithm, but it allows for personalized preferences to influence the ranking of nodes in a g...
```python import typing class PageRankCalculator: def __init__(self, lemma_data: typing.Dict[int, str]): self.lemma_data = lemma_data def get_node_weights(self) -> typing.Optional[typing.Dict[Lemma, float]]: """ Get the *node weights* for initializing the use of the [*Personali...
magicoder
python
You are tasked with implementing a neural network layer using the given code snippet as a reference. The code snippet represents the `forward` method of a neural network class, which takes an input tensor `x` and passes it through a series of layers, including convolutional and fully connected layers. Your task is to e...
```python import torch import torch.nn as nn class CustomNeuralNetwork(nn.Module): def __init__(self): super(CustomNeuralNetwork, self).__init__() self.conv1 = nn.Conv2d(in_channels=3, out_channels=16, kernel_size=3, stride=1, padding=1) self.conv2 = nn.Conv2d(in_channels=16, out_channels=3...
magicoder
python
You are tasked with implementing a function to calculate ratios for the overview or aggregated results for a middle view. The function, `get_ratios`, takes several parameters: `id1`, `id2`, `direction`, `ops`, `bins`, `bins_col`, and `jsonit`. It also calls two other functions, `create_hashname` and `get_diff_cache`, a...
```python import timeit # Function to calculate ratios for the overview or aggregated results for the middle view def get_ratios(id1, id2, direction, ops, bins=1, bins_col=1, jsonit=True): # Create a unique hashname based on input parameters hashname = create_hashname(id1, id2, bins, bins_col, direction, ops) ...
magicoder
python
You are tasked with implementing a function that counts the number of occurrences of a specific substring within a given string. The function should be case-insensitive and should consider overlapping occurrences of the substring. For example, in the string "in_residence", the substring "res" occurs twice (at index 3 a...
```python def count_true(string: str, substring: str) -> int: count = 0 string = string.lower() substring = substring.lower() start = 0 while start < len(string): index = string.find(substring, start) if index != -1: count += 1 start = index + 1 else: ...
magicoder
python
You are tasked with creating a program that processes GitHub repository data and performs specific operations based on the information provided. The program will read input from a file containing lines of data in the following format: ``` <reponame>rishabmenon/PyNimbus<filename>PyNimbus/nhcoutlooks.py<gh_stars>0 #!/usr...
```python def process_github_data(input_file): with open(input_file, 'r') as file: lines = file.readlines() total_stars = 0 max_stars = 0 max_stars_repo = "" max_filename_length = 0 max_filename = "" for line in lines: repo_name = line.split('<reponame>')[1].split('<filenam...
magicoder
python
You are tasked with implementing a function that processes HTTP requests for a project management system. The function should handle different types of requests and their corresponding actions. The requests are related to retrieving project documents with specific routing parameters. Your task is to design a function t...
```csharp using System; using System.Threading.Tasks; public class ProjectDocumentHandler { public async Task<object> HandleProjectDocumentRequest(string urlId, string escaped, RequestType requestType) { switch (requestType) { case RequestType.FluentSync: return Flue...
magicoder
csharp
You are tasked with implementing a hierarchical tree structure using Python. The tree will be used to represent a hierarchy of nodes, with each node potentially having child nodes. Your task is to create a class that can build and manage this hierarchical tree structure. You are provided with a code snippet that inclu...
```python class TreeNode: def __init__(self, value): self.value = value self.children = [] class TreeBuilder: def __init__(self): self.root = None def createTree(self): self.root = TreeNode("Root") def buildTree(self): # 1. Start with defining lowest hierarchy,...
magicoder
python
You are tasked with implementing a function that processes a given SVG (Scalable Vector Graphics) file and extracts information about the rectangles defined within it. Each rectangle is represented by a `<rect>` tag in the SVG file, and its attributes specify the position and dimensions of the rectangle. Write a funct...
```python import xml.etree.ElementTree as ET def extractRectangles(svg): root = ET.fromstring(svg) rectangles = [] for rect in root.findall('.//rect'): x = float(rect.get('x', 0)) y = float(rect.get('y', 0)) width = float(rect.get('width')) height = float(rect.get('height'))...
magicoder
python
You are working on a data analysis tool that processes metrics from various services. The tool has a method `_get_minimal_resolution` that calculates the minimal resolution of the metrics for different services. The minimal resolution is the smallest time difference between consecutive data points in the metrics. The ...
```python import pandas as pd def get_minimal_resolution(other_service_metric_vals, associated_service_metric_vals): minimas_to_consider = [pd.Timedelta(1, unit='s')] for service_name, metric_vals in other_service_metric_vals.items(): if metric_vals.shape[0] > 0: other_service_metric_vals_...
magicoder
python
You are tasked with creating a Python package for a reservation exchange system. The package should include an app configuration that specifies the default app configuration for the reservation exchange system. The provided code snippet sets the `default_app_config` variable to `'respa_exchange.apps.RespaExchangeAppCon...
```python # respa_exchange/apps.py from django.apps import AppConfig class RespaExchangeAppConfig(AppConfig): name = 'respa_exchange' def ready(self): # Perform any necessary initialization tasks when the app is ready pass # Placeholder for initialization tasks ``` In the solution, the `Respa...
magicoder
python
You are tasked with implementing a user association manager for an external login system. The manager will handle the association of external user accounts with local user accounts in a forum application. The code snippet provided is the beginning of the `UserAssociationManager` class, which takes three dependencies: `...
```csharp using PopForums.Repositories; using PopForums.Services; namespace PopForums.ExternalLogin { public class UserAssociationManager : IUserAssociationManager { private readonly IExternalUserAssociationRepository _externalUserAssociationRepository; private readonly IUserRepository _userRep...
magicoder
csharp
You are working on a data analysis project and need to create a Python function to calculate the mean of a list of incorrect vector values and visualize the data using a scatter plot. The incorrect vector values represent errors in a machine learning model's predictions. Your task is to write a function that takes a li...
```python import matplotlib.pyplot as plt def plot_incorrect_vectors(incorrect_vector_list): incorrect_vector_mean = sum(incorrect_vector_list) / len(incorrect_vector_list) # plot plt.title('Incorrect Vector NO. of all data') plt.scatter(range(len(incorrect_vector_list)), incorrect_vector_list) pl...
magicoder
python
You are tasked with implementing a class that manages the preparation and execution of a series of tasks. The class, named `TaskManager`, has an internal method `_prepare` that is called to set up the necessary parameters before executing the tasks. The `_prepare` method checks if the parameters are already set and if ...
```python class TaskManager: def __init__(self): self._params = {} self._tasks = [] def _prepare(self): if not self._params: # Initialize parameters if not set self._params['initialized'] = True def add_task(self, task): self._tasks.append(task) ...
magicoder
python
You are tasked with implementing a simple moving average calculation for a given set of data points. The moving average is calculated by taking a window of a specified size and computing the average of the values within that window as it moves through the data. Your task is to write a function that takes a list of data...
```python def calculate_moving_average(data, window_size): if len(data) < window_size: raise ValueError("Window size cannot be larger than the data size") moving_averages = [] window_sum = sum(data[:window_size]) moving_averages.append(window_sum / window_size) for i in range(windo...
magicoder
python
You are tasked with creating a Rust function that simulates the behavior of the `fs::create_dir_all` function. The `fs::create_dir_all` function creates a new directory and all its parent components if they are missing. Your task is to implement a similar function called `custom_create_dir_all` that takes a path as an ...
```rust use std::fs; use std::io; fn custom_create_dir_all(path: &str) -> Result<(), std::io::Error> { fs::create_dir_all(path) } ``` The `custom_create_dir_all` function uses the `fs::create_dir_all` function from the standard library to create the directory and all its parent components if they do not exist. If ...
magicoder
rust
You are tasked with creating a form validation function for a user registration page. The function should validate various input fields based on the provided rules. The rules are defined in an object format, where each key represents a field name and its corresponding value is an array of validation rules. The validati...
```javascript function validateForm(formData, validationRules) { const validationResults = {}; for (const field in validationRules) { if (validationRules.hasOwnProperty(field)) { const rules = validationRules[field]; const value = formData[field]; for (const rule in rules) { if (rule...
magicoder
javascript
You are tasked with implementing a custom decoding process for a data structure using Swift. The given code snippet is part of a larger Swift program that involves decoding data from a container using a custom decoder. The `innerDecoder` is obtained from the `container` using the `superDecoder(forKey:)` method, and the...
```swift struct Inner: Decodable { let property1: String let property2: Int init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.property1 = try container.decode(String.self, forKey: .property1) self.property2 = try container.deco...
magicoder
swift
You are working on a data visualization application that displays density matrices for different quantum states. The code snippet provided is a part of the application's user interface, where users can select different parameters to filter and visualize the density matrices. Your task is to implement a function that ta...
```python import pandas as pd import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D def visualize_density_matrices(statei, statej, Jt, Tt): # Assuming nu.densities is a pandas DataFrame containing the density matrices filter_densities = nu.densities.loc[(nu.densities['state...
magicoder
python
You are tasked with implementing a Python function that simulates a simple game of rock-paper-scissors. The game should allow a user to input their choice (rock, paper, or scissors) and then randomly generate a computer's choice. The function should then determine the winner based on the standard rules of the game: roc...
```python import random def userFunction(): choices = ["rock", "paper", "scissors"] # Take user input for their choice user_choice = input("Enter your choice (rock, paper, or scissors): ").lower() # Validate user input while user_choice not in choices: user_choice = input("Invalid...
magicoder
python
You are tasked with implementing a Python function that extracts a list of classes and functions from a given module and its submodules. The module structure is organized as follows: - The main module is named `train`, and it contains a class `Trainer`. - The submodule `model` contains a function `get_model`. - The ma...
```python from typing import List import importlib import inspect def extract_functions_and_classes(module_name: str) -> List[str]: module = importlib.import_module(module_name) members = dir(module) result = [] for member in members: if inspect.isclass(getattr(module, member)) or inspect.isfun...
magicoder
python
You are tasked with implementing a thread-safe timestamp formatter using Java's `ThreadLocal` class. The provided code snippet initializes a `ThreadLocal` variable `TIMESTAMP_FORMAT` with a `SimpleDateFormat` object that formats timestamps in the "yyyy-MM-dd HH:mm:ss.SSS" format and uses the UTC time zone. Your task i...
```java import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.TimeZone; public class ThreadSafeTimestampFormatter { private static final ThreadLocal<SimpleDateFormat> TIMESTAMP_FORMAT = new ThreadLocal<SimpleDateFormat>() { @Override protected SimpleDat...
magicoder
java
You are given an array of integers `arr`. Your task is to write a function `lis_dp(arr)` to find the length of the longest increasing subsequence (LIS) in the given array using dynamic programming. A subsequence of an array is a sequence that can be derived from the array by deleting some or no elements without changi...
```python def lis_dp(arr): lis_arr = [1] * len(arr) # Initialize LIS array with 1 for each element for i in range(1, len(arr)): for j in range(0, i): if arr[i] > arr[j]: lis_arr[i] = max(lis_arr[i], lis_arr[j] + 1) # Update LIS value for current index return max(lis_ar...
magicoder
python
You are tasked with implementing a respawn system for a game character in Unity. The provided code snippet is a part of the respawn system script. The script includes a reference to the character's health, the initial position, and the respawn duration. The `Awake` method initializes the health component, and the `OnEn...
```csharp private void OnEnable() { if (health.CurrentHealth <= 0) { StartCoroutine(RespawnCoroutine()); } } private IEnumerator RespawnCoroutine() { float timer = 0f; while (timer < respawnDuration && health.CurrentHealth <= 0) { timer += Time.deltaTime; yield return nu...
magicoder
csharp
You are tasked with creating a program that parses and extracts information from a configuration file in a specific format. The configuration file contains XML-like tags and attributes, and your program needs to extract the values of certain attributes based on given criteria. Given the following code snippet as an ex...
```java import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.StringReader; public class ConfigParser { public static String extractFileName(String conf...
magicoder
java
You are tasked with creating a program that simulates a simple text-based adventure game. The game will involve a series of rooms, each with its own description and potential actions that the player can take. The player will navigate through the rooms by choosing different actions, and the game will respond accordingly...
```python class Room: def __init__(self, description, actions): self.description = description self.actions = actions def perform_action(self, action): if action in self.actions: return f"You {action} in the {self.description}." else: return "Invalid acti...
magicoder
python
You are tasked with creating a custom Angular directive that dynamically loads and displays content based on a specified condition. Your directive should be able to handle both eager and lazy loading of components and ensure that the content is displayed securely. Your directive should have the following requirements:...
```typescript import { Directive, Input, TemplateRef, ViewContainerRef, ElementRef, Renderer2, OnInit } from '@angular/core'; @Directive({ selector: '[appDynamicContent]' }) export class DynamicContentDirective implements OnInit { @Input() content: string; constructor( private templateRef: TemplateRef<any>,...
magicoder
typescript
You are tasked with implementing a class that manages command fields within a command scope. The class should provide methods for extracting specific command fields based on their group and name. You are given a partial code snippet for the implementation of this class, and your task is to complete the implementation o...
```csharp public interface ICommandField { // Define properties and methods for the command field interface } public interface ICommandScope { // Define properties and methods for the command scope interface } public class CommandManager { public virtual ICommandField ExtractCommandField(ICommandScope sco...
magicoder
csharp
You are tasked with implementing a retry mechanism for a network client that makes HTTP requests. The client should automatically retry the request if it times out, up to a specified maximum number of retries. You are given a partial implementation of the client and the test case for the retry functionality. The `CSRC...
```javascript class CSRClient { constructor() { this.maxRetries = 3; // Maximum number of retries } async execute(request) { let retries = 0; while (retries <= this.maxRetries) { try { const res = await this.makeRequest(request); return res; } catch (error) { if (e...
magicoder
javascript
You are tasked with implementing a function that processes a resolution and returns a specific value based on certain conditions. The resolution is represented using the following Rust code snippet: ```rust let (is_unit, unit) = if resolution.target().module(0).is_unit() { (true, Arc::clone(&resolution)) } else { ...
```rust use std::sync::Arc; // Define the FDModule, BiVec, and FiniteChainComplex types for demonstration purposes struct FDModule { // Implementation details } struct BiVec { // Implementation details } struct FiniteChainComplex { // Implementation details } struct Resolution { // Implementation de...
magicoder
rust
You are tasked with implementing a function that reverses the order of elements within a given sequence. The sequence is represented as an array of integers, and the reversal operation should be performed based on a specified axis. The axis indicates the dimension along which the reversal should occur. For example, if ...
```python def reverse_sequence(input_sequence, axis): if axis == 0: return input_sequence[::-1] elif axis == 1: return [seq[::-1] for seq in input_sequence] else: raise ValueError("Invalid axis value. Axis should be 0 or 1.") ``` The `reverse_sequence` function first checks the axis ...
magicoder
python
You are working on a deployment script for a Linux system and need to automate the setup of user-specific configurations for the XFCE desktop environment. Your task is to write a shell script that performs the following actions: 1. Copy the file "archlogo-full.svg" to the "/usr/share/icons/" directory using sudo privi...
```bash #!/bin/bash # Copy archlogo-full.svg to /usr/share/icons/ with sudo privileges sudo cp archlogo-full.svg /usr/share/icons/ # Create ~/.config/xfce4 directory if it doesn't exist and copy contents of specified directories mkdir -p ~/.config/xfce4 cp -rv xfconf panel terminal ~/.config/xfce4 # Check and rename...
magicoder
shell
You are tasked with implementing a validation function for Bank Identifier Code (BIC) and International Bank Account Number (IBAN) in Swift. The BIC is used to identify a specific financial institution, while the IBAN is used to identify an individual account involved in international transactions. Your task is to crea...
```swift import UIKit func viewControllerDidRequestBICIBANValidation(_ viewController: UIViewController) { let alert = UIAlertController(title: "BIC/IBAN Validation", message: "Please enter the BIC or IBAN for validation", preferredStyle: .alert) alert.addTextField { textField in textField.placeholder ...
magicoder
swift
You are tasked with creating a Python class that manages a file system. The class should provide methods for creating, deleting, and listing files and directories, as well as for navigating through the file system. Your task is to implement the `FileManager` class with the following methods: 1. `create_file(file_name:...
```python from typing import List import os class FileManager: def __init__(self): self.current_directory = os.getcwd() def create_file(self, file_name: str): file_path = os.path.join(self.current_directory, file_name) if not os.path.exists(file_path): open(file_path, 'a')....
magicoder
python
You are tasked with implementing a permission-checking function for a web application. The function should determine whether a user has the necessary permissions to access a specific feature based on their user type and role permissions. You are given a code snippet from a Laravel Blade template, which checks if a use...
```php function checkPermission($addon) { $userType = Auth::user()->user_type; $userPermissions = json_decode(Auth::user()->staff->role->permissions ?? "[]"); if ($addon != null) { if ($addon->activated) { if (in_array($userType, ['admin', 'customer', 'branch']) || in_array('1001', $use...
magicoder
php
You are tasked with creating a Python program that processes a list of integers and performs specific operations on them. Your program should define a function `process_numbers` that takes in a list of integers and performs the following operations: 1. Calculate the square of each number in the list. 2. Sum all the squ...
```python class EvenSumException(Exception): pass def process_numbers(numbers): try: squared_numbers = [num ** 2 for num in numbers] sum_of_squares = sum(squared_numbers) if sum_of_squares % 2 == 0: raise EvenSumException("Even sum found") else: return su...
magicoder
python
You are tasked with creating a program that can extract the name of a player mentioned in a given text. The text will contain a placeholder "<NAME>" which needs to be replaced with the actual name of the player. The player's name will be surrounded by a "#" symbol on both sides. Your program should be able to identify ...
```python import re def replace_name(text): match = re.search(r'#(.*?)#', text) if match: name = match.group(1) modified_text = text.replace('<NAME>', name) return modified_text else: return "No player name found in the text." # Example usage input_text = 'When reminded tha...
magicoder
python
You are tasked with creating a Python program that processes a list of metadata entries and extracts specific information from them. Each metadata entry is represented as a string in the format "key :: value". The keys and values are separated by the string " :: ". Your program should extract the unique programming la...
```python from typing import List, Dict def extract_languages_and_versions(metadata_entries: List[str]) -> Dict[str, str]: languages_and_versions = {} for entry in metadata_entries: if entry.startswith('Programming Language :: '): language_version = entry.split(' :: ')[-1] langu...
magicoder
python
You are tasked with creating a Django model for an IP address management (IPAM) system. The IPAM system needs to store information about hosts and their associated IP addresses. Each host can have multiple IP addresses, and each IP address can be associated with only one host. You need to define the Django model to rep...
```python from django.db import models class Host(models.Model): name = models.CharField(max_length=100) description = models.TextField() def __str__(self): return self.name class Inet(models.Model): address = models.CharField(max_length=15) # Assuming IPv4 addresses host = models.Foreig...
magicoder
python