query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with implementing a function to convert a given string into title case, following specific rules for capitalization. Title case involves capitalizing the first letter of each word in a string, except for certain words known as "minor words." These minor words should remain in lowercase unless they are th...
```python def titlecase(s: str, minor_words: str = '') -> str: if not s: return '' minor_words = minor_words.lower().split() title_cased = [word.capitalize() if word.lower() not in minor_words or i == 0 else word.lower() for i, word in enumerate(s.split())] return ' '.join(title_cased) ``` The ...
magicoder
python
You are tasked with creating a Python function that processes a list of integers and returns the count of unique elements in the list. However, the function should raise a custom validation error if the input list contains any non-integer elements or is empty. You need to implement the function `count_unique_elements`...
```python class ValidationError(Exception): pass def count_unique_elements(input_list): if not all(isinstance(x, int) for x in input_list) or len(input_list) == 0: raise ValidationError("Invalid input: list must contain only integers and cannot be empty") return len(set(input_list)) ``` The `count...
magicoder
python
You are given a snippet of code that processes an image and calculates the average color intensity of certain pixels. Your task is to implement a function that takes an image and a threshold as input and returns the number of pixels that satisfy specific contrast conditions based on the given code snippet. You need to...
```python def calculate_contrast_pixels(img, threshold) -> int: contrast_pixels = 0 for i in range(len(img)): for j in range(len(img[0])): if j > 0: r1, g1, b1 = img[i, j-1] r2, g2, b2 = img[i, j] r3, g3, b3 = img[i, j+1] ave1 ...
magicoder
python
You are tasked with creating a Python function that fetches stock price data from the Twelve Data API and calculates the average closing price for a given stock symbol over a specified time period. You are provided with the following code snippet as a starting point: ```python api_url = f'https://api.twelvedata.com/ti...
```python import requests def calculate_average_closing_price(symbol, api_key): api_url = f'https://api.twelvedata.com/time_series?symbol={symbol}&interval=1day&outputsize=30&apikey={api_key}' response = requests.get(api_url) if response.status_code == 200: data = response.json() closi...
magicoder
python
You are tasked with implementing a validation function for a web application's backend. The function should take in a request object and validate specific fields based on predefined rules. If any fields fail validation, the function should return a JSON response containing information about the invalid fields and a cor...
```php function validateFields($request) { $errors = []; $tag = "your_specific_tag"; // Replace with the actual tag // Extract specific fields from the request object for validation $data = $request->only([ 'field1', 'field2', // Add other fields to validate ]); // Vali...
magicoder
php
You are tasked with creating a script to automate the building and pushing of Docker images for different Node.js versions. The script should read the version from a `package.json` file, validate it as a semantic version (semver), transpile TypeScript code using `tsc`, and then build and push Docker images for specific...
```bash #!/bin/bash # Read version from package.json version=$(read_json -k 'version' -f package.json) # Validate semver version semver "$version" # Transpile TypeScript code tsc # Define array of Node.js versions node_versions=( 13 ) # Iterate through Node.js versions for v in "${node_versions[@]}"; do echo "...
magicoder
shell
You are tasked with parsing and extracting information from a series of field descriptors in a protocol buffer message definition. Each field descriptor contains various attributes such as name, full name, index, number, type, default value, etc. Your goal is to write a program that can extract and organize this inform...
```python import re # Define a class to represent a field descriptor class FieldDescriptor: def __init__(self, name, full_name, index, number, type, default_value): self.name = name self.full_name = full_name self.index = index self.number = number self.type = type s...
magicoder
python
You are tasked with implementing a class method that updates an in-flight order with trade updates from a trade message REST API. The method should return a tuple containing the total quantity filled, total cost of the filled quantity, and the last state of the order. The class also has a property `is_cancelled` that r...
```python from typing import Dict, Any, Tuple from decimal import Decimal class InFlightOrder: def __init__(self, last_state: str): self.last_state = last_state self.total_quantity_filled = Decimal(0) self.total_cost = Decimal(0) @property def is_cancelled(self) -> bool: re...
magicoder
python
You are tasked with creating a Python program to analyze and visualize the medal count of different countries in a sports event. The given code snippet is a part of the program that generates a horizontal bar chart representing the number of winners from each country. Your task is to complete the program by implementin...
```python import pandas as pd import matplotlib.pyplot as plt # Read the CSV file into a DataFrame medal_data = pd.read_csv('medal_count.csv') # Sort the data based on the number of winners in ascending order pivot_sorted = medal_data.sort_values(by='Vincitori', ascending=True) # Create a horizontal bar chart pivot_...
magicoder
python
You are working on a Python testing framework and need to create a custom field class for validating and typecasting input values. Your task is to implement the `Field` class with the following requirements: - The `Field` class should have the following attributes: - `name`: a string representing the name of the fie...
```python import unittest from unittest.mock import Mock class Field: def __init__(self, name, default_value, annotation=None): self.name = name self.default_value = default_value self.annotation = annotation def validate(self, value): if value is None: value = self...
magicoder
python
You are tasked with creating a Python script that processes a series of PDDL problem files and solves them using the PyStrips library. PyStrips is a Python library for planning and solving problems specified in the Planning Domain Definition Language (PDDL). Your script should take as input a list of PDDL problem file...
```python import subprocess def solve_problems(domain_file, problem_files): for problem_file in problem_files: print(f">> Solving {problem_file} ...") subprocess.run(['python3', 'pystrips.py', 'solve', domain_file, problem_file]) print() # Example usage domain_file = 'pddl/robot/domain.pdd...
magicoder
python
You are tasked with implementing a Python function that processes a given input string to extract and manipulate specific data. The function should take a string as input and perform the following operations: 1. Remove any leading or trailing whitespace from the input string. 2. Create a StringIO object from the proce...
```python import tokenize import StringIO from django import template def process_input_string(input_str: str) -> CallNode: a = input_str.strip() buf = StringIO.StringIO(a) keys = list(tokenize.generate_tokens(buf.readline)) kwargs = {} args = [] if keys[0][0] == tokenize.NAME: kwargs[s...
magicoder
python
You are tasked with creating a PHP function that connects to a MySQL database, executes a search query, and returns the results. The function should handle potential errors and ensure the database connection is properly closed. You are given the following code snippet as a starting point: ```php function buscar($b) {...
```php function buscar($b) { $con = mysqli_connect('localhost','moises', 'pemex11'); if (!$con) { die('Could not connect: ' . mysqli_error()); } mysqli_select_db($con, 'SECOE'); $query = "SELECT * FROM your_table WHERE column_name = '" . mysqli_real_escape_string($con, $b) . "'"; ...
magicoder
php
You are given a user-item matrix in the form of a dataframe, where rows represent users and columns represent items. Each cell in the dataframe contains the user's rating for that item, or 0 if the user has not rated that item. Your task is to calculate the average rating given by each user and return the results in a ...
```python import pandas as pd def calculate_average_ratings(user_item_mat: pd.DataFrame) -> pd.DataFrame: # Calculate the average rating for each user avg_ratings = user_item_mat.apply(lambda row: row[row > 0].mean(), axis=1) # Create a new dataframe with user ids and average ratings avg_df = pd.D...
magicoder
python
You are tasked with creating a custom attribute validation system for a game server configuration settings class. The `NeutronGlobalSettings` class contains various properties that define the server's behavior, such as network addresses, ports, frame rate, maximum players, and serialization mode. Your goal is to implem...
```csharp using System; [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] public class AddressValidationAttribute : Attribute { public void Validate(string[] addresses) { if (addresses.Length > 5) { throw new ArgumentException("Addresses array cannot exceed 5 elemen...
magicoder
csharp
You are tasked with creating a function that takes in a configuration object for Prettier options and returns a formatted string representing the options in a specific format. The Prettier options object contains various settings for formatting TypeScript code. The function should format the options into a string with ...
```typescript interface Options { [key: string]: string | boolean; } function formatPrettierOptions(options: Options): string { const formattedOptions: string[] = []; Object.keys(options) .sort() .forEach((key) => { formattedOptions.push(`${key}: ${options[key]}`); }); return formattedOptions...
magicoder
typescript
You are tasked with implementing a function to determine if one string is a permutation of another. A permutation is a rearrangement of the characters in a string. For example, "abc" is a permutation of "bca" and "cab". Your task is to create a function `bool CheckPermutation(string s1, string s2)` that takes in two st...
```cpp #include <string> #include <algorithm> class Solution { public: bool CheckPermutation(std::string s1, std::string s2) { if (s1.length() != s2.length()) { return false; // If the lengths are different, they cannot be permutations } std::sort(s1.begin(), s1.end()); // So...
magicoder
cpp
You are tasked with implementing a class that represents a programming task. The class has several properties and methods that need to be defined. Your goal is to create a class that fulfills the given requirements. You need to implement a class `ProgrammingTask` with the following properties and methods: - `Descripti...
```csharp using System; using System.Collections.Generic; public class ProgrammingTask { public string Description { get; } = "Implement a class representing a programming task."; public string ExampleCommand { get; } = "dotnet run"; public string Task { get; } = "Create a class with specified properties a...
magicoder
csharp
You are tasked with implementing a function that processes a sequence of tokens and updates an incremental state based on the previous output tokens. The function takes two parameters: `prev_output_tokens`, a list of tokens representing the previous output, and `incremental_state`, an optional incremental state that ca...
```python def process_tokens(prev_output_tokens, incremental_state=None): if incremental_state is None: incremental_state = {} # Initialize incremental state to an empty dictionary for token in prev_output_tokens: # Process each token and update the incremental state if isinstance(toke...
magicoder
python
You are tasked with creating a Python program to establish a connection to an MQTT broker and subscribe to a unique topic. The provided code snippet includes a variable `KeepAliveBroker` set to 60 and a string variable `TopicoSubscribe` initialized with the value "PAHOMQTTRaspPi3". Additionally, there is a callback fun...
```python import paho.mqtt.client as mqtt KeepAliveBroker = 60 TopicoSubscribe = "PAHOMQTTRaspPi3" # Callback - connection to the broker established def on_connect(client, userdata, flags, rc): print("[STATUS] Connected to the Broker. Connection result: " + str(rc)) # Create an MQTT client instance client = mqtt...
magicoder
python
You are tasked with implementing a function to parse a Zambda configuration file and return a parsed configuration object. The Zambda configuration file contains various settings and parameters for a Zambda application. The file is stored on the file system, and the function takes the file path as an input parameter. Y...
```typescript import * as fs from 'fs'; interface ZambdaConfig { [key: string]: string | number | boolean; } export function parseZambdaConfig(configFilePath: string): ZambdaConfig { const config: ZambdaConfig = {}; try { const fileContent = fs.readFileSync(configFilePath, 'utf8'); const lines = fileCo...
magicoder
typescript
You are tasked with implementing a simple authentication system using Swift. Your goal is to create a class that encapsulates the functionality for establishing a connection and fetching an authentication token. The class should have a method to initialize the connection and another method to fetch the authentication t...
```swift import Foundation // Define the connection info type struct ConnectionInfo { let url: URL init?(url: URL) { guard url.absoluteString.hasPrefix("https://") else { return nil } self.url = url } } // Define the Authenticator class class Authenticator { func init(url: URL) -> Con...
magicoder
swift
You are tasked with implementing a genetic algorithm for optimizing a system that uses genes to represent knowledge states. Each gene is associated with a knowledge state and has specific methods for calculating distance, copying, and performing crossover with other genes. Your task is to implement the `crossover` meth...
```python def crossover(self, other: 'KnowledgeStateGene') -> Gene: # Perform crossover at a random point crossover_point = random.randint(1, len(self.key) - 1) # Create new keys for the offspring genes offspring1_key = self.key[:crossover_point] + other.key[crossover_point:] offspring2_key = o...
magicoder
python
You are tasked with creating a Solana program that manages a music streaming platform. The program will handle the creation and updating of tracks, including their metadata and ownership. The program will use Borsh serialization for data storage and Solana Program Library for program development. Your task is to imple...
```rust use borsh::{BorshDeserialize, BorshSerialize}; use solana_program::{ instruction::{AccountMeta, Instruction}, program_error::ProgramError, pubkey::Pubkey, sysvar, }; /// Instruction arguments #[repr(C)] #[derive(BorshSerialize, BorshDeserialize, Clone)] pub struct InstructionArgs { /// data...
magicoder
rust
You are tasked with implementing a Python function that converts a nested dictionary into a flattened dictionary and stores it in a Redis hash. The function should take two parameters: `redis_transfer`, which is a Redis client object, and `test_dict`, which is the nested dictionary to be flattened and stored in Redis. ...
```python def flatten_and_store_redis_hash(redis_transfer, test_dict, parent_key=''): for key, value in test_dict.items(): if isinstance(value, dict): flatten_and_store_redis_hash(redis_transfer, value, parent_key + key + '_') elif isinstance(value, list): for i, item in enum...
magicoder
python
You are tasked with implementing a class that manages a collection of data items for a BlackBerry platform. The class, `PlatformBlob`, is responsible for handling the retrieval of data items from a blob data source. The provided code snippet shows a method `nextDataItem()` within the `PlatformBlob` class, which is inte...
```cpp BlackBerry::Platform::WebBlobDataItem* PlatformBlob::nextDataItem() { if (!m_blobData || m_currentItem >= m_blobData->items().size()) return 0; // Return null pointer if blob data is invalid or current item index is out of range else return m_blobData->items()[m_currentItem++]; // Retur...
magicoder
cpp
You are tasked with creating a program that manages a simple linked list data structure. The linked list should support basic operations such as insertion, deletion, and traversal. To ensure the correctness of your implementation, you decide to use the Unity testing framework to create unit tests for your linked list f...
```c // list.h #ifndef LIST_H #define LIST_H typedef struct Node { int data; struct Node* next; } Node; void insertNode(Node** head, int value); void deleteNode(Node** head, int value); void printList(Node* head); #endif ``` ```c // list.c #include "list.h" #include <stdio.h> #include <stdlib.h> void inser...
magicoder
c
You are tasked with implementing a function to convert the endianness of a given data to a specified endianness. Endianness refers to the order in which bytes are stored in a multi-byte data type. There are two common types of endianness: big-endian and little-endian. In big-endian, the most significant byte is stored ...
```python def switch_endianness(data, new="<"): """ Convert the input `data` endianness to `new`. Args: data (bytes): A byte string representing the input data. new (str): A string representing the target endianness ("<" for little-endian, ">" for big-endian). Default is "<". Returns: byte...
magicoder
python
You are tasked with implementing a Python function that calculates the phase shift of a signal based on the given input data. The phase shift is defined as the fraction of the period by which a wave is shifted in relation to a reference wave. In this problem, you are provided with a code snippet that sets the x-axis la...
```python from typing import List def calculate_phase_shift(x_values: List[float], y_values: List[float]) -> float: max_y = max(y_values) min_y = min(y_values) amplitude = (max_y - min_y) / 2 half_amplitude = amplitude / 2 half_amplitude_index = y_values.index(max_y - half_amplitude) quarter_pe...
magicoder
python
You are tasked with creating a Python class that simulates a simple online ticket reservation system for a theater. The system should allow users to reserve tickets for various plays and manage those reservations. Your task is to implement the `TheaterReservation` class with the following functionalities: 1. Initializ...
```python class TheaterReservation: def __init__(self): self.reservations = [] def reserve_tickets(self, play_name, num_tickets): for play in self.reservations: if play['name'] == play_name: play['tickets'] += num_tickets break else: ...
magicoder
python
You are tasked with implementing a discount calculation system for an e-commerce platform. The system should apply a percentage-based discount to eligible items in a customer's shopping cart. The discount is determined by a set of conditions and a simple action. The conditions specify the criteria that items must meet ...
```php function calculateDiscountAmount($conditions, $simple_action, $discount_amount) { // Implementing the logic to calculate the total discount amount based on the conditions and simple action // Assume $cartItems is an array of items in the shopping cart $eligibleItems = []; // Array to store eligible ...
magicoder
php
You are tasked with creating a Python class that simulates a simple banking system. The class should have methods for depositing funds, withdrawing funds, and checking the balance. Additionally, the class should log all transactions to a file for auditing purposes. Your task is to implement the `BankAccount` class wit...
```python import logging from datetime import datetime class BankAccount: def __init__(self, initial_balance): self.balance = initial_balance logging.basicConfig(level=logging.DEBUG, filename="bank_transactions.log") def deposit(self, amount): self.balance += amount self._log_t...
magicoder
python
You are tasked with implementing a Python function that processes thermodynamic properties based on the given input types. The input types are represented by the constants defined in the code snippet below. Your task is to create a function that takes in the input type and returns the corresponding thermodynamic proper...
```python def get_thermo_property(input_type): thermo_properties = { 'PT_INPUTS': 'Pressure and Temperature', 'DmassT_INPUTS': 'Density and Temperature for mass-based properties', 'DmolarT_INPUTS': 'Density and Temperature for molar-based properties', 'HmolarT_INPUTS': 'Enthalpy and ...
magicoder
python
You are tasked with creating a Python class that manages the exporting of animation data from a 3D animation software. The class should handle the process of exporting animation data to a file in a specific format. Your task is to implement the `AnimationExporter` class with the following requirements: 1. The class sh...
```python class AnimationExporter: def __init__(self): self.__files = [] def export_animation(self, name, format): file_name = f"{name}.{format}" # Construct the file name based on the name and format self.__files.append(file_name) # Append the constructed file name to the __files lis...
magicoder
python
You are tasked with creating a Python function that simulates the addition of a new entry to the `/etc/fstab` file in a Linux system. The `/etc/fstab` file is used to control how disk partitions are mounted and accessed by the system. The code snippet provided demonstrates the addition of a new entry for the `/boot` pa...
```python def add_fstab_entry(target_dir: str, device: str, mount_point: str, fs_type: str, options: str, dump: int, pass_num: int) -> None: entry = f"{device} {mount_point} {fs_type} {options} {dump} {pass_num}\n" with open(f"{target_dir}/etc/fstab", "a") as fstab_file: fstab_file.write(entry) ``` The...
magicoder
python
You are tasked with implementing a retry mechanism for a polling function in JavaScript. The `poller` function is an asynchronous function that returns the current state of a resource. The `tester` function takes the state as an argument and returns a boolean value indicating whether the state is acceptable or not. If ...
```javascript const poller = async () => { // Implementation of the poller function }; const tester = (state) => { // Implementation of the tester function }; const retryPoller = async (maxAttempts) => { for (let attempt = 1; attempt <= maxAttempts; attempt++) { try { const state = await poller(); ...
magicoder
javascript
You are tasked with implementing a function that parses and extracts specific attributes from a given SVG icon definition. The SVG icon definition is represented as a code snippet in JSX format, and the function should extract the `fill`, `fillRule`, `clipRule`, and `d` attributes from the `<path>` element. Write a fu...
```javascript function extractSvgAttributes(svgIconDefinition) { const match = svgIconDefinition.match(/<path\s+(.*?)\/>/); if (match) { const attributesString = match[1]; const attributes = attributesString.split(/\s+/).reduce((result, attribute) => { const [key, value] = attribute.split('='); ...
magicoder
javascript
You are tasked with creating a Python function that efficiently copies the content of one file to another using a single line of code. The function should take two file paths as input and copy the content from the source file to the destination file. The function should handle files encoded in UTF-8 and UTF-16. Your t...
```python def copy_file_content(source_file: str, destination_file: str) -> None: open(destination_file, 'w', encoding='utf-16').write(open(source_file, encoding='utf-16').read()) if source_file.endswith('.txt') else open(destination_file, 'w', encoding='utf-8').write(open(source_file, encoding='utf-8').read()) ```...
magicoder
python
You are working on a version control system and need to implement a feature that retrieves the repository name and the author's username from a given code repository URL. The repository URL follows the format `<reponame><authorname>/<modulename>`. You need to write a function that takes the repository URL as input and ...
```python def parseRepositoryURL(repositoryURL): parts = repositoryURL.split('/') return parts[1], parts[0] # Test cases print(parseRepositoryURL("benrdavison/brd_mod")) # Output: ("brd_mod", "benrdavison") print(parseRepositoryURL("user123/projectA_module")) # Output: ("projectA_module", "user123") ```
magicoder
python
You are tasked with implementing a cable-driven robot simulation using Python. The robot consists of multiple cables, each with its own set of properties and behaviors. Your goal is to create a class that represents a cable-driven robot and its associated cables, and to implement methods for adding cables, setting prop...
```python from math import sin, cos class Cable: def __init__(self, name, length, stiffness): self.name = name self.length = length self.stiffness = stiffness self.applied_force = 0 def apply_force(self, force): self.applied_force = force class CableRobot: def __in...
magicoder
python
You are given a JSON object representing the coordinates of the top-left corner of a set of rectangles. Each rectangle is represented by a key-value pair in the JSON object, where the key is the name of the rectangle and the value is the coordinates of its top-left corner in the form of a tuple (x, y). The x and y coor...
```python from typing import Union, List def highest_top_left(json_obj: dict) -> Union[str, List[str]]: max_y = max(coord[1] for coord in json_obj.values()) highest_rectangles = [name for name, coord in json_obj.items() if coord[1] == max_y] if len(highest_rectangles) == 1: return highest_rectangle...
magicoder
python
You are tasked with implementing a function to store the state of a given test case using the provided code snippet as a reference. The function should create a new TestModel object with specific attributes and then store the state using the given task_id. Write a function `store_state_works(case, store)` that takes i...
```python from flows.statestore.tests.models import TestModel def store_state_works(case, store): test_model = TestModel.objects.create(fruit='apple', count=34) if store: task_id = '10293847565647382910abdcef1029384756' # Store the state using the task_id # Your implementation to s...
magicoder
python
You are tasked with creating a custom UIView subclass that represents a speech bubble with a label inside. The speech bubble should have customizable corner radius, border width, and border color. The label's text and font should also be customizable. Your task is to implement the custom UIView subclass with the follow...
```swift import UIKit class SpeechBubbleView: UIView { @IBInspectable var cornerRadius: CGFloat = 2 @IBInspectable var borderWidth: CGFloat = 1 @IBInspectable var borderColor: UIColor = UIColor.black @IBInspectable var bubbleBackgroundColor: UIColor = UIColor.white @IBInspectable var labelText: Str...
magicoder
swift
You are tasked with creating a Python function that generates a sparse schedule for a railway environment. The railway environment is represented by a `RailEnv` object, and the schedule should be generated based on a given speed ratio map. The speed ratio map is a dictionary that maps speed profiles to their correspond...
```python from typing import Dict, List class Schedule: def __init__(self, schedule_data: List[str]): self.schedule_data = schedule_data def generate_sparse_schedule(width: int, speed_ratio_map: Dict[str, float]) -> Schedule: # Your implementation here # Example implementation: if width < 0: ...
magicoder
python
You are tasked with implementing a function to manage bindings between log entries and their corresponding locations. The log entries are represented by the `Log_Entry` class, which has two methods for setting the name: `setName()` and `setNameByLocation()`. The `setName()` method takes precedence over `setNameByLocati...
```python class Log_Entry: def __init__(self): self.name = None self.location = None def setName(self, name): self.name = name def setNameByLocation(self, name, location): if self.name is None: self.name = name self.location = location class Binding...
magicoder
python
You are tasked with implementing a script parser for a game engine that supports machine learning (ML) mode. The game engine has a method `_parse_ml_scripts` which takes a list of input script names and checks whether these scripts exist. If all the input scripts exist, the method converts their names to absolute impor...
```python import os class GameMode: ML = "ML" class ExecutionCommandError(Exception): pass class GameEngine: def __init__(self, game_mode): self.game_mode = game_mode self.input_modules = [] def _parse_ml_scripts(self, input_scripts): existing_modules = [] for script ...
magicoder
python
You are tasked with creating a program to retrieve and display information from a database based on user input. The program should interact with a database using a custom `databaseexe` class, which provides methods for executing SQL queries and retrieving results. The provided code snippet is a part of a larger progra...
```csharp public class DatabaseHelper { private Databaseexe databaseexe; public DatabaseHelper(Databaseexe databaseexe) { this.databaseexe = databaseexe; } public (string yinshua, string zhanjiao, string dading) GetFixProData(string id) { string yinshuaQuery = "select yingshua ...
magicoder
csharp
You are tasked with implementing a lead-lag estimation algorithm for a given time series dataset. The lead-lag estimation involves computing the time delay between two related time series, which can be used to analyze the relationship and potential causality between them. In this problem, you will need to implement a f...
```python import numpy as np def lead_lag_estimation(ts1: np.ndarray, ts2: np.ndarray) -> int: cross_corr = np.correlate(ts1, ts2, mode='full') lead_lag = np.argmax(cross_corr) - (len(ts1) - 1) return lead_lag ``` The `lead_lag_estimation` function calculates the cross-correlation between the two input ti...
magicoder
python
You are tasked with creating a program to manage different types of borders for a photo editing application. The application supports various border types, each with its own set of parameters. Your task is to implement a class that can manage these borders and their parameters. You are given a snippet of code that con...
```java import java.util.HashMap; import java.util.Map; public class BorderManager { private Map<String, Map<String, String>> borderParameters; public BorderManager() { this.borderParameters = new HashMap<>(); } public void addBorderType(String borderType, Map<String, String> parameters) { ...
magicoder
java
You are working on a project that involves processing and saving images using the OpenCV library in Python. You have a NumPy array representing an image in RGB format, and you need to save it to a specified file path after converting it to the BGR color format. Write a Python function that takes the image array and the...
```python import cv2 import numpy as np def save_image_as_bgr(array: np.ndarray, path: str) -> None: bgr_image = cv2.cvtColor(array, cv2.COLOR_RGB2BGR) cv2.imwrite(path, bgr_image) ``` The `save_image_as_bgr` function first converts the input RGB image array to BGR format using `cv2.cvtColor` with the `cv2.CO...
magicoder
python
You are tasked with implementing a simplified version of the BERTopic algorithm, which is a topic modeling technique that leverages BERT embeddings for document clustering and topic extraction. In this simplified version, you will focus on the initial step of the algorithm, which involves creating document embeddings u...
```python import numpy as np from typing import List from transformers import BertModel, BertTokenizer import torch def generate_bert_embeddings(documents: List[str]) -> np.ndarray: # Load pre-trained BERT model and tokenizer model_name = 'bert-base-uncased' tokenizer = BertTokenizer.from_pretrained(model_...
magicoder
python
You are tasked with creating a script to automate the deployment of virtualized MySQL instances using the rumprun unikernel on a Xen hypervisor. The rumprun command line tool is used to configure and launch the unikernel instances. The snippet provided is an example of the rumprun command used to launch a MySQL unikern...
```python def generate_rumprun_command(instance_name, memory_size, network_interface, vif_name, mac_address): rumprun_command = f"rumprun xen -N {instance_name} -M {memory_size} -i -I {network_interface},vifname={vif_name},mac={mac_address}" print("Generated rumprun command:") print(rumprun_command) # Exam...
magicoder
python
You are tasked with implementing a Python function that constructs an alias for a special built-in method. The special built-in method in question is `AssertType.make_alias`, which is part of a module called `special_builtins`. The function `build_assert_type` takes a single argument `vm`, which represents a virtual ma...
```python def build_assert_type(vm): # Construct an alias for the AssertType.make_alias method alias = special_builtins.AssertType.make_alias("assert_type", vm, "pytype_extensions") return alias ``` The `build_assert_type` function simply calls the `AssertType.make_alias` method with the specified paramete...
magicoder
python
You are tasked with implementing a class that manages combo boxes and directories in a file management application. The class contains a method `updateComboBox` that updates the items in a given combo box based on the contents of a directory. Additionally, the class has a member variable `currentDir` that represents th...
```python class FileManagement: def __init__(self, path): self.fileComboBox = # initialize file combo box self.textComboBox = # initialize text combo box self.directoryComboBox = # initialize directory combo box self.currentDir = QDir(path) def updateComboBox(self, comboBox): ...
magicoder
python
You are tasked with creating a Python function that can load configuration files from a specified directory and then test the loading process using the `pytest` framework. The function `get_configs_paths` takes a directory path as input and returns a list of configuration file paths found within that directory. The `te...
```python import os import pytest CONFIGS_PATH = "/path/to/configs/directory" def get_configs_paths(directory_path: str): """ Returns a list of configuration file paths found within the specified directory. Args: directory_path (str): The path to the directory containing configuration files. Re...
magicoder
python
You are tasked with implementing a program that simulates a simple vending machine. The vending machine has a set of available items, each with a corresponding price. The program should allow users to select an item, insert coins, and then dispense the selected item if the user has inserted enough money. If the user ha...
```python from typing import Dict class VendingMachine: def __init__(self, items: Dict[str, float]): self.items = items self.selected_item = None self.total_inserted = 0 def select_item(self, item: str) -> str: if item in self.items: self.selected_item = item ...
magicoder
python
You are tasked with creating a PHP class that simulates a simple database connection using PDO (PHP Data Objects). Your class should include methods for establishing a connection to a database, setting attributes, and executing prepared statements. Your task is to implement the `Database` class with the following req...
```php class Database { private $connection; public function __construct($host, $dbName, $username, $password) { $dsn = "mysql:host=$host;dbname=$dbName"; $this->connection = new PDO($dsn, $username, $password); $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); } ...
magicoder
php
You are tasked with implementing a Python function that converts a given HTML unordered list (ul) into a LaTeX formatted enumerated list (enumerate). The function should take the HTML node representing the ul and a depth parameter as input and produce the corresponding LaTeX formatted enumerated list. The function shou...
```python def stream_ul_to_latex(latex_stream, node, depth): write_latex_stream(latex_stream, f"\\begin{{enumerate}}") for child_node in node.find_all("li"): stream_single_node(latex_stream, child_node, depth) write_latex_stream(latex_stream, f"\\end{{enumerate}}") # Return the next node ret...
magicoder
python
You are tasked with testing a TypeScript application that utilizes the Moq library for mocking. The application involves a configuration module, a drawer provider, and a drawer registration system. The code snippet provided is a part of the test setup for this application. Your task is to write a unit test using the M...
```typescript import { Mock, It, Times } from 'moq'; import { Config, DrawerProvider, RegisterDrawer } from './your-application'; describe('Config and Drawer Registration', () => { let configMock: Mock<Config>; let drawerProviderMock: Mock<DrawerProvider>; let registerDrawerMock: Mock<RegisterDrawer>; let iden...
magicoder
typescript
You are tasked with implementing a dependency injection framework for a Java application. The framework should support the `@Inject` annotation to automatically inject dependencies into classes. The `@Inject` annotation should be used to inject the `FlowContainer` dependency into the target class. Your task is to creat...
```java import java.lang.annotation.*; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) @interface Inject {} class FlowContainer { // Implementation of FlowContainer class } class DependencyInjector { private Map<Cl...
magicoder
java
You are tasked with implementing a simple tip calculator in Swift. Your task is to create a function that calculates the total bill amount including tip, based on the bill amount and the desired tip percentage. You are given a code snippet that includes a method to hide a tip label using a cross-dissolve animation in a...
```swift func calculateTotalBillWithTip(billAmount: Double, tipPercentage: Double) -> Double { let tipAmount = billAmount * (tipPercentage / 100.0) let totalBillAmount = billAmount + tipAmount return round(totalBillAmount * 100) / 100 } ``` The `calculateTotalBillWithTip` function takes in the `billAmount`...
magicoder
swift
You are given a snippet of HTML code representing a product display on an e-commerce website. The code contains an anchor tag `<a>` with a class "secondary_img" and an image tag `<img>` with a class "lazy". Additionally, there is a `<span>` tag with a class "label_sale" representing a discount label. Your task is to w...
```python from bs4 import BeautifulSoup def extractProductInfo(html): soup = BeautifulSoup(html, 'html.parser') product_url = soup.find('a', class_='secondary_img')['href'] image_url = soup.find('img', class_='lazy')['data-src'] discount_percentage = soup.find('span', class_='label_sale').get_text().st...
magicoder
python
You are given two arrays, A and B, each containing N integers. Your task is to find the length of the longest subsequence that appears in both arrays. A subsequence of an array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. You nee...
```python from typing import List def longestCommonSubsequence(A: List[int], B: List[int]) -> int: n = len(A) m = len(B) dp = [[0] * (m + 1) for _ in range(n + 1)] for i in range(1, n + 1): for j in range(1, m + 1): if A[i - 1] == B[j - 1]: dp[i][j] = dp[i - 1][j - ...
magicoder
python
You are tasked with creating a Python function that simulates a simple text-based adventure game. The game will involve the player making choices that lead to different outcomes. The function should take the player's input and return the result of their choices. The game will have a specific storyline and multiple deci...
```python def adventure_game(player_input: str) -> str: if player_input == "left": return "You chose to go left. You encounter a river. Do you want to swim across or find a bridge?" elif player_input == "right": return "You chose to go right. You encounter a cave. Do you want to enter the cave o...
magicoder
python
You are working on a system update script for an embedded device running a custom operating system called ArkOS. The script is responsible for checking the presence of a specific joystick input device and then downloading and executing the appropriate update script based on the device's availability. Additionally, the ...
```python import subprocess def performSystemUpdate(joystick_present: bool, location: str) -> None: log_file = "/path/to/log_file.log" # Replace with the actual log file path update_script = "/home/ark/ArkOSUpdate.sh" if joystick_present: update_script_url = f"{location}/Update-RG351MP.sh" el...
magicoder
python
You are given an array of image data represented as a 2D grid of pixels. Each pixel is represented by a value, where 0 represents a white pixel and 1 represents a black pixel. Your task is to write a function to find the longest contiguous sequence of white pixels in the image array. Write a function `longestWhitePixe...
```python from typing import List def longestWhitePixelSequence(image: List[List[int]]) -> int: max_length = 0 current_length = 0 for row in image: for pixel in row: if pixel == 0: # white pixel current_length += 1 max_length = max(max_length, current_l...
magicoder
python
You are tasked with implementing a custom logging system for a mobile application. The system should log events from different parts of the application, such as a collection view, and categorize them based on the scene where the event occurred. Your task is to create a Swift class that manages the logging functionalit...
```swift // Logger class for managing logging functionality class Logger { enum Scene: String { case collectionView case otherScene // Add more scenes as needed } func log(scene: Scene, message: String) { print("Logging event in \(scene.rawValue) scene: \(message)") ...
magicoder
swift
You are tasked with creating a unit test for a function that interacts with a database client and a context object. The function is expected to return a specific server error response and log a mock error to the console. Your goal is to write the test case using a popular testing framework like Jest. The function to b...
```javascript // Assuming the function to be tested is named 'performDatabaseOperation' // Import necessary modules and the function to be tested const { performDatabaseOperation } = require('./yourModule'); // Replace 'yourModule' with the actual module name // Mock objects const mockDbClient = {}; // Replace with a...
magicoder
javascript
You are tasked with implementing a generic parser for the 'Caravel' language. The 'Caravel' language is a simple, custom language used for defining routes and destinations in a navigation system. The language consists of commands and parameters that define the route and its properties. The parser needs to handle the f...
```python from typing import List, Tuple class CaravelParser: def __init__(self): self.routes = {} self.destinations = {} def parse_command(self, command: str) -> None: tokens = command.split() if tokens[0] == 'route': route_id = tokens[1] self.routes[ro...
magicoder
python
You are tasked with creating a Python function that retrieves the Lunch Money API key from the environment variables using the `dotenv` library and then makes a GET request to a specific endpoint using the `requests` library. Your function should handle potential errors and return the response from the API. Your funct...
```python import os import requests from dotenv import load_dotenv def get_lunchmoney_data(endpoint: str) -> dict: try: load_dotenv() # Load environment variables from .env file api_key = os.getenv('LUNCHMONEY_API_KEY') # Retrieve Lunch Money API key if api_key: headers = {'A...
magicoder
python
You are tasked with implementing a function that takes in a list of tuples, each containing two elements: a string representing a word and an integer representing its frequency. Your goal is to create a dictionary where the keys are the words and the values are the total frequencies of each word across all the tuples. ...
```python from typing import List, Tuple, Dict def calculate_word_frequencies(word_tuples: List[Tuple[str, int]]) -> Dict[str, int]: word_freq_dict = {} for word, freq in word_tuples: if word in word_freq_dict: word_freq_dict[word] += freq else: word_freq_dict[word] = fr...
magicoder
python
You are working on a bioinformatics project and need to write a function to manipulate protein sequences in a pandas DataFrame. The function `clean_sequence_length` takes a DataFrame `dataframe` containing protein sequence data and performs the following operations: 1. It identifies proteins whose sequence length exce...
```python import pandas as pd def clean_sequence_length(dataframe, max_seq_len=20): reverse_rows = [] for index, row in dataframe[dataframe.sequence.apply(len) > max_seq_len].iterrows(): reverse_rows.append([row.id + '_r', row.sequence[::-1], row.function]) reverse_rows = pd.DataFrame(reverse_rows...
magicoder
python
You are tasked with creating a custom permission class for a RESTful API using Python's Django Rest Framework. The custom permission class should allow access to safe methods (GET, HEAD, OPTIONS) for all users, but restrict access to admin users only for unsafe methods (POST, PUT, DELETE). Your task is to implement a ...
```python from rest_framework.permissions import BasePermission, SAFE_METHODS, IsAdminUser class CustomPermission(BasePermission): def has_permission(self, request, view): if request.method in SAFE_METHODS: return True # Allow safe methods for all users else: return request...
magicoder
python
You are tasked with implementing a class for handling multi-bitmap characters in a C64 VIC display emulator. The provided code snippet is the constructor for the `C64CharMulti` class, which inherits from the `C64Bitmap` class. The `C64CharMulti` constructor takes in a pointer to a `CViewC64VicDisplay` object, as well a...
```cpp #include <iostream> #include <cstring> class CViewC64VicDisplay { // Define CViewC64VicDisplay class as per requirements }; class C64Bitmap { protected: int width; int height; bool multiColor; public: C64Bitmap(int w, int h, bool multi) : width(w), height(h), multiColor(multi) { //...
magicoder
cpp
You are tasked with implementing a simple event listener system in Python. The system should allow objects to register as listeners for specific events and receive notifications when those events occur. You are provided with a partial implementation of the `EventDispatcher` class, which is responsible for dispatching ...
```python class Listener: def on_arrived(self, client: 'Client') -> None: raise NotImplementedError def on_scheduled(self, client: 'Client') -> None: raise NotImplementedError class Client: def __init__(self, name: str): self.name = name class EventDispatcher: def __init__(s...
magicoder
python
You are tasked with creating a role-playing game (RPG) character system. The provided code snippet is part of a battle system where different character classes (Knight, Wizard, Sniper, HolyKing) use their unique skills to attack an opponent and reduce their hit points (hp). Your task is to implement the classes for th...
```java // Character class for Knight class Knight { int qSkill(Character opponent) { // Implement Knight's unique skill calculation here // Example: return damage based on Knight's strength and opponent's defense return calculateDamageBasedOnStrengthAndDefense(); } } // Character class...
magicoder
java
You are tasked with implementing a Python class to solve a system of ordinary differential equations (ODEs) using the Radau IIA method. The Radau IIA method is a type of implicit Runge-Kutta method that is particularly suitable for stiff ODEs. Your task is to complete the implementation of the `RadauIIA5` class by fill...
```python import numpy as np from scipy.optimize import fsolve class RadauIIA5: def __init__(self, f, t0, y0, h): self.f = f self.t0 = t0 self.y0 = y0 self.h = h def solve(self, t_end): t = self.t0 y = self.y0 solution = [y] while t < t_end: ...
magicoder
python
You are tasked with implementing a password validation function that checks whether a given password meets certain criteria. The function should return true if the password meets all the specified requirements, and false otherwise. The password validation criteria are as follows: 1. The password must be at least 8 cha...
```python import re def validatePassword(password): # Check if the password length is at least 8 characters if len(password) < 8: return False # Check if the password contains at least one uppercase letter, one lowercase letter, one digit, and one special character if not re.search(r"[A-Z]...
magicoder
python
You are tasked with creating a Python function that simulates the behavior of a command-line tool for validating YANG data models. YANG is a data modeling language used to model configuration and state data manipulated by the Network Configuration Protocol (NETCONF), NETCONF Remote Procedure Call (RPC), and NETCONF Not...
```python import os def validate_yang_model(lint: bool, debug_level: int) -> str: bash_command = ['pyang'] pyang_param = '--lint' if lint else '--ietf' bash_command.append(pyang_param) bash_command.append('2>&1') if debug_level > 0: print('DEBUG: running command {}'.format(' '.join(bash_co...
magicoder
python
You are tasked with implementing a graph data structure and a related algorithm to traverse the graph. The graph is represented using the DOT language, a plain text graph description language. Each node in the graph represents a concept related to personal and world finance, and each directed edge represents a relation...
```python from collections import defaultdict class Graph: def __init__(self): self.graph = defaultdict(list) def add_edge(self, start, end): self.graph[start].append(end) def dfs_util(self, node, visited): visited.add(node) print(node, end=" ") for neighbor in se...
magicoder
python
You are tasked with creating a function that converts ground coordinates to image coordinates based on a given model. The ground coordinates are represented by a tuple of three values (longitude, latitude, altitude), and the image coordinates are represented by a tuple of three values (x, y, z). The model used for the ...
```python def ground_to_image(model, ground): # Call the groundToImage method of the model object to convert ground coordinates to image coordinates x, y, z = model.groundToImage(*ground) return x, y, z ``` The `ground_to_image` function takes in a model object and a ground coordinate tuple. It then calls t...
magicoder
python
You are tasked with creating a Rust program that involves struct serialization and macro usage. Your goal is to implement a macro that initializes a struct and then use the serde library to serialize the struct into a specific format. You are given a code snippet that defines a Rust struct `RenameAllRename` with two f...
```rust use serde::{Serialize, Deserialize}; use serde_json; #[serde(rename_all = "camelCase")] #[derive(Serialize, Deserialize)] struct RenameAllRename { pen_pineapple: String, #[serde(rename = "pen_pen")] apple_pen: String, } macro_rules! add { ($struct_name:ident {$($value:expr),+}) => { le...
magicoder
rust
You are tasked with creating a program to parse and extract information from HTML code. Specifically, you need to extract the text content within the anchor tag `<a>` and the corresponding href attribute value from the given HTML code snippet. The HTML code snippet is as follows: ```html <li> <a data-toggle="collaps...
```python from bs4 import BeautifulSoup html_code = ''' <li> <a data-toggle="collapse" href="#accordion-list-3" class="collapsed"><span>03</span> Membuka Peluang Kerjasama <i class="bx bx-chevron-down icon-show"></i><i class="bx bx-chevron-up icon-close"></i></a> </li> ''' # Parse the HTML code soup = BeautifulSoup...
magicoder
python
You are tasked with implementing a program to analyze a 1D Gaussian distribution and perform various operations on it. Write a Python function `gaussian_1D_profile` that takes in the following parameters: - `x_min`: The minimum value of the x-axis. - `x_max`: The maximum value of the x-axis. - `x_step`: The step size...
```python import numpy as np import matplotlib.pyplot as plt from scipy.integrate import simps def gaussian_1D_profile(x_min, x_max, x_step, center, sigma, amplitude): """Function to create a 1D Gaussian distribution. Parameters ---------- x_min : float The minimum value of the x-axis. ...
magicoder
python
You are tasked with creating a script to manage Google Cloud Platform (GCP) resources using the gcloud command-line tool. Your script should handle setting the GCP project, parsing command-line arguments, and providing usage information. Your script should have the following functionalities: 1. Set the GCP project usi...
```bash function set_parameters() { FORCE=false local OPTIND n f while getopts ":n:f:" o; do case "${o}" in n) cluster_name=${OPTARG} ;; f) case ${OPTARG} in true) FORCE=true ;; ...
magicoder
shell
You are working on a natural language processing (NLP) project and are tasked with implementing a custom component for spaCy, a popular NLP library in Python. The code snippet provided is a part of the setup process for integrating custom components into spaCy's processing pipeline. Your task is to create a custom spa...
```python # Import necessary libraries and classes import spacy from medspacy.target_matcher import TargetMatcher from medspacy.section_detection import Sectionizer # Initialize spaCy NLP pipeline nlp = spacy.load("en_core_web_sm") # Define the custom component for entity matching and section detection class CustomCo...
magicoder
python
You are tasked with creating a function that processes product prices based on certain criteria. The function should take an array of product details as input and return the calculated prices. Each product has a base price, and the function needs to apply different types of discounts based on the product category and a...
```php function calculateProductPrices($products) { $calculatedPrices = []; foreach ($products as $product) { $finalPrice = $product['base_price']; switch ($product['category']) { case 'electronics': $finalPrice *= (1 - 0.10); // Apply 10% discount bre...
magicoder
php
You are tasked with designing a module resolution system for a Rust application. The application consists of several modules, each containing various components. The provided code snippet represents the initial module structure and the re-exported components. Your task is to implement a function that resolves the actu...
```rust fn resolve_module_path(component_name: &str) -> String { if component_name == "ColorWidget" { return "color_widget::ColorWidget".to_string(); } else if component_name == "CameraPaintable" { return "gst_paintable::CameraPaintable".to_string(); } "Component not found".to_string() }...
magicoder
rust
You are tasked with implementing a simple hierarchical structure for a software application. The structure consists of nodes, each of which can have zero or more child nodes. Each node has a method `move` that takes a position as a parameter and moves the node to that position. When a node is moved, all of its child no...
```cpp #include <iostream> #include <vector> #include <algorithm> class Node { public: Node(std::vector<Node*> children, std::pair<int, int> position) : m_children(children), position(position) {} void move(std::pair<int, int> newPosition) { // Calculate the offset by which the node is being moved ...
magicoder
cpp
You are tasked with creating a PHP class that manages a collection of forms. Each form can have multiple fields, and the class should provide functionality to add, remove, and retrieve forms and their fields. Additionally, the class should be able to validate the forms and their fields based on certain criteria. Your ...
```php class FormManager { private $forms = []; public function addForm($formName) { $this->forms[$formName] = []; } public function removeForm($formName) { unset($this->forms[$formName]); } public function addField($formName, $fieldName, $fieldType) { if (...
magicoder
php
You are tasked with creating a Flask web application that hosts two distinct blueprints, each serving different functionalities. The provided code snippet initializes a Flask application and imports two blueprints, `container_blueprint` and `status_blueprint`. Your task is to complete the Flask application by registeri...
```python from flask import Flask from .blueprints.containers import blueprint as container_blueprint from .blueprints.status import blueprint as status_blueprint app = Flask(__name__) # Register the container_blueprint with a URL prefix of '/containers' app.register_blueprint(container_blueprint, url_prefix='/contai...
magicoder
python
You are tasked with implementing a generic system for managing data and information in a Rust application. The system consists of two main components: `SystemData` and `SystemInfo`. The `SystemData` holds the actual data, while the `SystemInfo` provides additional information about the system. Additionally, you need to...
```rust // Define the guard and guard borrow types struct Guard<'a> { data: SystemData<'a>, info: SystemInfo<'a>, } struct GuardBorrow<'a, 'b> { guard: &'a mut Guard<'b>, } // Implement the create_guard function fn create_guard<'a>( data: SystemData<'a>, info: SystemInfo<'a>, ) -> Guard<'a> { ...
magicoder
rust
You are given a list of class schedules, where each schedule is represented as a tuple of two integers: the start time and the end time of the class. Your task is to write a function that takes this list of class schedules and returns a subset of non-overlapping classes that can be attended, maximizing the number of cl...
```python from typing import List, Tuple def schedule(classes: List[Tuple[int, int]]) -> List[Tuple[int, int]]: if not classes: return [] classes.sort(key=lambda x: x[1]) # Sort classes based on end time possible_classes = [classes[0]] # Initialize with the first class for i in range(1, len...
magicoder
python
You are tasked with creating a user validation system for a web application. The provided code snippet is a part of the user validation process. The `UserValidator` class is responsible for validating user input and constructing a `User` object if the validation is successful. The `validateUserEdit` method is used to v...
```java // User class definition class User { private String username; private String email; public User(String username, String email) { this.username = username; this.email = email; } // Getters and setters for username and email properties public String getUsername() { ...
magicoder
java
You are tasked with creating a Python function that simulates the behavior of a web page dropdown menu using the Selenium library. The function should take in a list of options and perform a series of actions on the dropdown menu, including selecting options by index, visible text, and value. After these actions, the f...
```python from selenium import webdriver from selenium.webdriver.support.ui import Select from typing import List import time def simulate_dropdown_behavior(options: List[str]) -> List[str]: driver = webdriver.Firefox() driver.get("file:///C:/Users/Bhoomika%20Agarwal/Desktop/Exercise%20Files/CH03/03_02/html_co...
magicoder
python
You are tasked with implementing a Swift protocol and a class to model users and their twin counterparts. The `UserProtocol` defines the blueprint for a user, and the `User` class implements this protocol while also defining a type alias `TwinType` to represent the twin counterpart of a user. Your task is to complete ...
```swift public final class User: UserProtocol { typealias TwinType = User var username: String var age: Int init(username: String, age: Int) { self.username = username self.age = age } func greet() -> String { return "Hello, my name is \(username)." } ...
magicoder
swift
You are tasked with implementing a custom annotation processor for a Java application. The application uses the `@GuardedBy` annotation to indicate the lock that must be held when accessing a particular field or method. Your annotation processor needs to enforce this locking discipline by generating compile-time errors...
```java import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.Modifier; import javax.lan...
magicoder
java
You are working on a graphics processing library that supports various texture compression formats. Each compression format is represented by an enumeration case and has a specific bit per pixel (bpp) value. Your task is to implement a function that calculates the total memory size required to store a texture using a g...
```swift func calculateTextureSize(_ format: TextureCompressionFormat) -> Int { let textureWidth = 1024 let textureHeight = 1024 var bpp = 0 switch format { case .uncompressedR32G32B32A32: bpp = 128 case .compressedDxt1RGB, .compressedDxt1RGBA, .compressedEtc1RGB: bpp = 32 ...
magicoder
swift
You are tasked with implementing a C++ class that manages communication with a DDS (Data Distribution Service) middleware using the ROS 2 Lifecycle Messages package. The class should handle the creation of a DDS DomainParticipant, DataReader, and DataWriter, and provide methods for initializing, reading, and writing da...
```cpp #include "lifecycle_msgs/msg/rosidl_typesupport_opensplice_cpp__visibility_control.h" #include "rclcpp/rclcpp.hpp" #include "dds/domain/DomainParticipant.hpp" #include "dds/pub/DataWriter.hpp" #include "dds/sub/DataReader.hpp" class DDSMiddlewareManager { public: DDSMiddlewareManager() : participant_(nullpt...
magicoder
cpp
You are tasked with implementing a custom awaiter in C#. The awaiter should be able to handle both synchronous and asynchronous operations. Your task is to complete the implementation of the `ValueAwaiter<TResult>` struct, which represents an awaiter that can be created around an existing value or another async operati...
```csharp using System; using System.Runtime.InteropServices; using System.Threading.Tasks; public interface IAwaiter<TResult> { bool IsCompleted { get; } TResult GetResult(); void OnCompleted(Action continuation); } [StructLayout(LayoutKind.Auto)] public struct ValueAwaiter<TResult> : IAwaiter<TResult> {...
magicoder
csharp