query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with implementing a custom expansion method for generating integer ranges in a scripting language. The scripting language uses a Java-like syntax and allows for the creation of custom expansion methods for various functionalities. Your task is to create a static expansion method that generates an intege...
```java @Document("vanilla/api/loot/IntRange") @NativeTypeRegistration(value = IntRange.class, zenCodeName = "crafttweaker.api.loot.IntRange") public final class ExpandIntRange { @ZenCodeType.StaticExpansionMethod public static IntRange exactly(final int value) { return IntRange.exact(value); // Im...
magicoder
java
You are tasked with implementing a notification system for a social media platform. The platform supports two types of users: regular users and pages. Additionally, there are three types of notifications: fulfillment, needs, and repost. The notification system needs to be designed to efficiently handle the generation a...
```javascript class NotificationSystem { constructor() { this.subscribers = { USER: {}, PAGE: {}, }; } registerUserOrPage(type, id) { if (!this.subscribers[type][id]) { this.subscribers[type][id] = new Set(); } } subscribeToNotificationType(type, id, notificationType) { ...
magicoder
javascript
You are tasked with creating a program that simulates a simple task scheduling system. The system should be able to handle tasks with different levels of priority and execute them based on their priority. You are given a code snippet that sets the default quality of service (QoS) for task dispatching to `DispatchQoS....
```python import queue import time class Task: def __init__(self, priority, execution_time): self.priority = priority self.execution_time = execution_time def __lt__(self, other): return self.priority < other.priority class TaskScheduler: def __init__(self): self.high_prio...
magicoder
python
You are tasked with creating a Livewire component for a web application that displays a paginated list of orders with the ability to search and sort the data. The Livewire component has three public properties: `$sortField`, `$sortAsc`, and `$search`. The `render` method of the component retrieves the orders from the d...
```php public function sortBy($field) { if ($this->sortField === $field) { $this->sortAsc = !$this->sortAsc; // Toggle the sorting order if the same field is clicked again } else { $this->sortField = $field; $this->sortAsc = true; // Default to ascending order when a new field is selecte...
magicoder
php
You are tasked with creating a Java class that validates OAuth tokens for a web application. The class should implement a method to validate the access token received from the client against the authorization server's public keys. The public keys are retrieved from the authorization server's endpoint and are used to ve...
```java import java.security.KeyFactory; import java.security.PublicKey; import java.security.Signature; import java.security.spec.X509EncodedKeySpec; import java.util.Base64; import java.util.Set; import org.italiangrid.storm.webdav.config.OAuthProperties.AuthorizationServer; public class OAuthTokenValidator { p...
magicoder
java
You are tasked with implementing a stream manager class that handles the acquisition and release of streams for different protocol versions. The stream manager should enforce a maximum number of streams that can be acquired and ensure that streams are acquired and released correctly. You are given a code snippet that ...
```cpp #include <iostream> #include <vector> #include <stdexcept> template <typename T> class StreamManager { private: std::vector<std::vector<T>> streams; // Vector of vectors to store streams for each protocol version public: explicit StreamManager(const std::vector<size_t>& maxStreamsPerVersion) { ...
magicoder
cpp
You are tasked with implementing a simple event handling system in Swift. Your goal is to create a protocol that defines the structure for an event coordinator, and then implement a class that conforms to this protocol to handle and propagate events. You need to define a protocol called `EventCoordinator` with the fol...
```swift // Define the EventCoordinator protocol protocol EventCoordinator { func handleEvent(_ event: String) var nextCoordinator: EventCoordinator? { get set } } // Implement the SimpleEventCoordinator class conforming to EventCoordinator class SimpleEventCoordinator: EventCoordinator { var nextCoordinat...
magicoder
swift
You are tasked with implementing a class hierarchy for representing geopolitical locations in the context of emergency data exchange. The provided code snippet shows the declaration of an abstract class `EDXLGeoPoliticalLocation` that extends `EDXLLocationType` and is marked as serializable. Your task is to design and...
```csharp using System; [Serializable] public abstract class EDXLLocationType { // Common properties and methods for all location types } [Serializable] public abstract class EDXLGeoPoliticalLocation : EDXLLocationType { public abstract string LocationName { get; set; } public abstract void DisplayLocatio...
magicoder
csharp
You are tasked with implementing a Python class that manages access control lists (ACLs) for different types of resources. The provided code snippet includes a custom ACL class and a ReadAcl class with predefined ACL instances for public, private, and custom algorithms. Your task is to create a Python class called Acl...
```python class AclType: public = "public" private = "private" my_algos = "my_algos" class Acl: def __init__(self, acl_type): if acl_type not in [AclType.public, AclType.private, AclType.my_algos]: raise ValueError('Invalid ACL type %s' % acl_type) self.acl_type = acl_type ...
magicoder
python
You are tasked with creating a program that simulates a simple command-line interface for a file system. Your program should support basic commands such as `cd` (change directory), `ls` (list files), and `pwd` (print working directory). The file system is represented as a tree structure, where each node represents a di...
```python class TreeNode: def __init__(self, name): self.name = name self.children = [] def cd_command(root, path): if path.startswith('/'): current = root path = path[1:] else: current = root directories = path.split('/') for directory in directories: ...
magicoder
python
You are tasked with creating a function that simulates a music playlist generator. The function should randomly select a song from a given artist's collection. You are provided with two helper functions: `get_random_artist_keys(max_artists)` and `get_random_post_keys(max_posts)`. The former function returns a list of r...
```python import random as rand def get_random_song(): """ Returns a random song from a random artist's collection. If no artists or songs are available, returns None. """ def get_random_artist_keys(max_artists): # Simulated implementation to generate random artist keys return [f"Ar...
magicoder
python
You are tasked with implementing a Python function that processes configuration arguments and updates a configuration dictionary based on certain conditions. The function should handle the following requirements: - Iterate through pairs of arguments and prepend flags. - For each key-value pair in the arguments, perfor...
```python def process_config_args(args, rc_config): sequence_parameters = {'param1': 'description1', 'param2': 'description2'} # Replace with actual sequence parameters for arg, prepend in zip((args.prepend, args.append), (True, False)): for key, item in arg: if key == 'channels' and key n...
magicoder
python
You are tasked with implementing a custom command execution system for a text editor. The text editor provides an API with a `run_command` method that takes a command name as a string and executes the corresponding command. However, the text editor has a limitation that it does not support executing external system com...
```python import subprocess def execute_command(command: str) -> str: if command == "exit": sublime.run_command('exit') return "Command executed successfully" else: try: output = subprocess.check_output(command, shell=True, text=True) return output except...
magicoder
python
You are tasked with creating a Python programming problem related to database management and object-relational mapping (ORM). You are given the following code snippet as inspiration: ```python def createTable(self): models.Base.metadata.create_all(engine) ``` Using this as a starting point, create a problem that...
One possible solution is to ask the students to create a Python class that represents a simple database table using SQLAlchemy ORM. The class should include attributes representing columns in the database table, and a method to create the table in the database. Here's an example solution: ```python from sqlalchemy im...
magicoder
python
You are tasked with implementing a blockchain data structure for a new cryptocurrency. The blockchain consists of three types of blocks: Entry Credit Blocks, Factoid Blocks, and Admin Blocks. Each block contains a header and specific data associated with its type. The code snippet provided is a part of a method that co...
```python class Block: def __init__(self, type, height, entry_credit_block=None, factoid_block=None, admin_block=None): self.type = type self.height = height self.entry_credit_block = entry_credit_block self.factoid_block = factoid_block self.admin_block = admin_block def co...
magicoder
python
You are given a function `isPalindrome` that takes a string as input and returns `true` if the string is a palindrome, and `false` otherwise. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward, ignoring spaces, punctuation, and capitalization. The provided ...
```java public boolean isPalindrome(String s) { s = s.replaceAll("[^a-zA-Z0-9]", "").toLowerCase(); // Remove non-alphanumeric characters and convert to lowercase int left = 0, right = s.length() - 1; while (left < right) { if (s.charAt(left) != s.charAt(right)) { return false; // If cha...
magicoder
java
You are given a function `divisible_count(x, y, k)` that takes in three integers `x`, `y`, and `k`. The function is defined as follows: ```python def divisible_count(x, y, k): return (k * (y // k + 1) - x) // k ``` The function is designed to calculate the count of integers within the range `[x, y]` (inclusive) t...
```python def count_divisible_numbers(x, y, k): if x % k == 0: return (y - x) // k + 1 else: return (y // k + 1) - (x // k + 1) ``` The `count_divisible_numbers` function first checks if `x` is divisible by `k`. If it is, then the count of divisible numbers within the range `[x, y]` is simply `...
magicoder
python
You are working on a deployment automation script for a distributed system. The script is responsible for stopping all services, checking out the latest code, deploying the updated code, and then starting all services. The script uses environment variables to reference the base directory and contains a set of commands ...
```python def generateDeploymentScript(baseDir: str) -> str: deploymentScript = f"{baseDir}/stopAll.sh\n" deploymentScript += f"{baseDir}/checkoutAndDeployNode.sh\n" deploymentScript += f"{baseDir}/startAll.sh\n" deploymentScript += "echo \"---------------------------------------\"\n" deploymentScri...
magicoder
python
You are given a function `countBits` that takes an integer `num` as input. The function is expected to return an array `dp` of size `num+1`, where `dp[i]` represents the number of 1 bits in the binary representation of `i` for all `0 <= i <= num`. The function `countBits` is implemented as follows: ``` def countBits(n...
```python from typing import List def countBits_alternative(num: int) -> List[int]: dp = [0] * (num+1) for i in range(num+1): dp[i] = bin(i).count('1') return dp ``` The `countBits_alternative` function initializes an array `dp` of size `num+1` with all elements set to 0. It then iterates through ...
magicoder
python
You are tasked with implementing a Python class that utilizes the `smtplib` library to send email notifications. The class, `MailChannel`, should inherit from the `CommChannel` class and implement the necessary methods to send emails. The `CommChannel` class is assumed to have a method `send_notification` that takes a ...
```python class MailChannel(CommChannel): """ Class to send notifications using mail. """ def __init__(self, sender_email, sender_password): self.sender_email = sender_email self.sender_password = sender_password def send_notification(self, recipient_email, subject, message): """Se...
magicoder
python
You are given a file containing a series of 32-bit hexadecimal values. Each value represents a memory address. Your task is to write a program that reads the file, identifies the memory addresses, and calculates the total memory space used by these addresses. Write a function `calculateMemorySpace(file)` that takes a ...
```python def calculateMemorySpace(file): total_space = 0 with open(file, 'r') as f: for line in f: if line.strip().startswith(".4byte"): address = int(line.strip().split()[1], 16) total_space += 4 # Each address occupies 4 bytes return total_space ``` Th...
magicoder
python
You are working on a machine learning framework and need to implement a function for materialization trace information. The materialization trace information is used to track the operations and inputs involved in the lazy evaluation of tensors. You are given a code snippet that includes a part of the implementation for...
```swift // Define the data structure for LazyTensorOperation struct LazyTensorOperation { // Define properties and methods as per the requirements } // Define the data structure for LazyTensorTrace struct LazyTensorTrace { // Define properties and methods as per the requirements } // Define the protocol for ...
magicoder
swift
You are tasked with implementing a booking system for a service-based business. The system should allow customers to book various services and manage their bookings. To achieve this, you need to create a class that represents a service booking and its associated calendar. Your task is to implement a PHP class that mod...
```php class ServiceBooking { public function servicesBooking() { return $this->belongsTo(ServiceBooking::class, 'service_booking_id', 'id'); } public function lapCalendar() { // Implement calendar functionality associated with the service booking // Example: Fetch and manag...
magicoder
php
You are tasked with implementing a virtual class for managing options in a graphics application. The class `rs2_options` is an abstract base class that provides an interface for accessing and manipulating options. Your goal is to create a concrete derived class that implements the pure virtual function `GetOptionsPoint...
```cpp #include <iostream> #include <string> #include <vector> // Abstract base class for managing options class rs2_options { public: virtual ~rs2_options() {} virtual void* GetOptionsPointer() = 0; }; // Concrete derived class for managing graphics options class GraphicsOptions : public rs2_options { privat...
magicoder
cpp
You are tasked with implementing a Python class that performs a series of transformations on a stream of data. The class should inherit from three different parent classes: `Bolt`, `StatefulComponent`, and `StreamletBoltBase`. The `Bolt` class represents a component in a stream processing topology, the `StatefulCompone...
```python from abc import ABC, abstractmethod class Bolt(ABC): @abstractmethod def process(self, data): pass class StatefulComponent(ABC): @abstractmethod def save_state(self): pass @abstractmethod def restore_state(self, state): pass class StreamletBoltBase(ABC): ...
magicoder
python
You are tasked with implementing a custom loss function for a reinforcement learning algorithm. The given code snippet is part of a larger codebase for a deep reinforcement learning agent using the DDPG (Deep Deterministic Policy Gradient) algorithm. Your task is to complete the implementation of the custom loss functi...
```python # Import necessary libraries and modules import torch import torch.optim as optim class DDPGAgent: def __init__(self, ...): # Other initialization parameters # Initialize other parameters and attributes def custom_loss_function(self, custom_loss_param): if self.lagrangian_custom_los...
magicoder
python
You are tasked with creating a program to simulate a simple agent navigating a grid-based environment. The agent can move in four directions: up, down, left, and right. The goal is to implement a function that calculates the average number of steps required for the agent to reach a terminal state from multiple simulati...
```python import random class Agent: def __init__(self, grid_size): self.grid_size = grid_size self.position = (0, 0) # Agent starts at the top-left corner of the grid def move(self, direction): x, y = self.position if direction == "up" and y > 0: self.position = (...
magicoder
python
You are tasked with implementing a read-write lock mechanism using Swift. A read-write lock allows multiple readers to access a resource simultaneously, but only one writer can access the resource at a time, and no reader can access the resource while it is being written to. The code snippet provided is a guard conditi...
```swift class ReadWriteLock { private var readCount = 0 private var writeCount = 0 private let lockQueue = DispatchQueue(label: "com.example.readWriteLock") func startRead() { lockQueue.sync { guard writeCount == 0 else { lockQueue.sync { readCou...
magicoder
swift
You are tasked with implementing a custom resource class for an admin view in a web application. The `MyAdminView` class needs to handle various administrative tasks and provide endpoints for managing user data. Your task is to extend the `Resource` class and implement the necessary methods to achieve the required func...
```python from flask_restful import Resource, reqparse class MyAdminView(Resource): def __init__(self): self.users = [] # Placeholder for user data def get(self): return {'users': self.users}, 200 def post(self): parser = reqparse.RequestParser() parser.add_argument('user...
magicoder
python
You are tasked with implementing a function that evaluates a Gaussian Process (GP) at given test points. The GP is defined by a method `eval_at_fidel` within a class, which takes in test points `ZZ_test` and `XX_test`, and additional arguments `*args` and `**kwargs`. The function `eval_at_fidel` calls another method `g...
```python def eval_at_fidel(self, ZZ_test, XX_test, *args, **kwargs): """ Evaluates the GP at [ZZ_test, XX_test]. Read eval in gp_core.GP for more details. """ ZX_test = self.get_ZX_from_ZZ_XX(ZZ_test, XX_test) # Transform test points return self.eval(ZX_test, *args, **kwargs) # Evaluate GP at transfo...
magicoder
python
You are tasked with implementing a C++ function for interpolating values on Lie groups using the Sophus library. The Sophus library provides C++ implementations of Lie groups, Lie algebras, and exponential and logarithmic mapping. In this problem, you will focus on implementing interpolation for Lie groups using the So...
```cpp template <class Group, class Scalar> Group interpolate(const Group& p, const Group& q, const Scalar& t) { // Perform interpolation using the Sophus library return p * Group::exp((q.inverse() * p).log() * t); } ``` In the solution, the `interpolate` function takes the start and end points `p` and `q`, and...
magicoder
cpp
You are working on a project that involves encrypting and hiding a secret message within an image. Your task is to write a Python program that takes a plaintext message, encrypts it using the Advanced Encryption Standard (AES) algorithm in Cipher Block Chaining (CBC) mode, and then embeds the encrypted message into an ...
```python from Crypto.Cipher import AES from Crypto import Random import binascii from PIL import Image import stepic # Function to pad the plaintext to a multiple of 16 bytes def pad(text): return text + (16 - len(text) % 16) * chr(16 - len(text) % 16) # Function to encrypt the plaintext using AES in CBC mode de...
magicoder
python
You are given a class `Solution` with a method `helper` that takes two parameters: a string `s` and a set of words `wordDict`. The method is intended to return a boolean value indicating whether the string `s` can be segmented into a space-separated sequence of one or more dictionary words. The method should use the wo...
```python class Solution: def __init__(self, wordDict): self.wordDict = wordDict def helper(self, s, wordDict): if not s: return True # Base case: empty string can be segmented for i in range(1, len(s) + 1): if s[:i] in self.wordDict and self.helper(s[i:], self....
magicoder
python
You are tasked with implementing a simplified version of a shader program for rendering triangles. The provided code snippet demonstrates the usage of a `ShaderProgram` class to set a buffer of triangle indexes, render the triangles using indexed rendering, and then unbind the shader program. Your task is to create a ...
```java // ShaderProgram class for rendering triangles public class ShaderProgram { private int[] buffer; // Buffer for triangle indexes // Set the buffer of triangle indexes public void SetBuffer(int[] indexes) { this.buffer = indexes; } // Render triangles based on the specified renderin...
magicoder
java
You are tasked with implementing a Unicode range tracking system. The given code snippet is a part of a function that sets a bit in a Unicode range bitset based on the Unicode code point (cp) provided. The function hb_get_unicode_range_bit(cp) returns the bit position for the given Unicode code point. The Unicode range...
```cpp void setUnicodeRangeBit(unsigned int cp, std::bitset<128>& ulUnicodeRange) { unsigned int bit = hb_get_unicode_range_bit(cp); if (bit < 128) { unsigned int block = bit / 32; unsigned int bit_in_block = bit % 32; unsigned int mask = 1 << bit_in_block; ulUnicodeRange[block] ...
magicoder
cpp
You are tasked with creating a Python function that simulates a simple asynchronous task scheduler for a home automation system. The system uses OpenPeerPower (OPP) as its platform and interacts with a device called "Rituals Perfume Genie" to manage perfume diffusion in a smart home. The provided code snippet initializ...
```python import asyncio from datetime import timedelta from typing import List from openpeerpower.core import OpenPeerPower from openpeerpower.config_entries import ConfigEntry UPDATE_INTERVAL = timedelta(seconds=30) async def async_setup_entry(opp: OpenPeerPower, entry: ConfigEntry): """Set up Rituals Perfume G...
magicoder
python
You are tasked with implementing a Swift class that manages a list of transformations and provides functionality for refreshing the list. The class should handle the initialization of a view model and the setup of a header refreshing delegate. You are given a code snippet from a Swift class that initializes a view mod...
```swift class TransformListViewController: UIViewController, HeaderRefreshingDelegate { var viewModel: TransformListViewModel! var transformations: [Transformation] = [] override func awakeFromNib() { super.awakeFromNib() viewModel = TransformListViewModel(request: TransformListRequest(), ...
magicoder
swift
You are tasked with creating a Python unit test for a class that imports and processes JSON data from a specified endpoint. The class `HandleJsonData` is responsible for importing JSON data from a given URL and extracting specific keys from the JSON objects. The test case needs to verify that the class correctly handle...
```python class TestJsonData(unittest.TestCase): @requests_mock.Mocker() def test_import_json_data_success(self, m): # Mock the HTTP request and response m.get(endpoint, text=response_request) # Create an instance of HandleJsonData handle_json = HandleJsonData() # Impor...
magicoder
python
You are tasked with implementing a function that checks the validity of a given password based on the following criteria: 1. The password must be at least 8 characters long. 2. The password must contain at least one uppercase letter, one lowercase letter, one digit, and one special character from the set {!, @, #, $, %...
```javascript function validatePassword(password) { // Check if the password length is at least 8 characters if (password.length < 8) { return false; } // Check if the password contains at least one uppercase letter, one lowercase letter, one digit, and one special character const uppercase...
magicoder
javascript
You are tasked with implementing a sorting algorithm for a collection of reports based on their report dates. Each report has a title, content, and a report date. The reports are stored in an array of objects, and you need to sort them in descending order based on their report dates. You should implement a function `so...
```javascript function sortReportsByDate(reports) { return reports.slice().sort((a, b) => b.report_date - a.report_date); } const reports = [ { title: "Monthly Sales Report", content: "Summary of sales for the month of January", report_date: new Date('2022-01-31') }, { t...
magicoder
javascript
You are tasked with implementing a coroutine-based stack overflow detection mechanism in a programming language of your choice. A coroutine is a specialized version of a subroutine, designed for cooperative multitasking, where the execution of a coroutine can be paused and resumed at specific points. Stack overflow occ...
To solve this problem, you can implement a coroutine-based stack overflow detection mechanism using a language that supports coroutines and error handling, such as Python. Here's a sample solution using Python's generators and exception handling: ```python import sys class StackOverflowError(Exception): pass def...
magicoder
python
You are tasked with creating a Python class that manages a key vault system. The key vault manager should be able to handle various errors that may occur during its operation. Your task is to implement the `ERROR_KEY_VAULTS` class, which is a subclass of `ERROR_BASE`. The `ERROR_KEY_VAULTS` class should have attributes...
```python class ERROR_BASE: pass # Assume the base error class is implemented elsewhere class ERROR_KEY_VAULTS(ERROR_BASE): status_code = 'INTERNAL' message = 'KeyVault manager is failed to get sub resources. {field}.' def __init__(self, field): self.message = self.message.format(field=field)...
magicoder
python
You are given a scenario where a teacher wants to choose a leader from each group of students. The teacher wants to know the number of ways he can choose the group leaders from all the groups. Your task is to write a program to calculate the number of ways and print the answer modulo 10^9+7. Input: The first line cons...
```python def countGroupLeaderWays(N, relationships): MOD = 10**9 + 7 adj_list = {i: [] for i in range(1, N+1)} for A, B in relationships: adj_list[A].append(B) adj_list[B].append(A) visited = [False] * (N+1) ways = 1 for i in range(1, N+1): if not visited[i]: ...
magicoder
python
You are tasked with implementing a payment authorization system using the Apple Pay framework in Swift. The provided code snippet is a part of the implementation and represents a function that is called when a payment is authorized. The function `paymentAuthorizationViewController(_:didAuthorizePayment:handler:)` takes...
```swift func paymentAuthorizationViewController(_ controller: PKPaymentAuthorizationViewController, didAuthorizePayment payment: PKPayment, handler completion: @escaping (PKPaymentAuthorizationResult) -> Void) { // Perform payment authorization logic if payment.amount > 0 { // Payment amount is valid, ...
magicoder
swift
You are tasked with implementing a class method for a search engine's query parser. The method should handle the case when the query consists of a single word and set certain attributes of a `Term` object based on the query and additional character range information. You are given the following code snippet as a start...
```python class QueryParser: def __init__(self, fieldname, words, char_ranges): self.fieldname = fieldname self.words = words self.char_ranges = char_ranges self.term = None def parse_single_word_query(self): if len(self.words) == 1: self.term = terms.Term(se...
magicoder
python
You are given an array `arr` of non-negative integers, where each element represents the maximum jump length at that position. You are initially positioned at the first index, and you need to reach the last index. You can assume that you can always reach the last index. Write a function `canReachEnd(arr)` that returns...
```python def canReachEnd(arr): def helper(pos): if pos < 0 or pos >= len(arr) or pos in seen: return False if pos == len(arr) - 1: return True seen.add(pos) return helper(pos + arr[pos]) or helper(pos - arr[pos]) seen = set() return helper(0) ``` The...
magicoder
python
You are tasked with implementing a stack data structure using a given container class `C`. The stack should support the following operations: 1. `push(const T& val)`: Adds an element to the top of the stack. 2. `pop()`: Removes the element at the top of the stack. 3. `top() const`: Returns a const reference to the elem...
```cpp template <typename T, typename C> class Stack { public: using value_type = T; using reference_type = T&; using const_reference_type = const T&; void push(const T& val) { container.push_back(val); } void pop() { if (!container.empty()) { container.pop_back(); ...
magicoder
cpp
You are tasked with implementing a function that completes a keyword based on a given prefix and a set of locations. The function should match the selector for each location and extract the real prefixes from the lines at those locations. You are given the following code snippet as a starting point: ```python def _co...
```python import re def complete_keyword(prefix, locations): prefixes = set() for point in locations: # Assuming self._line_prefix(point) retrieves the line prefix at the given point line_prefix = self._line_prefix(point) real_prefix = re.sub(r"^ +(- +)*", " ", line_prefix) # collapse ...
magicoder
python
You are tasked with implementing a Python class to represent a chemical reaction mechanism. The class should handle the calculation of reaction rates based on the Arrhenius equation and third-body efficiencies. The provided code snippet serves as a starting point for the problem. Your task is to complete the implement...
```python class ChemicalReaction: def __init__(self, Pmin, Pmax, comment, arrheniusLow, thirdBody): self.Pmin = Pmin self.Pmax = Pmax self.comment = comment self.arrheniusLow = arrheniusLow self.thirdBody = thirdBody def calculate_rate_constant(self, T, P): arrhe...
magicoder
python
You are tasked with implementing a function to solve the N-Queens problem. The N-Queens problem is a classic chess-based problem where the goal is to place N queens on an N×N chessboard in such a way that no two queens threaten each other. In this problem, you need to implement a function that takes an integer N as inp...
```python from typing import List def solve_n_queens(n: int) -> List[List[str]]: def is_safe(board, row, col): for i in range(row): if board[i][col] == 'Q': return False if col - (row - i) >= 0 and board[i][col - (row - i)] == 'Q': return False ...
magicoder
python
You are tasked with creating a Bash script that automates the process of building and pushing a Docker image to Docker Hub. The script should allow for customization of the Docker image tag and Docker Hub login credentials. The script should also handle default values for the tag and login credentials if they are not p...
```bash #!/bin/bash # Set default value for TAG if not provided TAG="${TAG:-sunsingerus/metrics-exporter:dev}" # Check if DOCKERHUB_LOGIN is set if [ -z "$DOCKERHUB_LOGIN" ]; then read -p "Enter Docker Hub login credentials: " DOCKERHUB_LOGIN fi # Build the Docker image using the specified tag docker build -t "$...
magicoder
shell
You are working on a robotics project and need to implement a function to calculate the new pose of a robot based on its previous pose and a transformation matrix. The transformation matrix is represented by a 3x3 matrix M, and the previous pose is represented by a 1x3 array _last_pose. The function takes two parameter...
```python import numpy as np def calculate_new_pose(tmp, _last_pose): if tmp: tmp = [int(i) for i in tmp] alpha = _last_pose[3] * 3.1416 / 180 M = np.array([[np.cos(alpha), np.sin(alpha), 0], [-np.sin(alpha), np.cos(alpha), 0], [0, 0, 1]]) ...
magicoder
python
You are tasked with implementing a simple recurrent neural network (RNN) layer using the Long Short-Term Memory (LSTM) architecture. The LSTM cell has three main components: an input gate, a forget gate, and an output gate, each of which involves specific computations. Your goal is to implement the forward pass of the ...
```python def input_gate(x, h, c): # Implement the input gate computation i = sigmoid(Wi @ x + Ui @ h + bi) new_c = f * c + i * tanh(Wc @ x + Uc @ h + bc) new_h = o * tanh(new_c) return new_h, new_c def forget_gate(x, h, c): # Implement the forget gate computation f = sigmoid(Wf @ x + Uf @ ...
magicoder
python
You are tasked with implementing a function to merge two sorted arrays into a single sorted array. The function should take two input arrays of integers and return a new array containing all elements from both input arrays in sorted order. You are also required to define a struct `MergeRequest` with a specific set of f...
```rust fn merge_sorted_arrays(arr1: &[i32], arr2: &[i32]) -> Vec<i32> { let mut result = Vec::new(); let (mut i, mut j) = (0, 0); while i < arr1.len() && j < arr2.len() { if arr1[i] < arr2[j] { result.push(arr1[i]); i += 1; } else { result.push(arr2[j]);...
magicoder
rust
You are tasked with implementing a simple asynchronous networking application using Python's `asyncio` library. Your goal is to create a server that can handle incoming connections and perform a specific action upon receiving a request. The provided code snippet is part of a class method that is responsible for setting...
```python import asyncio class AsyncServer: def __init__(self): self.factory = ServerFactory() async def handle_connection(self, client_socket): request_data = await self.read_request(client_socket) if request_data == b'ACTION1': await self.perform_action1() elif re...
magicoder
python
You are tasked with creating a program to simulate a simple dice game. The game involves rolling a six-sided die multiple times and keeping track of the outcomes. The goal is to determine the probability of rolling a specific sequence of numbers in a given number of rolls. Your program should take the following inputs...
```python import random def simulate_dice_game(num_rolls, sequence): outcomes = [random.randint(1, 6) for _ in range(num_rolls)] sequence_length = len(sequence) count = 0 for i in range(num_rolls - sequence_length + 1): if outcomes[i:i+sequence_length] == sequence: count += 1 ...
magicoder
python
You are tasked with creating a Python program that processes documentation for a set of modules using the `pdoc` library. The program should identify a specific module and perform a certain action based on its name. Your task is to write a function `process_module` that takes a list of module names and a target module...
```python from typing import List import pdoc def process_module(mod_names: List[str], target_module: str) -> str: context = pdoc.Context() modules = [pdoc.Module(mod, context=context) for mod in mod_names] pdoc.link_inheritance(context) for module in modules: if module.name == target_modu...
magicoder
python
You are tasked with creating a program that simulates the process of converting a binary file into an Intel HEX file and then obtaining the size of the sections within the resulting ELF file. The program should take a binary file as input, perform the conversion, and display the sizes of the text and data sections in t...
```python import subprocess # Step 1: Convert binary file to Intel HEX file binary_file = "input.bin" hex_file = "output.hex" subprocess.run(["avr-objcopy", "-I", "binary", "-O", "ihex", binary_file, hex_file]) # Step 2: Obtain sizes of text and data sections in ELF file elf_file = "output.elf" subprocess.run(["avr-o...
magicoder
python
You are tasked with creating a Python unit test for a class that interacts with a database. The class has a method for creating jobs, and the test is designed to verify the number of database queries made when creating multiple jobs. The test uses the `unittest` framework, and the `assertIn` method is used to check if ...
```python import unittest class JobManager: def __init__(self, database): self.database = database def make_job(self, job_name): # Implementation of creating a job in the database # This method should interact with the database to create the job class TestJobManager(unittest.TestCase)...
magicoder
python
You are tasked with creating a Python function that generates an interactive plot of the Mandelbrot set using the Chaco library. The Mandelbrot set is a set of complex numbers for which the function f(z) = z^2 + c does not diverge when iterated from z = 0, where c is a constant complex number. Chaco is a 2D plotting li...
```python import numpy as np from chaco.api import ArrayPlotData, Plot, jet, ImageData, DataRange1D from chaco.tools.api import PanTool, ZoomTool from enable.api import ComponentEditor from traits.api import HasTraits, Instance from traitsui.api import View, Item class MandelbrotPlot(HasTraits): plot = Instance(Pl...
magicoder
python
You are tasked with implementing a class method for an interpolation algorithm. The algorithm is used to interpolate attributes from one scale to the next in a multi-resolution model. The provided code snippet is a part of the class definition for this algorithm. Your task is to complete the implementation of the `inte...
```python class InterpolationAlgorithm: """ Class for an interpolation algorithm to interpolate attributes from one scale to the next in a multi-resolution model. """ def __init__(self, vert_array, triv_array): """ Initialize the interpolation algorithm with vertex and triangle arrays. ...
magicoder
python
You are tasked with implementing a simulation of a particle system in a 2D space. The given code snippet is part of a larger program that initializes attractors and moving boxes for the simulation. The `initBoxes` method initializes a list of attractors and a list of moving boxes, while the `config` method is not shown...
```java // MovingBox class class MovingBox { private double x, y; // position private double vx, vy; // velocity public MovingBox() { // initialize position and velocity } public void updatePosition(List<Attractor> attractors) { // Update position based on attraction to the attract...
magicoder
java
You are given a string containing a series of semicolon-separated commands. Each command represents a specific action to be performed. Your task is to write a function to parse the string and execute the commands in the given order. The commands can be of three types: "print", "add", and "subtract". The "print" comman...
```python def executeCommands(commands: str) -> None: commands = commands.split(';') total = 0 for command in commands: if command.startswith('print'): num = int(command.split()[1]) print(num) elif command.startswith('add'): num = int(command.split()[1]) ...
magicoder
python
You are tasked with implementing a Python function that calculates the descriptive statistics of a given dataset. The function should accept a list of numerical values and return a dictionary containing the mean, median, mode, range, variance, and standard deviation of the dataset. Your function should be named `calcu...
```python from statistics import mean, median, mode, variance, stdev from collections import Counter def calculate_descriptive_statistics(data: list) -> dict: descriptive_stats = {} descriptive_stats['mean'] = mean(data) descriptive_stats['median'] = median(data) data_counter = Counter(data) ...
magicoder
python
You are tasked with creating a Swift program that processes a JSON file containing information about different rules. The program should read the JSON file, parse its contents, and then perform specific operations based on the parsed data. The JSON file contains an array of rule objects, where each rule has the follow...
```swift import Foundation import HandyJSON struct Rule: HandyJSON { var version: String? var name: String? var enabled: Bool? var conditions: Conditions? } struct Conditions: HandyJSON { var minAge: Int? var maxAge: Int? var gender: String? } func getEnabledRulesNames(for rules: [Rule]) ...
magicoder
swift
You are tasked with implementing a generic function that calculates the total cost of a set of items based on their unit price and quantity. The function should have preconditions that involve model/tag fields of the parameters. Your task is to write a Rust function that satisfies these preconditions. The function sig...
```rust // Define the Tag trait with model field and validate method trait Tag { fn model(&self) -> &'static str; fn validate(&self) -> bool; } // Implement the Tag trait for a specific tag type struct ExampleTag { model: &'static str, } impl Tag for ExampleTag { fn model(&self) -> &'static str { ...
magicoder
rust
You are tasked with implementing a Swift function that checks whether a given string is a palindrome. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward, disregarding spaces, punctuation, and capitalization. Your task is to implement the `isPalindrome` func...
```swift func isPalindrome(_ input: String) -> Bool { let alphanumericInput = input.lowercased().replacingOccurrences(of: "[^a-z0-9]", with: "", options: .regularExpression) return alphanumericInput == String(alphanumericInput.reversed()) } // Test cases print(isPalindrome("A man a plan a canal Panama")) // Ou...
magicoder
swift
You are tasked with creating a Python program to analyze the frequency of characters in a given string and then display the three most common characters along with their frequencies. You should implement a function `most_common_characters(string)` that takes a string as input and returns a list of tuples, each containi...
```python from collections import Counter def most_common_characters(string): # Remove spaces and convert to lowercase string = string.replace(' ', '').lower() # Use Counter to count character frequencies char_count = Counter(string) # Get the three most common characters most_common ...
magicoder
python
You are given a list of triplets, where each triplet represents a relationship between two individuals and a binary value indicating whether they are connected or not. The first two elements of each triplet represent the IDs of the individuals, and the third element represents the binary value (0 or 1) indicating the c...
```python from typing import List class UnionFind: def __init__(self, n): self.parent = list(range(n)) self.rank = [0] * n def find(self, x): if self.parent[x] != x: self.parent[x] = self.find(self.parent[x]) return self.parent[x] def union(self, x, y): ...
magicoder
python
You are given a robot that moves on a grid. The robot is initially located at position (0, 0) on the grid and is facing in the upward direction (facing = 0). The robot can move in four directions: up, down, left, and right. The robot's movements are represented by a string of characters, where each character denotes a ...
```python from typing import Tuple def final_position(moves: str) -> Tuple[int, int]: cur = (0, 0) facing = 0 # 0: up, 1: right, 2: down, 3: left for move in moves: if move == 'U': cur = (cur[0], cur[1] + 1) elif move == 'D': cur = (cur[0], cur[1] - 1) elif...
magicoder
python
You are tasked with implementing a function to encode a digitally signed object in a specific format. The digitally signed object contains information about the hash algorithm, signature algorithm, and signature data. Your goal is to create a function that takes this object as input and encodes it into a string accordi...
```cpp #include <string> namespace ct { struct DigitallySigned { enum HashAlgorithm { HASH_ALGO_SHA256, // Other hash algorithms may be defined here }; enum SignatureAlgorithm { SIG_ALGO_ECDSA, // Other signature algorithms may be defined here }; HashAlgorithm hash_algori...
magicoder
cpp
You are tasked with implementing a task scheduling algorithm for a system that manages various tasks with different policies. The system has an `Agent` class with a method `isXenMode()` that checks whether the system is running in Xen mode. Additionally, there is a static function `SetTaskPolicyOne` that sets the polic...
```cpp static void SetTaskPolicy(const char *task, const char *exclude_list[]) { Agent *agent = new Agent(); // Create an instance of Agent if (agent->isXenMode()) { // System is in Xen mode, set "XenPolicy" for the task // Implementation to set "XenPolicy" for the task // ... s...
magicoder
cpp
You are given a list of password policies and passwords. Each line of the input represents a password policy and the password it applies to. A password policy indicates the lowest and highest number of times a given letter must appear for the password to be valid. For example, "1-3 a" means the password must contain 'a...
```python from typing import List def count_valid_passwords(passwords: List[str]) -> int: valid_count = 0 for entry in passwords: policy, password = entry.split(": ") limits, letter = policy.split(" ") min_limit, max_limit = map(int, limits.split("-")) letter_count = password.co...
magicoder
python
You are tasked with implementing a custom data transformation class for a machine learning pipeline. The class is designed to round the input data and reshape it for further processing. Your task is to complete the implementation of the `CustomTransformer` class by adding the missing methods. The `CustomTransformer` c...
```python import numpy as np class CustomTransformer: def __init__(self, X): self.X = X def fit(self, X, y=None, **kwargs): self.X = round(X) return self def transform(self, X): return np.array(round(X[X.columns[0]])).reshape(-1, 1) # Sample usage import pandas as...
magicoder
python
You are tasked with implementing a thread-safe caching mechanism for generating unique keys based on a set of configuration fragments and build options. The provided code snippet outlines a method `key` that takes a set of configuration fragments and build options as input and returns a unique key for the requested con...
```java import java.util.Set; import java.util.concurrent.ConcurrentHashMap; public class BuildOptions { // Implementation details not provided } public class Key { // Implementation details not provided } public class SkyKey { // Implementation details not provided } public class KeyInterner { priv...
magicoder
java
You are tasked with implementing a simple Entity-Component System (ECS) in Python. An ECS is a design pattern used in game development to manage entities (game objects) and their associated components (attributes or behaviors). Your goal is to create a class `EntityManager` that manages entities and their components. ...
```python import uuid import typing as t class EntityManager: def __init__(self): self.entities = {} def create_entity(self) -> uuid.UUID: entity_id = uuid.uuid4() self.entities[entity_id] = {} return entity_id def add_component(self, entity_id: uuid.UUID, component: t.Any...
magicoder
python
You are tasked with creating a Bash script that dynamically generates a customized prompt for the Kubernetes command-line tool (`kubectl`). The prompt should display the current context and namespace of the active Kubernetes configuration. The script should also include color-coding to enhance the visual representation...
```bash #!/bin/bash # Function to generate the customized kubectl prompt generate_kubectl_prompt() { local context_color="%{$fg[blue]%}" # Blue color for context local namespace_color="%{$fg[green]%}" # Green color for namespace local reset_color="%{$reset_color%}" local current_context=$(kubectl co...
magicoder
shell
You are tasked with implementing a function to extract an integer from a given sequence of raw bits. The function should take into account the byte offset, bit offset, and the number of bits to extract. You are also required to update the byte index after the extraction. You are given the following code snippet as a r...
```python def extract_int_from_raw_bits(raw_bits, byte_offset, bit_offset, number_of_bits): # Calculate the starting bit position start_bit_position = (byte_offset * 8) + bit_offset # Extract the integer from the raw bits extracted_int = 0 for i in range(number_of_bits): bit_position = ...
magicoder
python
You are tasked with creating a Python module that manages a role-based access control system for a gaming platform. The system should allow users to have different roles, such as player, moderator, or administrator, and restrict access to certain game-related functionalities based on these roles. Your task is to imple...
```python class RoleManager: def __init__(self): self.roles = {} def add_role(self, role_name, permissions): self.roles[role_name] = permissions def remove_role(self, role_name): if role_name in self.roles: del self.roles[role_name] def get_permissions(self, role_n...
magicoder
python
You are tasked with implementing a C++ class that simulates a simple banking system. The class should have the ability to create accounts, deposit and withdraw funds, and provide the current balance. Additionally, the class should support the concept of an interest rate, where the balance of an account grows by a certa...
```cpp #include <iostream> class BankAccount { protected: double balance; double interest_rate; public: BankAccount(double initial_balance, double interest) : balance(initial_balance), interest_rate(interest) {} void deposit(double amount) { balance += amount; } void withdraw(double ...
magicoder
cpp
You are tasked with creating a Python function that simulates the process of loading a checkpoint for a deep learning model and preparing it for inference. The function should handle the loading of the checkpoint, setting the model's state dictionary, and preparing the model for evaluation. Additionally, the function s...
```python import torch from torch.nn.parallel import DataParallel def prepare_model(checkpoint_path: str, model: Any, parallel: bool = False, cpu: bool = False) -> Any: if cpu: checkpoint = torch.load(checkpoint_path, map_location=torch.device('cpu')) else: checkpoint = torch.load(checkpoint_pa...
magicoder
python
You are tasked with implementing a simplified version of a user login system in Java. The provided code snippet is a part of the `User` class, which contains a constructor and a `login` method. The `login` method makes use of an external `Requests` class to perform a login operation and retrieve data. Your task is to ...
```java import java.io.IOException; import java.util.ArrayList; class User { public User() { // Constructor implementation } public ArrayList<Day> login() throws IOException { Requests google = new Requests(this); return google.requestData(); } } class Requests { private U...
magicoder
java
You are tasked with implementing a custom indexing system for a document management application. The system should allow users to efficiently retrieve documents based on their unique index keys. Each document is associated with a set of index keys, and users should be able to search for documents using any combination ...
```java import java.util.*; public class Index { private Map<String, Set<Document>> indexMap; public Index() { indexMap = new HashMap<>(); } public void addDocument(Document document) { for (String key : document.getIndexKeys()) { indexMap.computeIfAbsent(key, k -> new Has...
magicoder
java
You are tasked with implementing a function that processes a given set of typography properties and returns a formatted string representing the CSS style declaration. The function should accept an object containing typography properties and their corresponding values, and return a string in the format "property1: value...
```typescript function formatTypography(typography: TypographyProperties): string { let styleDeclaration = ""; for (const property in typography) { if (typography.hasOwnProperty(property)) { const value = typography[property]; if (value !== undefined) { styleDeclaration += `${property.replac...
magicoder
typescript
You are tasked with creating a program to manage cryptocurrency trading. Your program needs to calculate the net profit from buying and selling cryptocurrencies, considering completed transactions and the current crypto balance. You are given a code snippet that includes a method to calculate the net profit and a stat...
```python class CryptoManager: @staticmethod def calculate_net_profit(buy_history, sell_history, crypto_balance): buy_total = 0 sell_total = 0 for purchase in buy_history: if purchase.status == "completed": buy_total += float(purchase.total.amount) fo...
magicoder
python
You are tasked with implementing a custom path management system using C++ templates. The system should allow the creation of paths and the ability to check for path uniqueness. The `Path` class is a template class that takes a `ListPathPool` as a template parameter. The `ListPathPool` is a container for storing paths....
```cpp #include <iostream> #include <string> #include <unordered_set> template <typename ListPathPool> class Path { public: Path() = default; Path(const Path& parent, const std::string& pathName) : parent_(&parent), pathName_(pathName) {} bool isUnique() const { if (parent_ == nullptr) { ...
magicoder
cpp
You are tasked with implementing a shell script function to deploy SSL certificates for a web server. The function, `deploycert`, takes in a domain name as an argument and is responsible for deploying the SSL certificate for the specified domain. The script also includes some commented-out options that can be used as f...
```bash deploycert() { local domain=${1:-defaultdomain.com} # Use default domain if no domain is provided local dry_run=false local keep_until_expiring=false local expand=false local force_renewal=false # Parse options while [[ $# -gt 0 ]]; do case "$1" in --dry-run) ...
magicoder
shell
You are tasked with creating a Java program to simulate a simple multi-threaded task management system. The program should create and manage multiple threads to perform independent tasks and then wait for all threads to complete before proceeding. Your task is to implement a Java program that creates a specified numbe...
```java // TaskThread class to represent a thread performing a task class TaskThread extends Thread { private int taskNumber; public TaskThread(int taskNumber) { this.taskNumber = taskNumber; } @Override public void run() { System.out.println("Task " + taskNumber + " is being execu...
magicoder
java
You are tasked with implementing a tessellation algorithm for PN Triangles in OpenGL. The goal is to replace input triangles with tessellated patches to produce smoother and more organic shapes. The tessellation amount can be tuned as a global state value. Your task is to write a function `tessellatePNTriangles` that ...
```c #include <vector> #include <cmath> struct Triangle { Vertex vertices[3]; }; struct Vertex { float position[3]; float normal[3]; }; void tessellatePNTriangles(const std::vector<Triangle>& inputTriangles, float tessellationAmount, std::vector<Vertex>& outputVertices) { for (const auto& triangle : ...
magicoder
c
You are working on a web application that allows super administrators to manage home tabs. The code snippet provided is a part of the backend logic for editing home tab details. The `$data` array contains the details of the home tab to be edited, and it is passed to the view for rendering the edit form. Your task is t...
```php public function edit_home_tab_details($updated_details) { // Assuming $updated_details contains the updated information from the form $home_tab_id = $updated_details['home_tab_id']; // Update the home tab details in the database $this->home_tab_model->update_home_tab($home_tab_id, $updated_detai...
magicoder
php
You are tasked with creating a Python program to scrape data from the Formula 1 official website. The provided code snippet is a part of a web scraping script using Scrapy, a popular web crawling and scraping framework. The script is designed to extract the fastest lap times from Formula 1 races for each year from 1950...
```python def parse_fastest_laps(response): fastest_laps = [] year = response.meta["year"] for row in response.xpath('//*[@class="resultsarchive-table"]//tbody//tr'): race = row.xpath('td[2]/text()').get() driver = row.xpath('td[3]/text()').get() team = row.xpath('td[4]/text()').get(...
magicoder
python
You are tasked with creating a script to automate the process of seeding a database for a Ruby on Rails application. The database seeding process involves populating the database with initial data, such as default records for tables, sample data for testing, or any other necessary data. Your script should read data fr...
```ruby # Define the seeding script to populate the database with initial data class DatabaseSeeder def initialize # Initialize any required variables or configurations end # Method to seed the database with data from a CSV file def seed_from_csv(file_path) # Read data from the CSV file and populate th...
magicoder
ruby
You are tasked with implementing a class method for a linguistic tool that generates a name in a specific form based on certain parameters. The method `name_in_form` takes two optional boolean parameters, `is_ablative` and `is_accusative`, and returns a string representing the name in a particular linguistic form. The ...
```python class LinguisticTool: def __init__(self, affix, type, suffix, owner=None): self.affix = affix self.type = type self.suffix = suffix self.owner = owner def name_in_form(self, is_ablative: bool = False, is_accusative: bool = False) -> str: if self.owner is None: ...
magicoder
python
You are tasked with implementing a function to parse and validate command-line switches for a Python application. The function should take a dictionary of switches and their values, and return a list of valid switches. A valid switch is defined as a key-value pair where the key starts with "--" and the value is not an ...
```python def validate_switches(switches): valid_switches = [key for key, value in switches.items() if key.startswith("--") and value] return valid_switches ``` The `validate_switches` function iterates through the key-value pairs in the `switches` dictionary. It checks if the key starts with "--" and the valu...
magicoder
python
You are tasked with creating a program that simulates a simplified version control system similar to Git. Your program should be able to handle basic version control operations such as committing changes, displaying commit history, and showing modified files in the last commit. Your task is to implement a Python class...
```python import time class VersionControl: def __init__(self): self.commits = [] def commit(self, message, files): commit_id = len(self.commits) + 1 timestamp = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) self.commits.append({ 'id': commit_id, ...
magicoder
python
You are tasked with implementing a class that accumulates insert and replace operations for a string and later performs them all at once so that positions in the original string can be used in all of the operations. You need to implement the `InsertableString` class with the following methods: - `__init__(self, initia...
```python class InsertableString(object): def __init__(self, initial_str): self.original_str = initial_str self.operations = [] def insert(self, index, substring): self.operations.append(('insert', index, substring)) def replace(self, start, end, new_substring): self.operat...
magicoder
python
You are tasked with implementing a Timestamp class that manages absolute and relative timestamps. The class should have methods to retrieve the absolute timestamp and to check if a relative timestamp exists. You need to implement the following methods in the Timestamp class: 1. `getAbsoluteTimestamp()`: This method s...
```java import java.time.Instant; public class Timestamp { private Instant absoluteTimestamp; private boolean hasRelativeTimestamp; public Timestamp(Instant absoluteTimestamp, boolean hasRelativeTimestamp) { this.absoluteTimestamp = absoluteTimestamp; this.hasRelativeTimestamp = hasRelativ...
magicoder
java
You are tasked with creating a program that analyzes the frequency of words in a given text file and outputs the top N most frequent words along with their counts. The program should ignore common English stop words (e.g., "the", "and", "is") and should be case-insensitive (i.e., "The" and "the" should be considered th...
```python import re from collections import Counter def topNWords(filename, N): with open(filename, 'r') as file: text = file.read().lower() words = re.findall(r'\b\w+\b', text) stop_words = {'the', 'and', 'is', 'a', 'an', 'in', 'on', 'at', 'to', 'of', 'for', 'with', 'it', 'this', 'that', '...
magicoder
python
You are tasked with creating a script to automate the testing of Swift module generation and Objective-C header file generation. The script should perform the following tasks: 1. Create an empty directory for the test output. 2. Use the Swift frontend to generate a Swift module, module documentation, and an Objective-...
```bash # Create an empty directory for the test output mkdir %t # Generate Swift module, module documentation, and Objective-C header file %target-swift-frontend(mock-sdk: %clang-importer-sdk) -enable-source-import -emit-module -emit-module-path %t/comments.swiftmodule -emit-module-doc -emit-module-doc-path %t/commen...
magicoder
shell
You are tasked with extending the functionality of a simple 2D game player by adding new states and associated behaviors. The player is represented by the `Player` struct, which has a `state` field of type `PlayerState` and a `frame_idx` field to keep track of animation frames. The `PlayerState` enum currently has one ...
```rust // Define the PlayerState enum with new states enum PlayerState { IdleRight, IdleLeft, Jumping, Flying, Growing, // Add more states as needed } // Implement the Player struct with state and frame_idx fields struct Player { state: PlayerState, frame_idx: u32, } // Implement meth...
magicoder
rust