query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with implementing a simple factory design pattern for creating different types of smartphones. The code snippet provided is a starting point for the problem. You are given the following class definitions: ```cpp class Nokia { public: virtual void Call(const std::string& number) = 0; }; class Lumia...
```cpp #include <iostream> #include <string> class Nokia { public: virtual void Call(const std::string& number) = 0; }; class Lumia920 : public Nokia { public: void Call(const std::string& number) override { std::cout << "Calling " << number << " using Lumia920" << std::endl; } }; class iPhone : ...
magicoder
cpp
You are tasked with implementing the A* search algorithm to find the shortest path between two points on a grid. The grid is represented as a 2D array where each cell can be either empty or blocked. The A* search algorithm uses a heuristic to guide its search and is commonly used in pathfinding and graph traversal. Yo...
```python import heapq def heuristic(a, b): return abs(a[0] - b[0]) + abs(a[1] - b[1]) def astar_search(grid, start, end): rows, cols = len(grid), len(grid[0]) open_set = [] heapq.heappush(open_set, (0, start)) came_from = {} g_score = {start: 0} f_score = {start: heuristic(start, end)} ...
magicoder
python
You are given an array A of integers. Your task is to find the maximum possible length of a contiguous subarray within A, such that the subarray is non-decreasing. For example, given the array A = [3, 1, 6, 2, 7, 4], the contiguous subarray [2, 7, 4] is the longest non-decreasing subarray, with a length of 3. Write ...
```python from typing import List def max_non_decreasing_subarray_length(A: List[int]) -> int: result = 0 stack = [] for j in reversed(range(len(A))): while stack and A[stack[-1]] <= A[j]: result = max(result, j - stack.pop()) stack.append(j) return result ``` The `max_non_...
magicoder
python
You are tasked with implementing a parser for a custom language that uses a specific syntax for defining key-value pairs. The language allows for defining multiple key-value pairs within a single string, with each pair separated by commas. The keys can have optional values, which are enclosed in square brackets and sep...
```python import re def parse(input_string): result = {} if input_string.startswith('BAP: '): input_string = input_string[5:] pairs = re.findall(r'(\w+)(?:=("[^"]*"|[^,]+))?(?:,|$)', input_string) for key, value in pairs: if value.startswith('"') and value.endswith('"'): ...
magicoder
python
You are given a hexadecimal-encoded image file in the form of a long string. Your task is to decode the image and convert it into a human-readable format. Write a function `decode_image(hex_string: str) -> str` that takes a hexadecimal-encoded image string as input and returns the decoded image in a human-readable for...
```python import binascii def decode_image(hex_string: str) -> str: # Remove any backslashes and concatenate the hex string hex_string = hex_string.replace('\\', '').replace('\n', '') # Convert the concatenated hex string to bytes image_bytes = bytes.fromhex(hex_string) # Write the bytes to a fil...
magicoder
python
You are tasked with implementing a custom YAML deserialization feature for a C# application. The application uses the YamlDotNet library for YAML processing. Your goal is to create a custom deserializer that can handle a specific attribute, `ScalarStyle`, for the `InputDefinition` class. The `InputDefinition` class is...
```csharp using YamlDotNet.Core; using YamlDotNet.Core.Events; using YamlDotNet.Serialization; namespace SubmissionEvaluation.Contracts.Data { public class CustomInputDefinitionDeserializer : INodeDeserializer { public bool Deserialize(IParser parser, Type expectedType, Func<IParser, Type, object> nest...
magicoder
csharp
You are tasked with creating a program to manage a hierarchical structure of body parts in a 3D model. Each body part has a unique identifier and a descriptive name. The identifiers follow a specific naming convention, where the prefix "mixamorig:" is followed by the body part name and a number indicating the level of ...
```python from typing import List, Tuple, Dict, Union def organize_body_parts(parts: List[Tuple[str, str]]) -> Dict[str, Union[str, Dict[str, Union[str, Dict[str, str]]]]]: hierarchy = {} for identifier, name in parts: parts_list = identifier.split(":")[1].split("Hand")[1].split("3") current_le...
magicoder
python
You are tasked with creating a script to automate the comparison of benchmark results for different sets of parameters. The script should take benchmark data, parameter values, and display names as input, and then calculate differences between original and modified benchmarks. Finally, the script should copy the result...
```bash #!/bin/bash # Define input variables benchmark="benchmark_data" vs=("value1" "value2" "value3") # Array of parameter values params=("param1" "param2" "param3") # Array of parameter names displayNames=("display1" "display2" "display3") # Array of display names originalBenchmarks=("original1" "original2" "ori...
magicoder
shell
You are tasked with creating a program that decrypts a message encoded using a simple substitution cipher. In a substitution cipher, each letter in the plaintext is replaced by a letter some fixed number of positions down or up the alphabet. For this problem, you are given a string `encrypted_text` containing the encry...
```python def decrypt_message(encrypted_text: str) -> str: decrypted = "" for symbol in encrypted_text: if symbol.isalpha(): if symbol.islower(): decrypted += chr(((ord(symbol) - ord('a') - 13) % 26) + ord('a')) if symbol >= 'n' else chr(((ord(symbol) - ord('a') + 13) % 26) +...
magicoder
python
You are tasked with designing a vehicle detection and tracking system for an autonomous driving application. The system will consist of several components, each responsible for a specific operation. The components include LaneFinder, PerspectiveFinder, StatsWriter, VehicleFinder, VehicleClusterer, and VehicleTracker. E...
```python class VehicleDetectionSystem: def __init__(self): self.lane_finder = LaneFinder() self.perspective_finder = PerspectiveFinder() self.stats_writer = StatsWriter() self.vehicle_finder = VehicleFinder() self.vehicle_clusterer = VehicleClusterer() self.vehicle_t...
magicoder
python
You are working on a data processing application that involves handling SQL scripts, source data, and destination tables. Your task is to implement a class method that processes input arguments and performs necessary operations based on the provided inputs. The method should handle various scenarios such as specifying ...
```python class DataProcessing: def process_input(self, **kwargs): self.s3_source_dir = kwargs['s3_source_dir'] assert exactly_one(sql, source, script), 'One of sql/source/script' # Input formatting dest = Table(SqlScript(filename=parse_path(destination)) if source is not N...
magicoder
python
You are tasked with implementing a custom JSON serialization method for a Swift array. The method should take an array of elements and convert it into a JSON string. Additionally, the method should support an optional parameter for pretty-printing the JSON output. You are provided with a partial implementation of the ...
```swift public extension Array { func jsonStringify(_ prettyPrinted: Bool = false) -> String { let options = prettyPrinted ? JSONSerialization.WritingOptions.prettyPrinted : JSONSerialization.WritingOptions(rawValue: 0) if JSONSerialization.isValidJSONObject(self) { do { ...
magicoder
swift
You are tasked with implementing a compression and decompression utility in C#. Your goal is to create a class that provides methods for compressing and decompressing data using the Deflate algorithm. The class should offer both synchronous and asynchronous decompression methods, and should allow the option to leave th...
```csharp using System; using System.IO; using System.IO.Compression; using System.Threading.Tasks; public class CompressionUtility { public MemoryStream Compress(Stream dataToCompress, bool leaveStreamOpen = false) { MemoryStream compressedStream = new MemoryStream(); using (DeflateStream defl...
magicoder
csharp
You are tasked with implementing a function to determine the number of days in a given month of a given year. The function should account for leap years, where February has 29 days. You are provided with a code snippet that contains a function to return 29 for February in a leap year and an array `daysinmonth` that hol...
```cpp #include <iostream> bool isLeapYear(int year) { if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) { return true; } return false; } int getDaysInMonth(int month, int year) { const int daysinmonth[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; if (month == 2) { ...
magicoder
cpp
You are tasked with creating a Discord bot that can perform various tasks based on user commands. The bot will need to read settings from a JSON file and utilize Discord's intents feature for specific functionalities. You are provided with a Python code snippet that initializes the necessary components for the bot, in...
```python import discord from discord.ext import commands import time import json with open('./setting.json', mode='r', encoding='utf8') as jfile: jdata = json.load(jfile) intents = discord.Intents.all() bot = commands.Bot(command_prefix=jdata['prefix'], intents=intents) @bot.event async def on_ready(): prin...
magicoder
python
You are tasked with developing a module for a web-based report generation system. The module should allow users to customize the header and footer of the reports, as well as specify various formatting options such as margins and orientation. The provided code snippet is a part of the module's configuration, defining th...
```python def generate_report_css(html: str, footer_html: str, css: str, name: str, margin_top: float, margin_bottom: float, margin_left: float, margin_right: float, orientation: str) -> str: page_size = "landscape" if orientation.lower() == "landscape" else "portrait" margin = f"{margin_top}mm {margin_right}mm...
magicoder
python
You are tasked with creating a Python program to fetch a list of free proxy servers from a website and test their connectivity to a specific URL. You will need to parse the proxy server details from the website, establish a connection to each proxy server, and then test the connectivity to a testing URL. Your program...
```python import requests from bs4 import BeautifulSoup import socket import socks import stem.process class Config: PROXY_WEBPAGE = "https://free-proxy-list.net/" TESTING_URL = "https://google.com" def fetch_proxy_list(): response = requests.get(Config.PROXY_WEBPAGE) soup = BeautifulSoup(response.tex...
magicoder
python
You are tasked with implementing a Python class for managing book information, specifically related to ISBN (International Standard Book Number) codes. The class should provide functionality for validating and formatting ISBN codes. Your task is to complete the implementation of the `ISBNManager` class by adding the f...
```python class ISBNManager: def __init__(self): self.name = 'isbn' def validate_isbn(self, isbn): isbn = isbn.replace('-', '') # Remove hyphens for validation if len(isbn) == 10: if not isbn[:-1].isdigit() or not (isbn[-1].isdigit() or isbn[-1] == 'X'): ret...
magicoder
python
You are tasked with creating a Python program to optimize a DEA (Data Envelopment Analysis) problem using the Korali library. DEA is a non-parametric method for measuring the efficiency of decision-making units (DMUs) such as firms, organizations, and schools. In this problem, you will need to set up an experiment usin...
```python import sys sys.path.append('./model') sys.path.append('./helpers') from model import * from helpers import * import korali # Define the DEA problem components # For example, define inputs, outputs, and constraints inputs = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # Example input data outputs = [[10, 11], [12, 13]...
magicoder
python
You are tasked with implementing a function that processes a series of input pairs and constructs a specific data structure based on the input. Each pair consists of a numeric identifier and a corresponding action. The actions are as follows: - If the identifier is 93, it signifies the count of generation settings to b...
```rust use std::iter::Peekable; enum Action { Handle(u32), } struct SpecificDataStructure { generation_settings: Vec<GenerationSetting>, source_object_handles: Vec<u32>, destination_object_handle: Option<u32>, } struct GenerationSetting { // Define the structure for generation settings if needed...
magicoder
rust
You are tasked with implementing a poker hand ranking system in Java. Your goal is to extend the existing codebase to include the functionality for identifying a "One Pair" hand in a poker game. The provided code snippet is a part of the existing codebase and represents the beginning of the implementation for the "One ...
```java @Override public void applyRankRule(Hand hand) { Map<Ranks, Long> counted = RankingUtil.countGroupByRank(hand); Map<Ranks, Long> pairs = RankingUtil.pairByRank(counted); if (!hand.isRanked() && pairs.size() == 1) { hand.setRanked(this); additionInformation = getPairedRank(pairs); ...
magicoder
java
You are tasked with implementing a Python class that represents a machine learning model. The class should have a method to fit the model and a property to retrieve the accuracy of the model on a test set. You need to implement the `fit` method and the `accuracy` property according to the given specifications. Your ta...
```python class Model: def __init__(self): self.__model = None self.__accuracy = None def fit(self, training_data): """ Fit the model to the training data :param training_data: input training data :type training_data: list or numpy array """ # As...
magicoder
python
You are tasked with creating a program that analyzes the frequency of words in a given text. Your program should take a string of text as input and output a list of unique words along with their frequencies, sorted in descending order based on frequency. For this problem, a word is defined as a sequence of alphanumeric...
```python import re from collections import Counter def word_frequency(text): # Convert text to lowercase and remove punctuation text = re.sub(r'[^a-zA-Z0-9\s]', '', text.lower()) # Split the text into words words = re.findall(r'\b\w+\b', text) # Count the frequency of each word word_counts = C...
magicoder
python
You are tasked with implementing a function to control the movement of a robot with two wheels. The provided code snippet is a part of a larger program that controls the robot's movement. The `rotate` function is responsible for rotating the robot by a specified angle at a given speed. The robot's movement is achieved ...
```python from math import pi # Constants WHEEL_DISTANCE = 10 # Example value for the distance between the two wheels INCHES_TO_TICKS = 20 # Example conversion factor from inches to ticks # Functions def _clear_ticks(): # Implementation of the function to reset the ticks count pass def _drive(left_speed, r...
magicoder
python
You are tasked with implementing a function that processes a dictionary of functions and their associated metadata. The function should filter and organize the functions based on certain criteria and return the result in a specific format. You are given the following code snippet as a starting point: ```python funcs ...
```python def functionInfo(name, func): # Example implementation of functionInfo # This is a placeholder and should be replaced with actual implementation # Assume 'group' is a key in the metadata dictionary return {'group': 'math', 'other_info': '...'} def processFunctions(funcs, group=None, grouped=F...
magicoder
python
You are tasked with implementing a class that manages an indexed collection of objects. The class should support adding new objects, removing existing ones, and iterating through the collection. You are given a code snippet that partially implements the functionality. Your task is to complete the implementation of the...
```php class Indexed { private static $collection = []; public static function build($attributes) { return new self($attributes); } private $attributes; public function __construct($attributes) { $this->attributes = $attributes; } public function save() { self::$c...
magicoder
php
You are tasked with implementing a network data transfer monitoring system. Your goal is to create a program that tracks the amount of data sent over a network connection and provides real-time feedback on the data being transferred. You will need to simulate a network connection and implement a data transfer monitorin...
```rust use tokio::net::TcpStream; use tokio::io::{AsyncReadExt, AsyncWriteExt}; #[tokio::main] async fn main() { let mut stream = TcpStream::connect("127.0.0.1:8080").await.unwrap(); let mut total_buffer_written = 0; loop { let mut data = [0u8; 1024]; let data_read = stream.read(&mut dat...
magicoder
rust
You are tasked with creating a Python program that converts a PDF file into an audiobook. The program should utilize the `PyPDF2` and `pyttsx3` libraries to extract text from each page of the PDF and convert it into speech. The program should be able to handle any PDF file and convert its content into an audiobook. Yo...
```python import pyttsx3 import PyPDF2 def pdf_to_audiobook(pdf_file_path): # Open the specified PDF file pdf_reader = PyPDF2.PdfFileReader(open(pdf_file_path, 'rb')) # Initialize the text-to-speech engine speaker = pyttsx3.init() # Iterate through each page of the PDF for page_num in range(p...
magicoder
python
You are tasked with creating a file upload helper function in PHP. The function should take a file and an upload directory as input and handle the file upload process. Your task is to complete the `uploadHelper` function by implementing the file upload logic using PHP's built-in functions. The `uploadHelper` function ...
```php class FileUploader { private function file_exists($files) { return file_exists($files); } private function uploadHelper($file, $uploaddir) { $targetFile = $uploaddir . basename($file['name']); if ($this->file_exists($targetFile)) { return $targetFile; } el...
magicoder
php
You are tasked with creating a Python program that simulates a simple server-client interaction using the `caravan` library. The server will be responsible for processing tasks sent by clients, and the clients will send tasks to the server for processing. Your task is to complete the Python program by implementing the...
```python # Import necessary modules from caravan import Server, Task, Client # Define a function to process tasks on the server def process_task(task): # Perform some processing on the task result = task + " processed" return result # Define the server component with Server.start() as server: # Defin...
magicoder
python
You are tasked with creating a Python program that analyzes a given directory and its subdirectories to retrieve information about the directory structure. Your program should list all the directories and files within the specified path and its subdirectories. Additionally, it should calculate the total size of all the...
```python import os import sys import logging logging.basicConfig(format='%(asctime)s | %(levelname)s: %(message)s', level=logging.DEBUG) def getDirsAndFiles(path): result = {} try: for root, dirs, files in os.walk(path): file_list = [f for f in files if os.path.isfile(os.path.join(root, f...
magicoder
python
You are working on a project that involves storing and retrieving large arrays of numerical data efficiently. You have decided to use Python's `pickle` module for serialization and deserialization, and the `numpy` library for handling numerical arrays. However, you want to ensure that the data is stored in a compressed...
```python import pickle import gzip import numpy as np def save_compressed_array(array, filename): try: with gzip.open(filename, 'wb') as file: pickle.dump(array, file) except (IOError, pickle.PickleError) as e: print(f"Error occurred while saving compressed array: {e}") def load_c...
magicoder
python
You are tasked with implementing a Python function that parses a bpython-formatted colored string and returns a list of tuples representing the colored segments of the string. The bpython-formatted colored string consists of color codes enclosed in square brackets followed by the text to be colored. The color codes ar...
```python from typing import List, Tuple def color_for_letter(letter_color_code: str, default: str = "k"): CNAMES = {"r": "red", "g": "green", "b": "blue", "k": "black"} # Define color mappings if letter_color_code == "d": letter_color_code = default return CNAMES[letter_color_code.lower()] def p...
magicoder
python
You are tasked with implementing a custom data structure called `UniqueStack` that combines the functionality of a stack and a set. The `UniqueStack` should store unique elements and support standard stack operations such as push, pop, and peek. Additionally, it should provide a method to retrieve the minimum element i...
```csharp using System; using System.Collections.Generic; public class UniqueStack { private Stack<int> stack; private HashSet<int> uniqueSet; public UniqueStack() { stack = new Stack<int>(); uniqueSet = new HashSet<int>(); } public void Push(int value) { if (!uniq...
magicoder
csharp
You are working on a project that involves a TypeScript Angular client generated from an API. The project structure includes a file named `api.ts` located at `<filename>front02/src/typescript-angular-client-generated/typescript-angular-client/api/api.ts`. This file is used to export functionality from a service named `...
```typescript import { StockService } from '<filename>front02/src/typescript-angular-client-generated/typescript-angular-client/api/stock.service'; class StockAnalyzer { private stockService: StockService; constructor(stockService: StockService) { this.stockService = stockService; } async analyzeStockDat...
magicoder
typescript
You are tasked with implementing a context manager for a database session in Python. The context manager should handle adding a status to the database, committing the changes, rolling back the changes in case of an exception, and removing the database session. Your task is to complete the implementation of the `Databas...
```python class DatabaseSession: def __enter__(self): # Enter the database session return self def __exit__(self, exc_type, exc_value, traceback): # Exit the database session if exc_type is not None: self.rollback() self.remove() def add(self, status): ...
magicoder
python
You are tasked with implementing a Python function that extracts information about the arguments and annotations of another function. Your goal is to create a function that takes a function `f` as input and returns specific details about its arguments and annotations. Write a Python function `extract_function_info(f)`...
```python import inspect def extract_function_info(f): info = {} argspec = inspect.getfullargspec(f) info['args'] = argspec.args info['varargs'] = argspec.varargs info['varkw'] = argspec.varkw info['defaults'] = argspec.defaults info['kwonlyargs'] = argspec.kwonlyargs info['kwonlyd...
magicoder
python
You are tasked with implementing a version control system for a software project. The version control system will manage three types of version numbers: release version, database version, and build version. Each type of version number has specific rules for when and how it should be updated. The release version (rr) s...
```python class VersionControlSystem: def __init__(self, release_version, database_version, build_version): self.release_version = release_version self.database_version = database_version self.build_version = build_version def update_release_version(self, new_release_version): s...
magicoder
python
You are given a code snippet that manipulates arrays using various operations. Your task is to implement a function that performs a specific rotation operation on an array. You are given the following information: - The code snippet uses the functions `reset`, `cp`, and `rot` to manipulate arrays. - The `reset` functi...
```cpp void rot(int* dest, const int* src, int size, int s) { int shift = s % size; // Calculate the effective shift within the array size // Perform the rotation operation for (int i = 0; i < size; i++) { dest[(i + shift) % size] = src[i]; } } ``` The `rot` function takes the destination arr...
magicoder
cpp
You are working on a medical imaging software project and need to implement a function to print a bucket map to a volume. The provided code snippet includes a function `printbucket` that takes three parameters: `bck` (bucket map), `vol` (volume), and `value`. Additionally, there are two variables `seed` and `voxel_size...
```python import aims # Assuming the necessary library is imported def printbucket(bck, vol, value): # Assuming the necessary initialization of lgw_vol and lgw_vol.header() is done seed = -lgw_vol voxel_size = lgw_vol.header()["voxel_size"] # Assuming the necessary initialization of RawConverter_...
magicoder
python
You are tasked with implementing a Python class method that retrieves a record from a database by its UUID (Universally Unique Identifier). The method should handle potential exceptions and errors, and ensure that the database transaction is rolled back in case of failure. Below is the skeleton of the method: ```pytho...
```python class DatabaseHandler: def retrieve_record_by_uuid(self, uuid): try: # Database query to retrieve record by UUID req = self.db.query("SELECT * FROM records WHERE uuid = %s", (uuid,)) if not req: return None else: retur...
magicoder
python
You are tasked with creating a Python class to manage outbound rules for a security group. The class should allow for adding, removing, and listing outbound rules. Each outbound rule consists of the following attributes: - `action` (a string representing the action of the rule, e.g., "ALLOW" or "DENY") - `ip` (a string...
```python class RuleNotFound(Exception): pass class SecurityGroup: def __init__(self): self.outbound_rules = [] def add_rule(self, action, ip, ip_range, port, port_range, protocol): for rule in self.outbound_rules: if rule['ip'] == ip and rule['port'] == port: r...
magicoder
python
You are tasked with creating a Django model for a document repository system. The model should include fields for the repository name, document URL, user who uploaded the document, and the date and time of the upload. Below is a partial code snippet for the Django model: ```python class Document(models.Model): rep...
```python from django.db import models from datetime import datetime, timedelta class Document(models.Model): repository = models.CharField(max_length=512) docurl = models.CharField(max_length=512) user = models.CharField(blank=True, max_length=32) datetime = models.DateTimeField(blank=True, null=True)...
magicoder
python
You are tasked with creating a Python class that handles running tests and generating test files. Your class should handle potential errors that may occur during the test running process. The provided code snippet is a part of the class method that initializes the test runner and handles specific exceptions. Your task ...
```python import sys import time class TestRunner: def __init__(self, runner_class, args, logger): self.runner_class = runner_class self.args = args self.logger = logger self.runner = None def run_tests(self, sg): while True: try: self.runner...
magicoder
python
You are working on an image processing project and need to implement a function to create multiple ellipses on a given image. The function should take an input image and return the image with applied shadow mask, blur effect, and multiple ellipses. You are given a code snippet that initializes a shadow mask and calls ...
```python import numpy as np import cv2 class ImageProcessor: def apply_shadow_mask(image, blur_width, intensity, ellipse): shadow_mask = np.zeros(image.shape[:2], dtype=np.uint8) shadow_mask.fill(const.WHITE) shadow_mask = cv2.ellipse(shadow_mask, ellipse, const.BLACK, -1) blurred...
magicoder
python
You are tasked with implementing a program to manage a pharmacy's inventory using object-oriented programming in Python. The pharmacy sells various types of medications, each with different properties such as name, price, quantity, and expiration date. Your program should allow the user to perform operations such as ad...
```python class Medication: def __init__(self, name, price, quantity, expiration_date): self.name = name self.price = price self.quantity = quantity self.expiration_date = expiration_date def update_price(self, new_price): if new_price >= 0: self.price = new_...
magicoder
python
You are tasked with creating a Python program to manage different types of projects and their content using object-oriented programming and inheritance. Your program should include the following classes and their relationships: 1. `ProjectGrouperAdmin`: A base class for managing project groups. 2. `ProjectContent`: A ...
```python class ProjectGrouperAdmin: def __init__(self): pass # Add methods and attributes as needed for managing project groups class ProjectContent: def __init__(self): pass # Add methods and attributes as needed for managing project content class ArtProjectContent(ProjectContent):...
magicoder
python
You are tasked with creating a Swift function that efficiently organizes files into a directory structure based on their file extensions. The function should take a source directory path as input and organize the files within it into subdirectories based on their file extensions. If the source directory does not exist,...
```swift func organizeFilesByExtension(sourceDirectory: String) { let fileManager = FileManager.default var isDirectory: ObjCBool = false // Check if the source directory exists if !fileManager.fileExists(atPath: sourceDirectory, isDirectory: &isDirectory) { // Create the source directory if it...
magicoder
swift
You are tasked with implementing a configuration struct for a genetic algorithm in Rust. The struct, named `GeneticAlgorithmConfig`, contains several fields representing various parameters and settings for the genetic algorithm. Your goal is to define the struct and its associated default implementation method. The `G...
```rust struct GeneticAlgorithmConfig { max_generations: Option<u32>, max_time: Option<u32>, min_cv: Option<f64>, target_proximity: Option<f64>, heuristic: Option<HeuristicType>, context: Option<ContextType>, termination: Option<TerminationType>, strategy: Option<StrategyType>, heuri...
magicoder
rust
You are tasked with implementing a function to rotate a 2D pixel buffer 270 degrees clockwise. The pixel buffer is represented as a 1D array, and the rotation should be performed in-place. You are given the following code snippet as a starting point: ```rust /// Rotate buffer 270 degrees clockwise pub fn rotate270<C>...
```rust pub fn rotate270<C>(buffer: &mut PixelBuffer<C>, width: usize, height: usize) where C: Color { let mut result = vec![Default::default(); buffer.data().len()]; for x in 0..width { for y in 0..height { let x2 = height - y - 1; let y2 = x; result[(x2 + y2 * widt...
magicoder
rust
You are given a string representing a simple HTML tag. The tag can be an opening tag, a closing tag, or a self-closing tag. Your task is to write a function that determines whether the tag is valid or not. A valid tag must adhere to the following rules: 1. Opening tags must start with `<` followed by a valid tag name a...
```python import re def isValidHTMLTag(tag): opening_tag_pattern = r'<[a-zA-Z][a-zA-Z0-9_]*>' closing_tag_pattern = r'</[a-zA-Z][a-zA-Z0-9_]*>' self_closing_tag_pattern = r'<[a-zA-Z][a-zA-Z0-9_]*\/>' if re.match(opening_tag_pattern, tag): return True elif re.match(closing_tag_pattern, tag)...
magicoder
python
You are tasked with creating a Python function that simulates a memory management system. The function should calculate the amount of physical memory available on a system, given certain constraints and constants. You are provided with a code snippet that imports modules and defines constants and a function. The const...
```python import _psutil_osx # --- constants NUM_CPUS = _psutil_osx.get_num_cpus() TOTAL_PHYMEM = _psutil_osx.get_total_phymem() # --- functions def avail_phymem(): "Return the amount of physical memory available on the system, in bytes." # Assuming a simple memory management model where a certain percentag...
magicoder
python
You are tasked with implementing a custom class in Java that extends the `Single` class and implements the `Callable` interface. The class, `TraceContextCallableSingle`, is designed to handle asynchronous computation and tracing within a distributed system. It takes a generic type `T` and has three member variables: `s...
```java import io.reactivex.Single; import io.reactivex.SingleSource; import io.opentracing.CurrentTraceContext; import io.opentracing.TraceContext; import java.util.concurrent.Callable; final class TraceContextCallableSingle<T> extends Single<T> implements Callable<T> { final SingleSource<T> source; final Cu...
magicoder
java
You are tasked with implementing a function to calculate the intersection point of two line segments in a 2D plane. The line segments are defined by their start and end points. The function should return the coordinates of the intersection point if it exists, or indicate if the line segments are parallel or overlapping...
```python def calculate_intersection(xs1, ys1, xe1, ye1, xs2, ys2, xe2, ye2): # Calculate the slopes and y-intercepts of the two line segments m1, b1 = 0.0, 0.0 m2, b2 = 0.0, 0.0 if abs(xe1 - xs1) > PRECISION: m1 = (ye1 - ys1) / (xe1 - xs1) b1 = ys1 - m1 * xs1 else: m1 = 1 ...
magicoder
python
You are tasked with creating a notification management system for a web application. The system should allow users to push notifications and clear all notifications. Additionally, there should be a theme toggle feature to switch between light and dark themes. You are provided with a code snippet that includes a navigat...
```jsx import React, { useState } from 'react'; // Notification component const Notification = ({ message, dismissNotification }) => { return ( <div className="notification"> <span>{message}</span> <button onClick={dismissNotification}>Dismiss</button> </div> ); }; // NotificationManager compo...
magicoder
jsx
You are tasked with implementing a Binary Search Tree (BST) class in Python. Your task is to create a method to remove a specific element from the BST and then calculate the height (or maximum depth) of the resulting tree. You are given a code snippet that demonstrates the usage of the BST class. The snippet first rem...
```python class Node: def __init__(self, key): self.left = None self.right = None self.val = key class BST: def __init__(self): self.root = None def insert(self, root, key): if root is None: return Node(key) else: if root.val < key: ...
magicoder
python
You are tasked with creating a Python function that processes a given dataframe to generate two distinct subsets based on certain conditions. The function should take in a dataframe `df` and a boolean variable `validate`, indicating whether to create a validation dataframe. If `validate` is `False`, the second datafram...
```python import pandas as pd def process_dataframe(df, samples_per_group, validate): """ Process the input dataframe to generate two distinct subsets based on the specified conditions. Parameters ---------- df : pandas DataFrame Input dataframe containing the data samples_per_group : ...
magicoder
python
You are given an array of non-negative integers representing the heights of a series of vertical lines. The distance between any two vertical lines is the difference in their indices. Your task is to write a function `maxArea` to find the maximum area formed between two vertical lines by using the shorter line as the h...
```python def maxArea(height): left = 0 # Initialize left pointer right = len(height) - 1 # Initialize right pointer max_area = 0 # Initialize maximum area while left < right: # Calculate the area between the lines at left and right pointers area = min(height[left], height[right]) * ...
magicoder
python
You are tasked with implementing a custom iterator in Java that iterates over a collection of elements and filters out any elements that do not meet a specific condition. Your custom iterator should be able to iterate over a collection of integers and yield only the elements that are greater than a given threshold. Yo...
```java import java.util.Iterator; public class ThresholdIterator implements Iterator<Integer> { private Iterator<Integer> iterator; private int threshold; private Integer nextElement; public ThresholdIterator(Iterator<Integer> iterator, int threshold) { this.iterator = iterator; this....
magicoder
java
You are given a 3x3 Tic-Tac-Toe board represented as an array of strings. Each string represents a row of the board, and each character in the string represents a square on the board. The characters can be either "X", "O", or " " (empty). Your task is to write a function that determines whether the current board state...
```python def isValidTicTacToe(board): def check_winner(player): for i in range(3): if all(board[i][j] == player for j in range(3)): # Check rows return True if all(board[j][i] == player for j in range(3)): # Check columns return True if all(...
magicoder
python
You are tasked with developing a Python script to automate the process of uploading image files to an AWS S3 bucket. The script should accept command-line arguments for the image size, the name of the S3 bucket, and the prefix under which the images should be stored. Your task is to implement the script to handle these...
```python import argparse import os import boto3 def upload_images_to_s3(img_size, bucket_name, prefix): # Validate image size if not img_size.isdigit() or int(img_size) <= 0: raise ValueError("Image size must be a positive integer") # Validate bucket name if not bucket_name: raise Val...
magicoder
python
You are tasked with creating a Python program that processes a given text file and generates a report of word frequencies. The program should read a text file named "input.txt" and count the occurrences of each word in the file. The output should display each word along with the number of times it appears in the file. ...
```python try: # Read the content of the input file with open("input.txt", "r") as file: content = file.read() # Remove punctuation and convert to lowercase content = content.lower().replace('.', '').replace(',', '').replace('!', '').replace('?', '') # Split the content into words word...
magicoder
python
You are tasked with implementing a class hierarchy for managing different types of storage disks in a virtualization environment. The base class `Disk` represents a generic storage disk, and it has two subclasses: `DiskImage` and `DiskVolume`. The `DiskImage` class represents a storage disk that stores data in the form...
```java // Define the enumeration for DiskStorageType enum DiskStorageType { IMAGE, VOLUME } // Define the base class Disk class Disk { private String id; private DiskStorageType storageType; public Disk(String id, DiskStorageType storageType) { this.id = id; this.storageType = sto...
magicoder
java
You are tasked with creating a Python function that validates a list of IP addresses against a given IP network. The function should raise specific exceptions for different scenarios, and handle both IPv4 and IPv6 addresses. Write a function `validate_ip_addresses(ip_list, network_str)` that takes in a list of IP addr...
```python from ipaddress import ip_network, ip_address from .exceptions import IncorrectIPCount, UntrustedIP def validate_ip_addresses(ip_list, network_str): try: network = ip_network(network_str) except ValueError: raise ValueError("Invalid network format") if len(ip_list) > network.num_a...
magicoder
python
You are working on a Python project that involves handling search responses using different classes. The code snippet provided includes the definition of two classes, `CartQueryResponseWithFacets` and `CartMatrixResponseWithFacets`, which inherit from other classes. Your task is to understand the inheritance and initia...
The `CartQueryResponseWithFacets` and `CartMatrixResponseWithFacets` classes are examples of class inheritance in Python. They inherit from `CartAggsToFacetsMixin`, `BasicQueryResponseWithFacets`, and `BasicMatrixResponseWithFacets` classes, which implies that they inherit attributes and methods from these parent class...
magicoder
python
You are tasked with implementing a lazy property in Swift that represents a user interface element in an iOS app testing framework. The lazy property should be initialized with a closure that returns an `XCUIElement` representing a chip element in a user interface. The `XCUIElement` class is part of the XCTest framewor...
The `belgiumChip` lazy property can be implemented as follows: ```swift lazy var belgiumChip: XCUIElement = { let app = XCUIApplication() return app.buttons["belgiumChip"] }() ``` In this solution, the `belgiumChip` lazy property is initialized with a closure that returns an `XCUIElement` representing the chi...
magicoder
swift
You are tasked with implementing a Python function to calculate the posterior probability distribution for a given set of data points. The posterior probability distribution is based on a Gaussian likelihood function and a Gaussian prior distribution. The likelihood function is defined as $p(X|\mu, \sigma)$, where $X$ ...
```python import numpy as np def calculate_posterior(data_points, mu, beta, mu_0, beta_0): likelihood_precision = beta prior_precision = beta_0 evidence = 0 for x in data_points: evidence += np.exp(-0.5 * likelihood_precision * (x - mu)**2) evidence *= np.sqrt(2 * np.pi / likelihood_preci...
magicoder
python
You are given two non-negative integers represented as strings, `numberN` and `numberM`. Your task is to implement a function to add these two numbers and return the result as a string. Function Signature: `char* addStrings(char* numberN, char* numberM)` Input: - Two non-negative integers `numberN` and `numberM`, whe...
```c #include <stdio.h> #include <stdlib.h> #include <string.h> char* addStrings(char* numberN, char* numberM) { int n = strlen(numberN), m = strlen(numberM); int maxLen = (n > m) ? n : m; int carry = 0; char* result = (char*)malloc((maxLen + 2) * sizeof(char)); // +2 for potential carry and null termi...
magicoder
c
You are tasked with implementing a token management system for a security service. The system provides three operations: issue, cancel, and renew. Each operation is associated with a specific method that interacts with the underlying token management service. The code snippet provided shows a part of the token manageme...
```java public class UnsupportedOperation extends RuntimeException { public UnsupportedOperation(String operation) { super("Unsupported operation: " + operation); } } public class TokenManager { private IssueOperation issueOperation; private CancelOperation cancelOperation; private RenewOpe...
magicoder
java
You are tasked with implementing a custom lazy initialization mechanism for a data structure in Rust. The provided code snippet includes a partial implementation of a `Default` trait for a struct `Data`, where the `status` field is initialized using the `Lazy` type. Your goal is to complete the implementation of the la...
```rust use once_cell::sync::Lazy; const _NOT_ENTERED: fn() -> Status = || Status::Pending; enum Status { Pending, Initialized, Failed, } struct Data { status: Lazy<Status>, key: ink_primitives::Key, } impl Default for Data { fn default() -> Self { Self { status: Lazy::ne...
magicoder
rust
You are tasked with implementing a function that simulates a simple text-based game. The game involves a player navigating through a grid-based world, collecting treasures, and avoiding obstacles. The player's position and the layout of the world are represented by a 2D grid. The player can move up, down, left, or righ...
```c #include <stdio.h> #define GRID_SIZE 5 // Function to move the player within the grid int movePlayer(char grid[GRID_SIZE][GRID_SIZE], int* playerX, int* playerY, char direction) { int newX = *playerX; int newY = *playerY; // Update new position based on movement direction if (direction == 'U') {...
magicoder
c
You are tasked with implementing a unit test for a presenter in a mobile application. The presenter is responsible for setting up and coordinating the display of reward information to the user. The presenter interacts with a stubbed view and a reward service. The code snippet provided is a part of the unit test for the...
```swift // Import necessary testing libraries and modules // Define the unit test class for the presenter class PresenterUnitTest: XCTestCase { // Define the test method to verify the setup behavior func testSetup() { // Create a stub for the view let stub = MockView() //...
magicoder
swift
You are tasked with creating a Python function that simulates the removal of files and directories based on a given file path. The function should handle both verbose and non-verbose modes, printing appropriate messages and performing the removal operations accordingly. You are provided with a code snippet that demons...
```python from pathlib import Path def remove_file_or_directory(verbose, local_file, path): removed_paths = set() if verbose: print(f'Removing {local_file}') if path.is_file(): path.unlink(missing_ok=True) removed_paths.add(local_file) elif path.is_dir(): # Handle direct...
magicoder
python
You are tasked with implementing a multi-block component system in Java. The `IMultiBlockUnit` interface represents a unit within a multi-block structure and provides methods for interacting with the multi-block system. Your goal is to create a concrete implementation of the `IMultiBlockUnit` interface and a correspond...
The provided solution includes the implementation of the `MyMultiBlockUnit` class that fulfills the requirements of the `IMultiBlockUnit` interface. Additionally, a placeholder `MyMultiBlockType` class is defined as an extension of the `MultiBlockType` class, allowing for the specification of the multi-block structure ...
magicoder
python
You are working on a project that involves training and evaluating a machine learning model using PyTorch. The given code snippet is part of a larger script that loads a trained model, prints a message indicating the successful loading of the model, and then proceeds to evaluate the model's performance on a dataset. Y...
```python import torch def perform_evaluation(model, eval_checkpoint_path, args, eval_dataset, eval_loader, model_save_path, device): # Load the trained model from the checkpoint path model.load_state_dict(torch.load(eval_checkpoint_path)) print('Model loaded from', eval_checkpoint_path) # Evaluate th...
magicoder
python
You are tasked with implementing a binary search tree (BST) in Python. A binary search tree is a binary tree in which for each node, the left child is less than the parent and the right child is greater than the parent. You need to implement the deletion operation for the BST. You are given a code snippet that handles...
```python class TreeNode: def __init__(self, key): self.key = key self.left = None self.right = None def deleteNode(root, key): if root is None: return root if key < root.key: root.left = deleteNode(root.left, key) elif key > root.key: root.right = delet...
magicoder
python
You are tasked with creating a custom exception hierarchy for a Python library called "Arequests" that handles various errors related to making HTTP requests. The provided code snippet shows the initial definition of a base exception class `ArequestsError` with a docstring. Your task is to extend this exception hierar...
```python class ArequestsError(Exception): """Basic exception for errors raised by Arequests""" pass class TimeoutError(ArequestsError): """Exception raised when a request times out""" pass class ConnectionError(ArequestsError): """Exception raised when a connection error occurs""" pass def m...
magicoder
python
You are given an array of integers `nums`, which is sorted in non-decreasing order. Your task is to find all unique triplets in the array that sum up to zero and return them as a list of lists. Each triplet should be in non-decreasing order. For example, given the input `nums = [-1, 0, 1, 2, -1, -4]`, the output shoul...
```python from typing import List def threeSum(nums: List[int]) -> List[List[int]]: nums.sort() res = [] for i in range(len(nums) - 2): if i > 0 and nums[i - 1] == nums[i]: continue l, r = i + 1, len(nums) - 1 while l < r: s = nums[i] + nums[l] + nums[r] ...
magicoder
python
You are tasked with implementing a PositionController class for a drone simulator. The PositionController is responsible for controlling the drone's position based on a given set of commands. The mission_setup method is used to set up the mission planner with a flight plan, and the controller is initialized with the dr...
```python class PositionController: def __init__(self, drone, commands, verbose=False): self.drone = drone self.commands = commands self.verbose = verbose def mission_setup(self, planner): import quadrotor.command as cmd # Assume the flight plan is set up here def e...
magicoder
python
You are tasked with creating a Python program to analyze and visualize polynomial functions. The program should take user input for the coefficients of a polynomial function, evaluate the function at various points, and then plot the resulting curve using matplotlib. Your program should perform the following steps: 1....
```python import numpy as np import matplotlib.pyplot as plt def main(): degree = int(input("Enter the degree of the polynomial function: ")) coefficients = [] for i in range(degree, -1, -1): coeff = float(input(f"Enter the coefficient for x^{i}: ")) coefficients.append(coeff) x_vals =...
magicoder
python
You are tasked with creating a script to automate the transfer of configuration files from a local machine to a remote server using the `scp` command. The script should be able to handle multiple configuration files and transfer them to the specified remote server. You are given a code snippet from a shell script that...
```bash #!/bin/bash # Check if the required parameters are provided if [ $# -lt 3 ]; then echo "Usage: $0 <local_file1> <local_file2> ... <remote_user>@<remote_host>:<remote_directory>" exit 1 fi # Extract the remote user, host, and directory from the last parameter remote_params=(${!#}) remote_user_host=$(echo $...
magicoder
shell
You are tasked with creating a PHP class that establishes a connection to a message broker using the STOMP protocol. The provided code snippet is a partial configuration array for the STOMP connection. Your task is to complete the PHP class by implementing the connection logic and error handling. Your PHP class should...
```php <?php class StompConnection { private $config; public function __construct($config) { $this->config = $config; } public function connect() { $stomp = new Stomp("tcp://{$this->config['host']}:{$this->config['port']}"); $connected = $stomp->connect($this->config['l...
magicoder
php
You are tasked with creating a program to process geographical coordinates and calculate the distance between two points on the Earth's surface. The program should take latitude and longitude coordinates as input and output the distance between the two points in kilometers. You are provided with the Haversine formula t...
```python import math def calculateDistance(lat1, lon1, lat2, lon2): R = 6371 # Radius of the Earth in kilometers lat1_rad = math.radians(lat1) lon1_rad = math.radians(lon1) lat2_rad = math.radians(lat2) lon2_rad = math.radians(lon2) dlat = lat2_rad - lat1_rad dlon = lon2_rad - lon1_rad ...
magicoder
python
You are tasked with creating a function that processes a listing of resources and returns a specific subset of data in a JSON format. The given code snippet is a part of a Laravel controller, and it contains two methods: `index()` and `index22()`. Your task is to complete the `index22()` method to achieve the same func...
```php public function index22() { $user = DB::table('presupuesto_unidads') ->select('id_unidad', 'presupuesto', 'gestion', 'id') ->where('visible', '=', '1') ->get(); return response()->json($user, 201); } ``` In the solution, the `index22()` method uses the Laravel Query Builder to re...
magicoder
php
You are tasked with implementing a function that processes a list of URLs and extracts the domain names from each URL. The domain name is defined as the substring between the protocol (e.g., "http://", "https://") and the first subsequent slash ("/"). If the URL does not contain a protocol or a subsequent slash, the en...
```python import re def extract_domain_names(urls): domain_names = [] for url in urls: match = re.search(r'(?<=://)([^/]+)|([^/]+)', url) if match: domain_names.append(match.group(0)) return domain_names ``` The `extract_domain_names` function uses the `re` module to perform a ...
magicoder
python
You are tasked with implementing a class that manages spatial and temporal processing for a video analysis system. The class should handle the initialization of spatial and temporal components based on certain conditions and parameters. Your task is to complete the implementation of the `VideoProcessor` class by fillin...
```python class VideoProcessor: def __init__(self, use_spatial, spatial_train, spatial_filename, use_pipeline, ditrl_pipeline_train, pipeline_filename, return_iad, return_vee, use_gcn, backbone_id): self.use_spatial = use_spatial self.spatial_train = spatial_train self.spati...
magicoder
python
You are tasked with implementing a resource management system that provides methods for using, destroying, draining, and clearing resources. The system should support asynchronous operations using promises. You are given a TypeScript-like code snippet that outlines the interface for the resource management system: ```...
```typescript class ResourceManager<T> { private resources: T[] = []; destroy(resource: T): void { const index = this.resources.indexOf(resource); if (index !== -1) { this.resources.splice(index, 1); } } drain(): PromiseLike<undefined> { return new Promise((resolve) => { // Simulat...
magicoder
typescript
You are tasked with creating a Python program that captures screenshots when the user clicks the mouse button. Your program should utilize the `pyautogui` and `pynput` libraries to achieve this functionality. The `pyautogui` library provides the ability to take screenshots, while the `pynput` library allows for monitor...
```python import pyautogui from pynput.mouse import Listener from datetime import datetime def clicou(x, y, botao, pressionado): if pressionado: im1 = pyautogui.screenshot() im1.save(f'{datetime.now()}.png') listener = Listener(on_click=clicou) listener.start() listener.join() ``` In the solution,...
magicoder
python
You are tasked with creating a PHP function that securely retrieves the username from a session variable and performs a specific action based on the presence of the username. Your function should handle potential security vulnerabilities and ensure that the username is properly validated before further processing. Wri...
```php function processUsername() { session_start(); // Start the session if not already started if (isset($_SESSION['uname'])) { $referrer = $_SESSION['uname']; // Perform specific action based on the presence of the username // For example, you can redirect the user to a specific page...
magicoder
php
You are tasked with implementing a method to add a discussion post to a forum. The method should take a `DiscussPost` object as a parameter and perform certain operations on the post before adding it to the forum. The `DiscussPost` class has a `title` attribute, which needs to be processed to escape HTML tags before be...
```java public class DiscussPostHandler { /** * Adds a discussion post to the forum after escaping HTML tags in the post's title. * * @param post The discussion post to be added * @return The ID of the added post * @throws IllegalArgumentException if the input post is null */ publi...
magicoder
java
You are tasked with implementing a Python class that manages a production system for a factory. The class, named `ProductionManager`, is responsible for handling the production of various items and managing the entry limit attributes. The class has a method `produces` that returns a list of items produced and a method ...
```python class ProductionManager: def __init__(self, config): self.entry_limit_attrs = config.get('entry_limit_attrs') self.logger = logging.getLogger() def produces(self, name_schema_id_list=None): """ Return list of items produced """ return PRODUCES def ...
magicoder
python
You are tasked with creating a script to merge multiple PDF files into a single PDF document. The script should take input from a file containing a list of file paths and a folder name, and then use the `wkhtmltopdf` and `pdftk` commands to merge the PDF files. Your script should perform the following steps: 1. Read e...
```bash #!/bin/bash # Define input file, folder name, and counter input="input.txt" foldername="output_folder" COUNTER=1 # Initialize PDFString variable PDFString="" # Read each line from the input file and convert PDF files while IFS= read -r line do wkhtmltopdf "$line" "./$foldername/$COUNTER.pdf" PDFStrin...
magicoder
shell
You are tasked with implementing a web scraping and crawling module in Python. The module should provide three functions: `scrape_by_url`, `crawl_by_url`, and `crawl_by_keyword`. The `scrape_by_url` function should retrieve the content of a web page given its URL, the `crawl_by_url` function should traverse a website s...
```python import requests from bs4 import BeautifulSoup from urllib.parse import urljoin def scrape_by_url(url): try: response = requests.get(url) if response.status_code == 200: return response.text else: return "" except requests.RequestException: retur...
magicoder
python
You are tasked with creating a function that processes a report for taxi services based on a given request. The function should take the request data as input and perform specific operations to generate the report. The request data will contain information related to taxi services, and the function needs to process thi...
```php public function reportePorCorteTaxi(Request $request){ // Extracting relevant data from the request $requestData = $request->all(); // Perform necessary data processing and report generation logic here // Example: Calculate total earnings, number of rides, average distance, etc. // Generate...
magicoder
php
You are tasked with implementing a data transfer object (DTO) for binary data. The DTO should support writing the binary content to a provided buffer asynchronously. Your task is to create a class that fulfills the requirements of the IDataTransferObject interface and passes the provided unit tests. The IDataTransferO...
```csharp using System; using System.Buffers; using System.Threading.Tasks; public interface IDataTransferObject { long Length { get; } bool IsReusable { get; } Task WriteToAsync(IBufferWriter<byte> writer); } public class BinaryTransferObject : IDataTransferObject { private readonly byte[] _content; ...
magicoder
csharp
You are tasked with implementing a function to calculate the gradient penalty for a Wasserstein GAN (Generative Adversarial Network). In a Wasserstein GAN, the gradient penalty is used to enforce the Lipschitz constraint on the discriminator network. The provided code snippet is a part of the gradient penalty calculati...
```python import torch def calculate_gradient_penalty(discriminator, interpolates, device, gamma): # Calculate the discriminator output for the interpolated samples disc_interpolates = discriminator(interpolates) # Compute the gradients of the discriminator output w.r.t. the interpolated samples gradi...
magicoder
python
You are tasked with implementing a service for a superhero simulator application. The service will be responsible for handling various functionalities related to superheroes, such as retrieving hero data, displaying messages, managing application state, handling routing, shortening URLs, managing the clipboard, and dis...
```typescript import { Injectable } from '@angular/core'; import { HeroesService } from './heroes.service'; import { NzMessageService, NzNotificationService } from 'ng-zorro-antd'; import { Store } from '@ngrx/store'; import { SimulatorState } from './simulator.state'; import { ActivatedRoute, Router } from '@angular/r...
magicoder
typescript
You are tasked with creating a Python script that automates the release process for a software project. The release process involves the following steps: 1. Clean up the existing build and distribution directories by removing them if they exist. 2. Use the `python -m build` command to create a new distribution of the ...
```python import os import subprocess import platform def clean_directories(): if os.path.exists('build'): os.system('rm -rf build') if os.path.exists('dist'): os.system('rm -rf dist') def create_distribution(): subprocess.run(['python', '-m', 'build'], check=True) def upload_distribution...
magicoder
python
You are tasked with implementing a function that processes and modifies labels based on specific rules. The function takes a label and a Y-axis option as input and applies the corresponding transformation to the label based on the Y-axis option. The Y-axis options are represented by an enumeration called `YAxisOptions`...
```typescript enum YAxisOptions { TIMES_LOWER_REF_VALUE, TIMES_UPPER_REF_VALUE } function processLabel(label: string, yAxisOption: YAxisOptions): string { switch (yAxisOption) { case YAxisOptions.TIMES_LOWER_REF_VALUE: const lowerRefPattern = /pattern/; // Replace 'pattern' with the spe...
magicoder
typescript
You are working on a Python application that interacts with a database using the `cursor` object. The `cursor.execute()` method is used to execute SQL queries. However, you want to ensure that the application handles potential errors that may arise during the execution of the query. Write a function `execute_query_saf...
```python from typing import Optional, List, Tuple, Any def execute_query_safe(cursor, query) -> Optional[List[Tuple[Any, ...]]]: try: cursor.execute(query) result_set = cursor.fetchall() return result_set except Exception as e: print(f"Error executing query: {e}") retur...
magicoder
python