query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are working as a DevOps engineer for a company that uses MongoDB for storing various types of data. As part of your responsibilities, you need to automate the process of importing JSON data into different MongoDB databases and collections. Your task is to write a Bash script that takes in two arguments: the databa...
```bash #!/bin/bash # Validate input arguments if [ "$#" -ne 3 ]; then echo "Usage: $0 <database> <collection> <json_file>" exit 1 fi # Assign input arguments to variables database=$1 collection=$2 json_file=$3 # Check if the JSON file exists if [ ! -f "$json_file" ]; then echo "Error: JSON file not found" e...
magicoder
shell
You are tasked with implementing a function that takes a list of strings as input and returns a new list containing only the unique strings, sorted in ascending order, while ignoring the leading colon (`:`) and considering case sensitivity. Write a function `get_unique_sorted_strings` that takes a list of strings as i...
```python from typing import List def get_unique_sorted_strings(input_list: List[str]) -> List[str]: unique_strings = set() for string in input_list: if string.startswith(':'): unique_strings.add(string[1:]) # Remove the leading colon and add to the set else: unique_str...
magicoder
python
You are tasked with implementing a custom module import mechanism in Python. Your goal is to create a module named `custom_import` that allows importing only specific modules listed in the `__all__` attribute of the module. The `__all__` attribute is a list of strings containing the names of the modules that can be imp...
```python # custom_import.py import importlib import sys class CustomImportLoader: def __init__(self, allowed_modules): self.allowed_modules = allowed_modules def load_module(self, fullname): if fullname not in self.allowed_modules: raise ImportError(f"Module '{fullname}' is not al...
magicoder
python
You are tasked with creating a web form for collecting feedback from users. The form should utilize the Django framework and Mezzanine CMS. Your task is to create a Django form that incorporates the Html5Mixin from Mezzanine and is linked to the Feedback model. Create a Django form class named "FeedbackForm" that inhe...
```python from mezzanine.core.forms import Html5Mixin from django import forms from .models import Feedback # Assuming the models.py file is in the same directory class FeedbackForm(Html5Mixin, forms.ModelForm): comment = forms.CharField(max_length=500) class Meta: model = Feedback fields = [...
magicoder
python
You are tasked with creating a custom UICollectionView cell for a seasonal image selection feature in a photo editing app. The provided code snippet includes the initial implementation of the `SeasonSelectCollectionViewCell` class, which is a subclass of `UICollectionViewCell`. The cell contains an `imageView` outlet t...
```swift import UIKit class SeasonSelectCollectionViewCell: UICollectionViewCell { @IBOutlet weak var imageView: UIImageView! var currentSeason: String = "" { didSet { setSeasonalImage() } } private func setSeasonalImage() { switch currentSeason { c...
magicoder
swift
You are tasked with implementing a class that manages asynchronous processes in a PHP application. The class should provide a method that accepts a callable and returns a Process object representing the asynchronous execution of the provided callable. You need to create a class called AsyncManager with a method __invo...
```php <?php class Process { private $pid; public function __construct(int $pid) { $this->pid = $pid; } public function getPid(): int { return $this->pid; } } class AsyncManager { public function __invoke(callable $callable): Process { $descriptorspec = [ ...
magicoder
php
You are tasked with creating a Python function that processes blog data and applies certain transformations based on specific conditions. The function will take in a blog object and perform the following operations: 1. If the `stickTop` flag is set to `True`, the function will retrieve the content of the blog from the...
```python from typing import Optional def process_blog(blog: Blog) -> None: if blog.stickTop: content = BlogDetail.objects.get(blogid=blog.id).content blog.shortcut = RenderMarkdown(content) category = Category.objects.get(id=blog.categoryid) blog.category = getCategoryStr(category) ``...
magicoder
python
You are tasked with creating a command-line utility that processes "tyler" files. These files contain specific instructions for a program to execute. The utility should accept a command-line argument specifying the tyler file to be processed. Your task is to implement the logic to extract the tyler file from the comman...
```rust use std::fs; use clap::{App, Arg}; fn main() { let matches = App::new("Tyler Utility") .arg( Arg::new("tyler_file") .about("The tyler file to run") .value_name("tyler_file") .required(true) .index(1), ) .get...
magicoder
rust
You are tasked with implementing a cell change monitoring system in a game environment. The system should register cell change handlers, trigger the appropriate callbacks when a cell change occurs, and set the discovered state of the game world. You are provided with a code snippet from the game's source code, which i...
```csharp using UnityEngine; public class CellChangeMonitor : MonoBehaviour { private static CellChangeMonitor _instance; public static CellChangeMonitor Instance { get { if (_instance == null) { _instance = new GameObject("CellChangeMonitor").AddCom...
magicoder
csharp
You are tasked with implementing a context manager in Python that initializes a configuration directory and composes a configuration using the `compose` function. The `initialize_config_dir` context manager takes a `config_dir` argument, which specifies the directory path for the configuration. Inside the context manag...
```python import os from pathlib import Path class initialize_config_dir: def __init__(self, config_dir): self.config_dir = config_dir def __enter__(self): # Initialize the configuration directory os.makedirs(self.config_dir, exist_ok=True) def __exit__(self, exc_type, exc_value, ...
magicoder
python
You are tasked with implementing a Python class method that calculates the similarity between two vectors. The method should take into account the dimension of the vectors and build weight vectors correctly. Your task is to complete the implementation of the `calculate_similarity` method in the given Python class. ```...
```python class VectorSimilarity: """ VectorSimilarity class for calculating similarity between two vectors. Attributes: input_dim : ``int`` The dimension of the vectors. This is ``y.size()[-1]`` - the length of the vector that will go into the similarity computation. We need this s...
magicoder
python
You are tasked with implementing a class for CUR matrix decomposition, a technique used for dimensionality reduction in machine learning. The class should include methods for selecting important features and performing the decomposition. The CUR decomposition involves selecting a subset of columns from the input matrix...
```python import numpy as np from scipy.linalg import svd class CURDecomposition: def __init__(self, n_to_select): self.n_to_select = n_to_select self.X = None self.C = None self.U = None self.R = None self.selected_idx_ = None def fit(self, X): self.X =...
magicoder
python
You are tasked with creating a Java program to manage a car database using JDBC (Java Database Connectivity). The program should establish a connection to a MySQL database, retrieve a list of cars, and insert each car into the database using prepared statements. You are given a `Car` class with the following structure...
```java import java.sql.*; import java.util.List; public class CarManager { public static void main(String[] args) throws SQLException { String url = "jdbc:mysql://172.17.0.2:3306/renault"; try (Connection connection = DriverManager.getConnection(url, "root", "1<PASSWORD>")) { List<Car>...
magicoder
java
You are tasked with implementing a function that takes an object as input and returns a new object with the keys and values reversed. If the input object has nested objects, the function should also reverse the keys and values of the nested objects. If the input object has arrays as values, the function should reverse ...
```javascript function reverseKeysAndValues(input) { if (typeof input !== 'object' || input === null) { return input; } if (Array.isArray(input)) { return input.map(reverseKeysAndValues); } const result = {}; for (const key in input) { if (typeof input[key] === 'object' && !Array.isArray(input...
magicoder
javascript
You are tasked with implementing a text formatting algorithm that wraps long words to fit within a specified line length. The algorithm should break long words at appropriate points and insert line breaks to ensure that no word exceeds the line length. The provided code snippet is a part of the algorithm that handles t...
```python import re def format_text(text: str, line_len: int) -> str: i = 0 formatted_text = "" word_sep = re.compile(r'\b') while i < len(text): match = word_sep.search(text, i) word = text[i:] sep = "" if match: word = text[i:match.start()] ...
magicoder
python
You are working on a data processing system that involves adding data to a configuration (cfg) using the `add_data` function. The `add_data` function takes three main arguments: the configuration (cfg), the data to be added, and a list specifying the data's location within the configuration. Additionally, the function ...
```python def add_data(cfg, data, location, edge_filter=None, args=None): if edge_filter is not None and args is not None: processed_data = edge_filter(data, args) cfg_location = cfg for loc in location: cfg_location = cfg_location[loc] cfg_location['processed_data'] = pr...
magicoder
python
You are tasked with implementing a custom operator in Swift that performs a specific operation on an array of strings. The operator should take an array of strings and concatenate them into a single string using a specified delimiter. Your task is to define the custom operator and implement the necessary functionality ...
```swift // Define the custom operator |> for concatenating array of strings with a delimiter infix operator |> : AdditionPrecedence // Extend the Array type to support the custom operator extension Array where Element == String { static func |> (left: [String], right: String) -> String { return left.joine...
magicoder
swift
You are tasked with creating a Python function that updates a configuration file by appending new lines to it. The function `update_config_user` takes two parameters: `lines`, a list of strings representing the new content to be added, and `separator`, a string representing the separator that will be used to distinguis...
```python import os def update_config_user(lines, separator=";; lines automatically added\n;; everything below this line will be scraped"): # Get the path to the config.user file path = os.path.join(get_user_config_path(), "config.user") # Read the existing content of the file, if it exists if os.path...
magicoder
python
You are tasked with implementing a Python class to manage a postal code database. The class should provide functionality to add, retrieve, and delete postal codes, as well as to check if a given postal code exists in the database. The postal codes will be stored in a dictionary where the keys are the postal codes and t...
```python class PostalCode: database = {} @classmethod def make_db(cls): cls.database = {} def add_postal_code(self, postal_code, city_name): self.database[postal_code] = city_name def get_city_name(self, postal_code): return self.database.get(postal_code, "Postal code not...
magicoder
python
You are tasked with creating a function that calculates the total staked amount in a staking pool for a given user address. The staking pool is part of a decentralized finance (DeFi) system and is managed through a smart contract. The staking pool contract has a function `stakedInCurrentEpoch` that returns information ...
```javascript async function calculateTotalStakedAmount(userAddress) { try { // Assume stakingFacet and ethers are properly initialized // Get staked information for the user address let staked = await stakingFacet.stakedInCurrentEpoch(userAddress); let stakedGhstMatic = staked[4]; // Get the po...
magicoder
javascript
You are tasked with implementing a simplified version of a method chaining system in Python. Method chaining is a technique that allows calling multiple methods on an object in a single statement, where each method returns the object itself. In this problem, you will create a class that supports method chaining for a s...
```python class MathOperations: def __init__(self): self.total = 0 def add(self, x): self.total += x return self def subtract(self, x): self.total -= x return self def multiply(self, x): self.total *= x return self def divide(self, x): ...
magicoder
python
You are tasked with implementing a data structure called an Observed-Remove Set (ORSet). An ORSet is a set that supports adding and removing elements, while also allowing querying for the presence of elements. The ORSet should be able to handle concurrent operations in a distributed system. Your task is to implement t...
```python class ORSet: def __init__(self): self.adds = {} self.removes = {} def add(self, element): if element not in self.adds: self.adds[element] = set() self.adds[element].add(self._generate_id()) def remove(self, element): if element in self.adds: ...
magicoder
python
You are tasked with implementing a simplified version of a tuple class in C++. A tuple is a fixed-size collection of heterogeneous values. Your task is to create a class `Tuple` that can store a fixed number of elements of different types and provide methods to access and modify these elements. Your `Tuple` class shou...
```cpp #include <iostream> #include <tuple> class Tuple { public: // Constructor that initializes the tuple with the given values template <typename... Args> Tuple(Args... args) : data(std::make_tuple(args...)) {} // Method to get the value at the specified index template <size_t Index> auto g...
magicoder
cpp
You are tasked with implementing a function that will parse a given HTML file and extract all the HTML tags present in the file. Your function should return a list of unique HTML tags found in the file, sorted in lexicographical order. Function Signature: `def extract_html_tags(html_file: str) -> List[str]:` Input: -...
```python from typing import List import re def extract_html_tags(html_file: str) -> List[str]: tags = re.findall(r'<\s*([a-zA-Z0-9]+)', html_file) # Using regular expression to find all HTML tags unique_tags = list(set(tags)) # Removing duplicates unique_tags.sort() # Sorting the tags in lexicographica...
magicoder
python
You are tasked with implementing a class that utilizes the `DetailedProgressListener` functional interface to track the progress of a file download. The `DetailedProgressListener` interface has a single method `notifyProgress` that takes in the progress percentage, a message, and additional data as parameters. Your tas...
```java import java.util.concurrent.TimeUnit; // Implementation of the DetailedProgressListener interface class SampleProgressListener implements DetailedProgressListener { @Override public boolean notifyProgress(double progress, String message, Object data) { System.out.println("Progress: " + progress...
magicoder
java
You are tasked with implementing a car management system for a barn. The system should allow the barn to accommodate different types of cars and provide functionality to control access to the barn for specific cars. Each car has a unique identifier and a size. The barn has a limited capacity and can only accommodate ca...
```python class Car: def __init__(self, car_id, size): self.id = car_id self.size = size def getId(self): return self.id def getSize(self): return self.size class Barn: def __init__(self, capacity): self.capacity = capacity self.cars = [] self....
magicoder
python
You are tasked with creating a Python function that visualizes a collection of automobile models stored in a directory. Each automobile model is represented by an image file in the directory. Your function should generate a visual representation of these automobile models and display them in a grid layout. You are pro...
```python import os import matplotlib.pyplot as plt import matplotlib.image as mpimg def visualize(directory_path, images_per_row=3): # Get the list of image files in the directory image_files = [f for f in os.listdir(directory_path) if os.path.isfile(os.path.join(directory_path, f)) and f.lower().endswith(('....
magicoder
python
You are tasked with creating a simple WPF application that displays data from a database using the MVVM (Model-View-ViewModel) design pattern. The application should have a MainWindow with a ViewModel (VM) that interacts with the database to retrieve and display the data. Your task is to implement the ViewModel class a...
```csharp // MainWindow_VM.cs public class MainWindow_VM : INotifyPropertyChanged { private Database database; private ObservableCollection<DataItem> dataItems; public MainWindow_VM(Database database) { this.database = database; dataItems = new ObservableCollection<DataItem>(); ...
magicoder
csharp
You are tasked with implementing a function to support log scale in a plotting library. The given code snippet is a part of a larger codebase for a plotting library. The snippet shows a conditional check for setting the y-axis label and enabling legend in a plot. The comment "# TODO add log scale support !!!" indicates...
```python class Plot: def __init__(self, layout_settings, settings, index): self.layout_settings = layout_settings self.settings = settings self.index = index def enable_log_scale_y(self, ax, labels=True): if not self.layout_settings.share_y or self.index[1] == 0: ax...
magicoder
python
You are tasked with creating a Python program to send emails using the `smtplib` library. Your program should take user input for the email sender's address, recipient's address, subject, and message body. Additionally, the program should handle potential errors that may occur during the email sending process. Your pr...
```python import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart def send_email(): try: # Prompt user for email details from_addr = input("Enter sender's email address: ") to_addr = input("Enter recipient's email address: ") subject = inpu...
magicoder
python
You are given an array `a` of length `n`. Your task is to find the maximum perimeter of a triangle that can be formed using three different elements from the array. The perimeter of a triangle is the sum of the lengths of its three sides. You need to implement the function `int maxTrianglePerimeter(int[] a)` where: - ...
```java public int maxTrianglePerimeter(int[] a) { int n = a.length; int maxPerimeter = 0; for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { for (int k = j + 1; k < n; ++k) { int side1 = a[i]; int side2 = a[j]; int side3 = a[...
magicoder
java
You are tasked with implementing a class that represents a numeric field with optional minimum and maximum value constraints. The class should validate whether a given value satisfies these constraints and also handle any other generic validation rules. You need to implement the `NumericField` class with the following...
```python class ValidationError(Exception): pass class Field: def __init__(self, default, required): self.default = default self.required = required def validate(self, value): if value is None and self.required: raise ValidationError("Value is required but was not provi...
magicoder
python
You are tasked with creating a Python module for managing remote servers using SSH protocol. The module should include classes for SSH protocol management, token resource management, and site management. Your task is to design and implement the required classes and their interactions. Your module should include the fo...
```python # AdlerManagerSSHProtocol.py class AdlerManagerSSHProtocol: def __init__(self, host, username, password): self.host = host self.username = username self.password = password def connect(self): # Implement SSH connection logic pass def execute_command(self, ...
magicoder
python
You are tasked with implementing a GraphQL subscription manager that handles update and delete operations for a specific document. The manager should be able to subscribe to these operations and execute the corresponding subscription documents when updates or deletions occur. You are given a code snippet that defines ...
```typescript import { DocumentNode } from 'graphql'; class SubscriptionManager { new: any | DocumentNode; updated: any | DocumentNode; deleted: any | DocumentNode; updateCallbacks: Function[]; deleteCallbacks: Function[]; constructor(newSubscription: any | DocumentNode, updatedSubscription: any | Documen...
magicoder
typescript
You are tasked with implementing a Python decorator that enforces a time limit on a function's execution and saves its output to a file. The decorator should take two optional arguments: `seconds` to specify the time limit in seconds and `suffix` to specify the file suffix for the saved output. The decorated function s...
```python import signal import time import os class TimeoutError(Exception): pass def timeout_handler(signum, frame): raise TimeoutError("Function execution timed out") def at_most(seconds): def decorator(func): def wrapper(*args, **kwargs): signal.signal(signal.SIGALRM, timeout_handl...
magicoder
python
You are tasked with creating a script to manage the installation and uninstallation of a custom component in a home automation system. The script should handle the following commands: `reinstall` to update the custom component, and `uninstall` to remove it. The script should connect to a remote server via SSH to perfo...
```bash #!/bin/bash # Check if the argument is provided if [ -z "$1" ]; then echo "Usage: $0 [reinstall|uninstall]" exit 1 fi # Store the argument in a variable ARG="$1" # Define the remote server address REMOTE_SERVER="ha" # Define the path for the custom component on the remote server REMOTE_PATH="config/cust...
magicoder
shell
You are tasked with implementing a custom data validation framework in Python. The framework should allow users to define validation rules for different types of data and raise specific exceptions when the validation fails. Your task is to create a new validator class called `NumberMaximumValueValidator` that checks i...
```python from datalidator.validators.base.Validator import Validator from datalidator.validators.exc.DataValidationFailedExc import DataValidationFailedExc class NumberMaximumValueValidator(Validator): def __init__(self, max_value): self.max_value = max_value def validate(self, data): if data...
magicoder
python
You are tasked with creating a program that simulates a simple shell environment. Your program should handle the execution of commands and the management of environment variables. Specifically, you need to implement the functionality to export and unset environment variables based on user input. Your program should su...
```python class ShellEnvironment: def __init__(self): self.environment = {} def export_variable(self, command): parts = command.split('=') if len(parts) == 2: var, value = parts self.environment[var] = value else: print("Invalid export command...
magicoder
python
You are tasked with implementing a function that processes a source code string to build the appropriate Abstract Binary Interface (ABI) for a module. The provided code snippet is a part of a Rust program and demonstrates the `build` function, which takes a source code string as input and returns the resulting module A...
```rust use parser; use builder; use elements; use parser::CompileError; pub fn process_source_code(src: &str) -> Result<elements::ModuleABIs, CompileError> { let tokens = parser::get_parse_tokens(src)?; let module = parser::parsers::file_input(&tokens[..])?.1.node; let module_abis = builder::module(&modul...
magicoder
rust
You are tasked with implementing a URL shortening service. The service should take a long URL and generate a unique short URL for it. Additionally, the service should be able to retrieve the original long URL when given the short URL. To achieve this, you need to create a database table to store the mappings between t...
```python import random import string # Function to generate a unique short URL def generate_short_url(long_url: str, domain_id: int) -> str: # Generate a random string of length 6 for the short URL short_url = ''.join(random.choices(string.ascii_letters + string.digits, k=6)) return short_url # Function ...
magicoder
python
You are tasked with implementing a function that calculates the total number of occurrences of a specific word in a given text. The function should be case-insensitive and should only count whole word matches. A word is defined as a sequence of alphanumeric characters, delimited by non-alphanumeric characters or the be...
```cpp #include <iostream> #include <string> #include <cctype> int countWordOccurrences(const std::string& text, const std::string& word) { int count = 0; std::string lowerText = text; std::string lowerWord = word; // Convert both text and word to lowercase for case-insensitive comparison for ...
magicoder
cpp
You are given a code snippet containing hexadecimal values. Your task is to write a program that converts these hexadecimal values into their corresponding decimal representations. Write a function `convertHexToDecimal` that takes a list of hexadecimal values as input and returns a list of their decimal equivalents. ...
```python from typing import List def convertHexToDecimal(hex_values: List[str]) -> List[int]: decimal_values = [] for hex_val in hex_values: decimal_values.append(int(hex_val, 16)) return decimal_values ``` The `convertHexToDecimal` function iterates through the input list of hexadecimal values, ...
magicoder
python
You are tasked with creating a Python function that processes a list of PDF files using Optical Character Recognition (OCR) and returns the extracted text. You will be using the FastAPI framework to create an API endpoint for this functionality. Your task is to complete the implementation of the FastAPI endpoint that ...
```python from fastapi import FastAPI, UploadFile, File from typing import List import pytesseract from pdf2image import convert_from_path app = FastAPI( title="PDF OCR API", description="An API for extracting text from PDF files using OCR" ) def extract_text_from_pdf(pdf_file: UploadFile) -> str: images ...
magicoder
python
You are given a knapsack problem, where you have a set of items, each with a weight and a value, and a knapsack with a maximum weight capacity. The goal is to maximize the total value of items that can be included in the knapsack without exceeding its capacity. You are provided with a recursive function `max_profit(W,...
```python def knapsackMaxValue(W, w, p): n = len(w) ans = [[-1 for _ in range(n)] for _ in range(W+1)] def max_profit(W, n): if n < 0 or W <= 0: return 0 if ans[W][n] != -1: return ans[W][n] if W >= w[n]: aux1 = max_profit(W - w[n], n - 1) + p[n] ...
magicoder
python
You are given a code snippet that defines a class `c` and a struct `S`. However, the code contains syntax errors and incomplete definitions. Your task is to identify and fix the errors in the code to make it syntactically correct and complete the definitions of the class and struct. Fix the code snippet by correcting ...
The corrected code snippet with the completed class and struct definitions is as follows: ```swift class c { // Complete the class definition } struct S<T: S<Int>> { // Complete the struct definition } ``` In the corrected code: - The class `c` and struct `S` are defined with the correct syntax. - The struct...
magicoder
swift
You are working on a system that manages committees and their meetings. The system has a function that retrieves information about committees and their associated meetings. The code snippet provided is a part of this function. It iterates through the `forward_to_committee_ids` of a committee and retrieves information a...
```python def process_committee_data(committee_data: dict) -> list: result = [] for committee_info in committee_data.get("forward_to_committee_ids", []): committee_name = committee_info.get("name") meeting_ids = committee_info.get("meeting_ids", []) permissions_count = sum(1 for meeting_...
magicoder
python
You are tasked with implementing a C++ function that parses a given file containing C++ header file paths and the number of stars given to each file on GitHub. The function should read the file, extract the header file paths and their corresponding star ratings, and then return a map or dictionary containing the header...
```cpp #include <fstream> #include <sstream> #include <map> #include <string> #include <regex> std::map<std::string, std::pair<int, int>> parseHeaderFileStars(const std::string& filename) { std::map<std::string, std::pair<int, int>> headerStarsMap; std::ifstream file(filename); std::string line; if (f...
magicoder
cpp
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 current balance. Additionally, the class should keep track of the total number of transactions performed on any account. Create a Python class `Ban...
```python class BankAccount: total_transactions = 0 def __init__(self): self.balance = 0 def deposit(self, amount): self.balance += amount BankAccount.total_transactions += 1 def withdraw(self, amount): if self.balance >= amount: self.balance -= amount ...
magicoder
python
You are tasked with implementing a custom iterator type in Rust. Your iterator, `DynIter`, should wrap any given iterator and provide a method to retrieve the size hint of the wrapped iterator. You are provided with a code snippet that includes a partial implementation of the `DynIter` type and a method to retrieve th...
```rust use std::iter::Iterator; struct DynIter<'a, V> { iter: Box<dyn Iterator<Item = V> + 'a>, } impl<'a, V> DynIter<'a, V> { pub fn new<I>(iter: I) -> Self where I: Iterator<Item = V> + 'a, { Self { iter: Box::new(iter), } } pub fn get_size_hint(&self) -...
magicoder
rust
You are tasked with implementing a deep copy functionality for a custom `DeepInventory` class in C#. The `DeepInventory` class represents an inventory item with a quantity. Your goal is to create a method that performs a deep copy of the `DeepInventory` object, ensuring that both the original and copied objects are com...
```csharp public class DeepInventory { public int Quantity { get; set; } public DeepInventory(int quantity) { Quantity = quantity; } public DeepInventory DeepCopy() { // Create a new instance of DeepInventory DeepInventory newInventory = new DeepInventory(this.Quantity)...
magicoder
csharp
You are tasked with implementing a program to calculate the value of a specific variable based on given input. The program should take into account the provided code snippet and additional context. Context: The given code snippet is part of a larger program that performs calculations based on certain input parameters....
```java public class Calculation { public static void performCalculation(double[][] result, double D, double sLen, double S, int step) { double C = D * sLen * S; // Calculate the value of C result[step - 1][6] = C; // Store the calculated value of C in the result array Utils.getResult(resu...
magicoder
java
You are tasked with implementing a function that performs a specific type of string manipulation. The function takes a string as input and returns a modified version of the string based on the following rules: 1. If the input string contains the substring "abc", it should be replaced with "def". 2. If the input string...
```java public String manipulateString(String inputStr) { if (inputStr.contains("abc")) { inputStr = inputStr.replace("abc", "def"); } if (inputStr.contains("xyz")) { inputStr = inputStr.replace("xyz", "123"); } return inputStr; } ```
magicoder
java
You are tasked with implementing a Python function that processes an image file using the OpenCV library. The function should load the image file, perform a specific image processing operation, and then save the processed image to a new file. Your task is to complete the implementation of the function `process_image` a...
```python import cv2 def process_image(input_file: str, output_file: str) -> bool: try: # Load the input image using OpenCV image = cv2.imread(input_file, cv2.IMREAD_GRAYSCALE) if image is None: print(f"Error: {input_file} not found") return False ...
magicoder
python
You are tasked with designing a secure authentication system for a web application. The system should include user registration and login functionalities. To achieve this, you need to implement the backend logic for user registration and login using Spring MVC and Spring Security. You are provided with a partial code ...
```java import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; // Assuming UserService and AuthenticationManager are properly defined @Controller public class AuthController { private final UserService userService; private...
magicoder
java
You are tasked with implementing a drag-and-drop functionality for an image view in a macOS application using Swift. The provided code snippet outlines the beginning of a custom `DragDropImageView` class that inherits from `NSImageView` and conforms to the `NSDraggingSource` protocol. Your goal is to complete the imple...
```swift import Cocoa class DragDropImageView: NSImageView, NSDraggingSource { required init?(coder: NSCoder) { super.init(coder: coder) registerForDraggedTypes([.fileURL]) } override func mouseDown(with event: NSEvent) { let pasteboardItem = NSPasteboardItem() if ...
magicoder
swift
You are tasked with implementing a token-based authentication system for a web application. The system should generate a token based on a given user identifier and then create an authentication header using the generated token. You are provided with a `TokenConfiguration` class that takes a user identifier as a parame...
```swift class TokenConfiguration { let userIdentifier: String init(_ userIdentifier: String) { self.userIdentifier = userIdentifier } func generateToken() -> String { // Generate token based on user identifier // Example implementation: Concatenate "Token:" with user i...
magicoder
swift
You are tasked with implementing a function to escape special characters in a C-style string. In C, strings are represented as arrays of characters terminated by a null character ('\0'). Special characters such as newline (\n), tab (\t), backslash (\), and double quotes (") need to be escaped when representing the stri...
```python import json def escape_c_string(s): return json.dumps(s)[1:-1] ``` The `escape_c_string` function uses the `json.dumps` method to escape the special characters in the input string `s`. The `json.dumps` method returns a JSON-formatted string, which includes properly escaped special characters. By slicing...
magicoder
python
You are tasked with creating a custom implementation of a Duck Typing feature in a programming language. Duck typing is a concept in programming that allows an object's methods and properties to be determined by their behavior rather than their type. In this problem, you will create a simplified version of a Duck Typin...
```csharp using System; using System.Reflection; namespace DuckTypingExample { public class DuckTyping { public T InvokeMethod<T>(object obj, string methodName) { MethodInfo method = obj.GetType().GetMethod(methodName); if (method != null && method.ReturnType == typeof(T...
magicoder
csharp
You are tasked with implementing a Rust program that involves defining exchange parameters for different cryptocurrency exchanges. The program should include a struct called `InitAnyExchange` that represents the parameters for various exchanges. The `InitAnyExchange` struct should be an enum with three variants: `Nash`...
```rust // Define the NashParameters struct #[derive(Clone)] pub struct NashParameters { pub api_key: String, pub secret_key: String, } // Define the BinanceParameters struct #[derive(Clone)] pub struct BinanceParameters { pub api_key: String, pub secret_key: String, } // Define the CoinbaseParameters...
magicoder
rust
You are tasked with implementing a generic function that can accept any type of input and perform a specific operation on it. Your task is to create a function called `apply_operation` that takes two arguments: `data` and `operation`. The `data` argument can be of any type (integer, float, string, list, etc.), and the ...
```python def apply_operation(data, operation): return operation(data) # Test cases def square(x): return x * x result1 = apply_operation(5, square) # Returns 25 result2 = apply_operation([1, 2, 3], len) # Returns 3 result3 = apply_operation("hello", str.upper) # Returns "HELLO" ``` The `apply_operation` f...
magicoder
python
You are tasked with implementing a dynamic throttling mechanism for executing blocks of code in a controlled manner. The provided code snippet outlines a function `dynamicThrottle` that takes in a DispatchSemaphore, a delay, a final execution timeout, and a closure to be executed. The function ensures that the next blo...
```swift public func dynamicThrottle(with semaphore: DispatchSemaphore, delay: CFTimeInterval = 0.01, finalExecutionTimeout: CFTimeInterval = 0.5, block: @escaping () -> Void) { // Wait for the semaphore to have a value of 1, indicating that the previous block has finished executing semaphore.wait() // Sch...
magicoder
swift
You are tasked with implementing a C++ program that processes a given header file to extract and display the names of all the included header files. The program should read the input header file and output the names of the included header files in the order they appear in the input file. You are given a code snippet f...
```cpp #include <iostream> #include <fstream> #include <string> #include <regex> #include <vector> #include <algorithm> #include <iterator> int main() { std::ifstream inputFile("example_header.h"); std::string line; std::vector<std::string> includedFiles; while (std::getline(inputFile, line)) { ...
magicoder
cpp
You are tasked with implementing a program to model geometric shapes using object-oriented programming in Python. The program should define a base class `Shape` with methods to calculate the area and perimeter of a shape. Additionally, you need to create subclasses for specific shapes such as `Circle`, `Rectangle`, and...
```python import math class Shape: def area(self): pass def perimeter(self): pass class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 def perimeter(self): return 2 * math.pi * self.radius...
magicoder
python
You are tasked with implementing a simple cryptocurrency ledger system in Python. The system consists of two classes: `User` and `Coin`. The `User` class represents a user of the cryptocurrency system, and the `Coin` class represents the cryptocurrency itself. The `User` class has the following attributes and methods:...
```python class InsufficientFundsError(Exception): pass class InvalidRecipientError(Exception): pass class User: def __init__(self, username, public_key): self.username = username self.public_key = public_key class Coin: def __init__(self, user): self.coin = {user.public_key: ...
magicoder
python
You are tasked with implementing a class that adheres to the `BuildConfigurationInterface` shown in the code snippet. The interface defines several methods that your class must implement. Your task is to create a PHP class that fulfills the requirements of this interface and provides the necessary functionality. Your ...
```php <?php use Neighborhoods\Prefab\Constant\MapInterface; class BuildConfiguration implements BuildConfigurationInterface { private $vendorName; private $constantMap; public function setVendorName(string $vendorName): BuildConfigurationInterface { $this->vendorName = $vendorName; r...
magicoder
php
You are tasked with creating a Python program to manage department information within an organization. The program should allow users to add new departments, update department details, and retrieve department information. To achieve this, you need to implement a Department class with appropriate methods for managing de...
```python class Department: def __init__(self): self.departments = {} self.next_id = 1 def add_department(self, name, description): self.departments[self.next_id] = {'name': name, 'description': description} self.next_id += 1 def update_department_description(self, departme...
magicoder
python
You are tasked with creating a script to automate the process of initializing a new branch called "gh-pages" in a Git repository for hosting a website. The script should perform the following steps: 1. Set the symbolic reference of the HEAD to the "gh-pages" branch. 2. Remove the index file from the Git repository. 3....
```bash #!/bin/bash # Set the symbolic reference of the HEAD to the "gh-pages" branch git symbolic-ref HEAD refs/heads/gh-pages # Remove the index file from the Git repository rm .git/index # Clean the repository, removing untracked files and directories git clean -fdx # Create a file named ".nojekyll" to indicate ...
magicoder
shell
You are given a Swift code snippet that defines an enumeration with some missing parts. Your task is to complete the enumeration and implement a function that takes an input of this enumeration type and returns a specific value based on the input. The given code snippet is as follows: ```swift enum CustomEnum { c...
```swift enum CustomEnum { case valid case invalid } func processEnum(_ input: CustomEnum) -> String { switch input { case .valid: return "Processed valid" case .invalid: return "Processed invalid" } } // Test cases print(processEnum(.valid)) // Output: Processed valid print(...
magicoder
swift
You are tasked with implementing a class that represents a simple bank account. The class should have the following functionalities: 1. Initialize the account with a customer's name and an initial balance. 2. Deposit a specified amount into the account. 3. Withdraw a specified amount from the account. 4. Return the cur...
```python class BankAccount: def __init__(self, customer_name, initial_balance): self.customer_name = customer_name self.balance = initial_balance def deposit(self, amount): if amount > 0: self.balance += amount return True else: return False ...
magicoder
python
You are working on a project that involves integrating CloudKit, Apple's cloud storage service, into a mobile app. As part of this integration, you need to implement a class that manages interactions with the CloudKit database. The class has three methods: `add`, `save`, and `fetch`, each of which interacts with the Cl...
```swift import CloudKit class CloudKitManager { let database: CKDatabase // Assume this is initialized elsewhere init(database: CKDatabase) { self.database = database } func add(_ operation: CKDatabaseOperation) { // Implementation of the add method database.add(operation) ...
magicoder
swift
You are tasked with creating a script to automate the process of converting Android APK files to JAR files and then decoding them to SMALI format for further analysis. The script should utilize the `dex2jar` and `apktool` tools to perform these tasks. Your script should take the following inputs: - `APK_FILE`: The pa...
```bash #!/bin/bash APK_FILE=$1 ZIP_PATH=$2 APK_NAME=$3 echo "Converting DEX to JAR..." dex2jar ${ZIP_PATH}/classes.dex -o ${APK_NAME}.jar echo "Decoding to SMALI..." apktool decode ${APK_FILE} ``` The provided bash script takes three command-line arguments: `APK_FILE`, `ZIP_PATH`, and `APK_NAME`. It then executes ...
magicoder
shell
You are tasked with creating a TypeScript class that manages supervisors in a company. The class should have a constructor that injects an instance of the HttpClient class and a method called `crearSupervisor` that takes supervisor data as input and sends a POST request to a server to create a new supervisor. Your task...
```typescript import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; class SupervisorManager { constructor(public http: HttpClient) { } crearSupervisor(data): Observable<any> { const url = 'https://example.com/api/supervisors'; // Replace with the actual API endpoint return ...
magicoder
typescript
You are tasked with implementing a cryptographic pairing operation for points on elliptic curves. The given code snippet provides a partial implementation of two classes, `AbstractPointG1` and `AbstractPointG2`, which represent points on different elliptic curves. The `pairing` method in each class is used to perform a...
```python class AbstractPoint: def __init__(self, group): self._group = group def group(self): return self._group def double(self): # Implementation of point doubling operation pass class AbstractPointG1(AbstractPoint): def pairing(self, other: 'AbstractPointG2'): ...
magicoder
python
You are tasked with implementing a music scheduling system for a Discord bot using Java. The system should allow users to add songs to a queue and play them in a scheduled manner. You are provided with a partial implementation of the `MusicScheduler` class, which uses the JDA (Java Discord API) library for interacting ...
```java import java.util.concurrent.BlockingDeque; import java.util.concurrent.TimeUnit; public class MusicScheduler extends AudioEventAdapter implements Runnable { // Existing attributes public MusicScheduler(AudioPlayer player, MessageDispatcher messageDispatcher, ScheduledExecutorService executorService, Block...
magicoder
java
You are tasked with implementing a method to set contour levels in a visualization library. The method `setContourLevels` is a synchronized method that takes an array of contour values as input. Your task is to write the implementation for this method, ensuring that it fires a `java.beans.PropertyChangeEvent` for the p...
```java public synchronized final void setContourLevels(double[] contourLevels) throws VisADException, RemoteException { if (contourLevels == null) { throw new IllegalArgumentException("Contour levels cannot be null"); } double[] oldLevels = this.contourLevels; // Assuming contourLevels is a class...
magicoder
java
You are tasked with creating a Python class that simulates a simple online game player management system. The system should allow for the registration and administration of players, including the ability to view and modify player details. Your task is to implement the `Player` class and a corresponding `PlayerAdmin` cl...
```python class Player: def __init__(self, username, level, score): self.username = username self.level = level self.score = score class PlayerAdmin: players = [] @classmethod def register_player(cls, username, level, score): player = Player(username, level, score) ...
magicoder
python
You are tasked with creating a Python class that logs the time taken for a function to execute. Your class should have a decorator method that can be used to wrap any function and log the time taken for its execution. The decorator should use the `logging` module to log the time taken in milliseconds. Additionally, the...
```python import time import logging class TimerLogger: def __init__(self): self.log_level = logging.INFO def set_log_level(self, level): self.log_level = getattr(logging, level.upper()) def log_time(self, func): def wrapper(*args, **kwargs): start_time = time.time() ...
magicoder
python
You are tasked with implementing a role-based access control system for an admin panel using Laravel's Eloquent ORM and middleware. The system should allow only authenticated users with the "admin" role to access certain routes. You need to create a middleware and apply it to the appropriate routes to enforce this acce...
```php use Illuminate\Database\Eloquent\ModelNotFoundException; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class AdminController extends Controller { public function __construct() { $this->middleware('admin'); } } ``` ```php // AdminMiddleware.php namespace App\Http\Middlewa...
magicoder
php
You are given a circular ring represented by a string `ring` and a sequence of characters `path` that you need to traverse. The ring is composed of lowercase English letters, and the initial position of the "pointer" is at index 0. The pointer can move clockwise or counterclockwise around the ring, and the goal is to f...
```python def minSteps(ring, path): def distance(p1, p2, ring_len): return min(abs(p1 - p2), ring_len - abs(p1 - p2)) memo = {} def dp(ring_idx, path_idx): if path_idx == len(path): return 0 if (ring_idx, path_idx) in memo: return memo[(ring_idx, path_idx)] ...
magicoder
python
You are tasked with implementing a Python class for calculating and comparing Chebyshev polynomials. The Chebyshev polynomials of the first kind are defined by the recurrence relation T_0(x) = 1, T_1(x) = x, and T_{n+1}(x) = 2x * T_n(x) - T_{n-1}(x) for n >= 1. Your task is to implement the `Chebyshev` class with the f...
```python from typing import List class Chebyshev: def __init__(self, coefficients: List[float]): self.coefficients = coefficients def evaluate(self, x: float) -> float: if len(self.coefficients) == 1: return self.coefficients[0] elif len(self.coefficients) == 2: ...
magicoder
python
You are tasked with creating a role-based access control system for a web application. The system should allow or deny access to specific resources based on the user's role. You are given a code snippet from a PHP class method that checks whether a user is authorized to access a specific resource. Your task is to imple...
To implement the role-based access control system, you can follow these steps: Step 1: Define Roles and Permissions Define a set of roles (e.g., admin, editor, viewer) and the corresponding permissions for each role. For example: - Admin role: full access to all resources - Editor role: read and write access to specif...
magicoder
php
You are tasked with creating a program that simulates a simple banking system. The system should be able to create and manage bank accounts, allowing users to deposit, withdraw, and check their balance. Each bank account should have a unique account number and be associated with the account holder's name. Your task is...
```python class BankAccount: account_number_counter = 1000 def __init__(self, account_holder_name): self.account_holder_name = account_holder_name self.account_number = BankAccount.account_number_counter + 1 BankAccount.account_number_counter += 1 self.balance = 0 def depos...
magicoder
python
You are tasked with implementing a simple addition game using Python. The game will generate random addition problems and prompt the user to solve them. The user's score will be based on the number of correct answers given within a certain time limit. Your task is to implement the `AdditionGame` class, which will have...
```python import random import time from typing import Tuple class AdditionGame: def __init__(self, max_len_query_digit: int, time_limit: int): self._max_len_query_digit = max_len_query_digit self._time_limit = time_limit def generate_query(self) -> Tuple[str, int]: max_digit = pow(10,...
magicoder
python
You are tasked with implementing a Swift extension for the Comparable protocol. The extension should provide a method that generates a value within a given closed interval, as close to the original value as possible. The method should take the lower and upper bounds of the closed interval as input and return a value wi...
```swift public extension Comparable { /** Generates a value that, given a closed interval, will be within the bounds, as close to the original value as possible. - parameter lower: The lowest value allowed in the closed interval - parameter upper: The highest value allowed in the closed interv...
magicoder
swift
You are tasked with creating a program that compares the titles of news articles from two different RSS feeds and finds the closest matching title from one feed for each title in the other feed. You are given a code snippet that retrieves and processes the RSS feeds from CNN and CBC news sources, and then uses the `dif...
```python from typing import List, Dict import difflib def find_closest_matches(cnn_titles: List[str], cbc_titles: List[str]) -> Dict[str, str]: closest_matches = {} for title in cnn_titles: match = difflib.get_close_matches(title, cbc_titles, 1, 0.01) closest_matches[title] = match[0] if match...
magicoder
python
You are tasked with creating a program that analyzes a given text file to count the occurrences of specific words. The program should read the text file, count the occurrences of each word, and then display the word count for each word in the file. For this problem, you should ignore case sensitivity, punctuation, and ...
```python import re def countWordOccurrences(file_path): word_count = {} with open(file_path, 'r') as file: text = file.read().lower() words = re.findall(r'\b\w+\b', text) for word in words: if word in word_count: word_count[word] += 1 else: ...
magicoder
python
You are tasked with implementing a currency conversion system using C++. The system should be able to convert between different currency codes based on the ISO 4217 standard. The provided code snippet is a part of the `currency` class, which includes a method `isonum2hash` for converting ISO currency codes to numerical...
```cpp #include <iostream> #include <cstring> class currency { public: void convert(const char* target_code, double amount) { double target_num = data::isonum2hash(target_code); double converted_amount = amount * (target_num / num_); converted_amount_ = converted_amount; std::strcpy(target_code_, tar...
magicoder
cpp
You are tasked with creating a program to manage the training of subjects for a citizen science project on Zooniverse. The program needs to handle user authentication, workflow selection, subject set identification, defining training chances, and optionally editing subject metadata. Your task is to implement the logic ...
```python # Import necessary libraries import zooniverse_api # Assuming the existence of a Zooniverse API library # Authenticate user zooniverse_api.authenticate(puser, ppswd) # Select workflow zooniverse_api.select_workflow(workflowid) # Define training process def manage_training_process(subjsetids, chances, defa...
magicoder
python
You are working on a project that involves handling Look-Up Tables (LUTs) in a microcontroller. The code snippet provided is a part of a struct definition in Rust programming language. The struct contains multiple LUTs, each followed by a reserved array of bytes. The LUTs are defined with specific offsets and descripti...
```rust fn extract_luts(base_address: usize) -> Vec<(usize, String)> { let mut result = Vec::new(); let offsets = [0x80, 0xa0, 0xc0, 0xe0]; let descriptions = ["no description available"; 4]; for i in 0..4 { let offset = base_address + offsets[i]; let description = descriptions[i].to_st...
magicoder
rust
You are tasked with creating a Rust library that provides functionality for manipulating and analyzing geometric shapes. Your library should include modules for calculating the area, perimeter, and other properties of common geometric shapes such as circles, rectangles, and triangles. Additionally, the library should p...
```rust // Define a module for the circle shape mod circle { const PI: f64 = 3.14159; pub struct Circle { radius: f64, } impl Circle { pub fn new(radius: f64) -> Circle { Circle { radius } } pub fn area(&self) -> f64 { PI * self.radius * self.ra...
magicoder
rust
You are tasked with implementing a Python function that performs array indexing in both LValue and RValue contexts. The function should handle the assignment of values to array elements and the retrieval of values from array elements. You are given the following code snippet as a starting point for your implementation...
```python def LeftIndex(p, w, left, unused_bp): # Assuming that the parser object p has a method for parsing expressions index_expr = p.parse_expression() # Check if the current token w is an assignment operator if w == '=': # LValue context: handle assignment of value to array element ...
magicoder
python
You are tasked with creating a Python script that extracts and prints the metadata information from a given code file. The metadata information is embedded as comments at the beginning of the file and follows a specific format. The metadata includes the author's name, email, copyright, license, and date. Write a funct...
```python import re def extract_metadata(file_path): metadata = {} try: with open(file_path, 'r') as file: for line in file: if line.strip().startswith('#'): match = re.match(r'__(\w+)__\s+=\s+"(.+)"', line.strip()) if match: ...
magicoder
python
You are tasked with creating a Python program to manipulate colors in various ways. The program should define a class `Color` with the following functionalities: 1. Initialize the color with a hex code. 2. Return the RGB representation of the color. 3. Return the complementary color. 4. Darken the color by a specified ...
```python class Color: def __init__(self, hex_code): self.hex_code = hex_code def hex_to_rgb(self): hex_code = self.hex_code.lstrip('#') return tuple(int(hex_code[i:i+2], 16) for i in (0, 2, 4)) def rgb_to_hex(self, rgb): return '#{:02x}{:02x}{:02x}'.format(*rgb) def g...
magicoder
python
You are given a string `s` consisting of lowercase English letters. Your task is to find the total count of all possible substrings of `s` that contain all three letters 'a', 'b', and 'c' at least once. The count of each letter in the substring does not matter, as long as all three letters are present. Write a functio...
```python def countSubstrings(s: str) -> int: left, right = 0, 0 subStringCount = 0 counter = {c: 0 for c in 'abc'} while right < len(s): counter[s[right]] += 1 while all(counter.values()): counter[s[left]] -= 1 left += 1 subStringCount += 1 # In...
magicoder
python
You are tasked with implementing a motion control system for a differential drive robot. The robot has two independent motors for its left and right sides, and it is equipped with a gyro sensor for measuring orientation. The provided code snippet includes the initialization of various components used in the motion cont...
```java public void calculateWheelSpeeds(double desiredLinearVelocity, double desiredAngularVelocity) { // Calculate the feedforward component double feedforwardLeft = m_feedforward.calculate(desiredLinearVelocity, desiredAngularVelocity); double feedforwardRight = m_feedforward.calculate(desiredLinearVeloc...
magicoder
java
You are tasked with creating a program that verifies the usage of a custom command-line tool called `cpack3`. The tool is expected to output usage information when the `--help` option is provided. Your task is to write a script that checks whether the usage information contains the expected keywords. Write a Bash scri...
```bash #!/bin/bash source "../common/common_cmake.sh" function pre_test() { LOG_INFO "Start to prepare the test environment." deploy_env LOG_INFO "Finish preparing the test environment." } function run_test() { LOG_INFO "Start to run test." cpack3 --help | grep -E "Usage|cpack \[options\]" #...
magicoder
shell
You are tasked with implementing a function to convert a string representation of a percentage to its equivalent decimal value. The function should handle various input cases and return both the converted value and a success indicator. Write a function `ConvertPercentToDecimal` that takes a string `percentStr` as inpu...
```csharp public (double, bool) ConvertPercentToDecimal(string percentStr) { if (string.IsNullOrEmpty(percentStr)) { return (0, false); } if (percentStr.EndsWith("%")) { if (double.TryParse(percentStr.TrimEnd('%'), out double percentValue)) { double decimalValue ...
magicoder
csharp
You are tasked with creating a Python function to interact with the Rundeck API for executing commands on specific nodes within a project. The function should take in the necessary parameters and make an HTTP POST request to the Rundeck server to execute the specified command on the designated nodes. You are provided ...
```python import requests def execute_rundeck_command(api_key: str, project: str, command: str, nodes: str, node_keepgoing: bool) -> dict: headers = { 'X-Rundeck-Auth-Token': api_key, 'Accept': 'application/json', 'Content-type': 'application/json' } rundeck_host = 'http://10.1.16....
magicoder
python
You are tasked with implementing a distance badge view for a mobile application. The distance badge view should display the distance between two points and include an icon and a label. Your task is to complete the implementation of the `HLDistanceBadgeView` class by adding a method to calculate the distance between two...
```swift import UIKit class HLDistanceBadgeView: HLBadgeView { @IBOutlet var label: UILabel! @IBOutlet var iconView: UIImageView! static func badgeView() -> HLDistanceBadgeView { // Implementation of badgeView method // ... } func updateDistance(from startPoint: CGPoint, to endPoi...
magicoder
swift
You are tasked with implementing a class to manage and process image data for a computer vision application. The class should support the insertion of image data, including keypoints, bounding boxes, image IDs, and keypoint pools. Additionally, the class should handle the storage and manipulation of various attributes ...
```python class ImageProcessor: def __init__(self): self.keypoints_det2 = dict() self.keypoints_proj2 = dict() self.bboxs = dict() self.image_ids = dict() self.rt = dict() self.keypoints_pool = dict() self.pca = [0.0] * 5 self.shape = [[0.0, 0.0, 0.0] ...
magicoder
python