query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with implementing a memory monitoring system for a network device. The system uses SNMP (Simple Network Management Protocol) to collect data about memory pools on the device. The given code snippet is part of a Java program that processes the SNMP data to retrieve memory pool information. The code snipp...
```java import java.util.HashMap; import java.util.Map; public class MemoryMonitor { public Map<String, Long> calculateMemoryUsage(String[] mpList, Map<String, SnmpOid> poolIndexMap, Map<SnmpOid, Long> memoryData) { Map<String, Long> memoryUsageMap = new HashMap<>(); for (String mpmName : mpList)...
magicoder
java
You are tasked with creating a script to manage Amazon Elastic Container Registry (ECR) using the AWS Command Line Interface (CLI). Your script should respect the environment variables `AWS_DEFAULT_REGION` and `AWS_DEFAULT_OUTPUT` if they are specified, and set them to default values if they are not already set. Additi...
```bash #!/bin/bash # Respect AWS_DEFAULT_REGION if specified if [ -z "$AWS_DEFAULT_REGION" ]; then export AWS_DEFAULT_REGION=us-east-1 fi # Respect AWS_DEFAULT_OUTPUT if specified if [ -z "$AWS_DEFAULT_OUTPUT" ]; then export AWS_DEFAULT_OUTPUT=json fi # Capture output output=$(aws ecr "$@") echo "$output" `...
magicoder
shell
You are tasked with creating a migration script for a blogging platform. The platform currently has a `Post` model and a `Tag` model. Each post can have multiple tags associated with it. However, due to a change in the platform's architecture, it has been decided to remove the direct relationship between posts and tags...
```python from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blog', '0012_remove_tag_image'), # Assuming this is the previous migration ] operations = [ migrations.RemoveField( model_name='post', name='tags', ...
magicoder
python
You are tasked with implementing a message layout system for a chat application. The code snippet provided sets the origin point for a message container based on the position of the message within the chat interface. The message container includes an avatar, message content, attachments, and duration information. Your ...
```swift func calculateMessageContainerOrigin(position: MessagePosition, itemWidth: CGFloat, avatarSize: CGSize, messageContainerSize: CGSize, messageContainerPadding: UIEd...
magicoder
swift
You are tasked with implementing a generic constraint system for a UI framework. The framework provides two types, `ConstraintItem` and `ConstraintView`, both of which conform to the `ConstraintRelatableTarget` protocol. Your goal is to create a generic function that can compare and relate two instances of types confor...
```swift protocol ConstraintRelatableTarget { func isEqual(to other: Self) -> Bool } extension ConstraintItem: ConstraintRelatableTarget { func isEqual(to other: ConstraintItem) -> Bool { // Custom comparison logic for ConstraintItem // Return true if equal, false otherwise } } extension C...
magicoder
swift
You are tasked with creating a Python function that processes submission information packages (SIPs) and performs various operations on them. The SIPs are stored in a directory structure, and the function needs to handle the loading, manipulation, and removal of these packages. You are given a code snippet that demons...
```python import os class SubmissionInformationPackage: def load(self, package_path): # Implementation of loading the SIP package pass def safeRemove(self): # Implementation of safely removing the SIP package pass def process_sip(base_dir, package_name): sipDir = base_dir ...
magicoder
python
You are tasked with implementing a codename generator that creates unique codenames for agents in a spy organization. The codenames should consist of a combination of an adjective and a noun, both randomly selected from predefined lists. The codename generator should ensure that each generated codename is unique and no...
```csharp namespace CodenameGenerator { public class CodenameGenerator { private List<string> adjectives = new List<string> { "Swift", "Stealthy", "Cunning", "Sneaky", "Silent" }; private List<string> nouns = new List<string> { "Shadow", "Phantom", "Ghost", "Whisper", "Specter" }; ...
magicoder
csharp
You are tasked with implementing a Swift enum that represents different error codes for a networking library. The enum should have associated values for specific error cases. Additionally, you need to write a function that takes an error code and returns a human-readable error message based on the enum cases. Your enu...
```swift enum NetworkError { case invalidURL(String) case unauthorized case serverError(Int) case custom(String) } func errorMessage(for error: NetworkError) -> String { switch error { case .invalidURL(let url): return "Invalid URL: \(url)" case .unauthorized: return "Unauth...
magicoder
swift
You are tasked with creating a Python class for managing API keys and handling connection errors for a fictional API service. Your task is to implement the `ApiManager` class, which should handle the following functionalities: 1. Storing and retrieving API keys for the Meraki API service. 2. Making API requests using ...
```python class ConnectionError(Exception): pass class ApiKeyMissing(Exception): def __init__(self): Exception.__init__(self, 'Meraki API Key missing.') class ApiManager: def __init__(self): self.api_key = None def set_api_key(self, key): self.api_key = key def get_api_ke...
magicoder
python
You are tasked with implementing a function that takes in an array of objects representing articles and returns an array of tags that occur most frequently across all the articles. Each article object has a `length` property representing the article length in words and a `tags` property representing an array of strings...
```javascript function findMostFrequentTags(articles) { const tagFrequency = new Map(); // Count the frequency of each tag for (const article of articles) { for (const tag of article.tags) { tagFrequency.set(tag, (tagFrequency.get(tag) || 0) + 1); } } // Find the maximum frequency let ma...
magicoder
javascript
You are tasked with implementing a function to calculate the average color of a triangle mesh in a 3D graphics application. The mesh is represented by a `TriangleMesh` object, which contains vertex colors. The vertex colors are stored in a `ColorList` object, which is a list of RGB color values. You need to create a f...
```cpp #include <iostream> int main() { // Create a sample TriangleMesh with vertex colors TriangleMesh mesh; mesh.get_vertex_colors().push_back({255, 0, 0}); // Red mesh.get_vertex_colors().push_back({0, 255, 0}); // Green mesh.get_vertex_colors().push_back({0, 0, 255}); // Blue // Calcula...
magicoder
cpp
You are tasked with implementing a C++ function that calculates the squared distance between two vectors using the Eigen library. The squared distance between two vectors is defined as the sum of the squared differences between their corresponding elements. You are given the following function signature: ```cpp double...
```cpp #include <vector> #include <Eigen/Dense> double calculateSquaredDistance(const std::vector<double>& vec1, const std::vector<double>& vec2) { // Check if the input vectors have the same size if (vec1.size() != vec2.size()) { throw std::invalid_argument("Input vectors must have the same size"); ...
magicoder
cpp
You are given a C++ code snippet that includes conditional compilation directives and shell commands. Your task is to understand the purpose of the code and identify the potential issue in the given code snippet. Identify the issue and explain the potential problem with the conditional compilation directives and shell...
The given code snippet appears to be a part of a shell script that is generating a C++ source file. The conditional compilation directives are used to check the size of `std::uintmax_t` and then conditionally include some content in the generated file based on the size of `std::uintmax_t`. The potential issue in the g...
magicoder
shell
You are tasked with implementing a function that processes data from a fictional event management system. The system uses RxSwift and RxDataSources to handle table view data. Your goal is to create a function that processes the data source for a table view displaying event details. You are provided with a code snippet...
```swift struct Event { let title: String let date: Date let location: String let description: String } enum EventDetailSectionModel { case generalInfo(event: Event) case description(event: Event) } func processEventDetails(events: [Event]) -> RxTableViewSectionedReloadDataSource<EventDetailSe...
magicoder
swift
You are tasked with implementing a function to process an incoming swap message received from TOR in a cryptocurrency wallet application. The provided code snippet is part of the implementation and includes a function `receive_swap_message` with the following signature: ```rust pub fn receive_swap_message<'a, L, C, K>...
```rust pub fn receive_swap_message<'a, L, C, K>( wallet_inst: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K>>>>, keychain_mask: Option<&SecretKey>, message: &String, ) -> Result<(), Error> { // Implement the processing of the incoming swap message here // Example: // Parse the incoming swap message ...
magicoder
rust
You are tasked with creating a Python script that automates the installation of required packages for a given project. The script should take a list of package names as input and install each package using the `pip` package manager. Additionally, the script should handle any potential errors that may occur during the i...
```python from typing import List import subprocess def install_packages(packages: List[str]) -> List[str]: successfully_installed = [] for package in packages: try: subprocess.run(["pip", "install", package], check=True) successfully_installed.append(package) except sub...
magicoder
python
You are tasked with implementing a simple parser for a custom language using the Rust programming language. The given code snippet provides a partial implementation of the parser using traits and methods. Your task is to complete the implementation by defining the missing methods and traits. You are provided with the ...
```rust // Define the Parser trait for parsing the input trait Parser { // Add methods for parsing the input based on grammar rules fn parse_input(&self, input: &str) -> Result<ParseResult, ParseError>; // Other parsing methods can be added as per the grammar rules } // Implement the Parser trait for Refer...
magicoder
rust
You are working on a deployment script for a distributed system. The script is responsible for updating the configuration files on all nodes and then running a benchmarking tool to measure the system's performance. The script takes three arguments: a list of all nodes in the system, the name of the configuration file t...
```bash #!/bin/bash # Check if the required arguments are provided if [ "$#" -ne 3 ]; then echo "Usage: $0 <AllNodes> <FileName> <LoadFile>" exit 1 fi AllNodes=$1 FileName=$2 LoadFile=$3 # Check if changePBConfig.sh script exists and is executable if [ ! -x "./script/changePBConfig.sh" ]; then echo "Erro...
magicoder
shell
You are tasked with creating a custom error handling system for a banking application. The application needs to handle specific error cases related to insufficient funds and invalid zero amounts. You are required to implement a custom error type and define the necessary error variants to represent these specific error ...
```rust use std::fmt; // Define the custom error type for the banking application #[derive(Debug)] enum BankError { InsufficientFunds, InvalidZeroAmount, } // Implement the std::fmt::Display trait for the BankError enum impl fmt::Display for BankError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result...
magicoder
rust
You are working on a game development project and need to implement a new type of ammunition for the game. The code snippet provided is a part of the item definition for the new ammunition in the game's codebase. Your task is to write a function that takes the properties of the ammunition item and generates the corresp...
```csharp public class AmmunitionItem { public int height; public int maxStack; public string toolTip; public bool consumable; public float knockBack; public int value; public int rare; public string shoot; public float shootSpeed; public AmmoID ammo; } public class AmmunitionIt...
magicoder
csharp
You are tasked with implementing a function that calculates the total number of lines of code in a TypeScript project by parsing the project's GitHub repository URL. The function should retrieve the TypeScript files from the repository and count the total number of lines in those files, excluding comments and empty lin...
```typescript import fetch from 'node-fetch'; import { promisify } from 'util'; import { parse } from 'node-html-parser'; const asyncParse = promisify(parse); async function calculateTotalLinesOfCode(repositoryUrl: string): Promise<number> { const response = await fetch(repositoryUrl); const html = await response...
magicoder
typescript
You are tasked with creating a program that reads a text file and counts the occurrences of each word in the file. Your program should ignore punctuation and consider words with different capitalizations as the same word. The program should then output the word count for each unique word in alphabetical order. For exa...
```python import sys import string def count_words(filename): word_count = {} try: with open(filename, 'r') as file: for line in file: for word in line.split(): word = word.strip(string.punctuation).lower() word_count[word] = word_coun...
magicoder
python
You are tasked with implementing a data structure to represent a 3-dimensional box and its associated operations. The `Box3` struct has two fields, `min` and `max`, each representing a 3-dimensional point. The struct also has methods to create a new box, retrieve the volume of the box, and perform a union operation wit...
```rust struct Point3 { x: f64, y: f64, z: f64, } impl Point3 { fn new(x: f64, y: f64, z: f64) -> Point3 { Point3 { x, y, z } } } struct Box3 { min: Point3, max: Point3, } impl Box3 { fn new(min: Point3, max: Point3) -> Box3 { Box3 { min, max } } fn volume(&se...
magicoder
rust
You are given a C++ code snippet that contains an incomplete namespace block. Your task is to complete the namespace block with the necessary code to define a class and a function within that namespace. Complete the namespace "example" by defining a class "MyClass" with a private integer member variable "value" and a ...
```cpp namespace example { class MyClass { private: int value; public: void setValue(int val) { value = val; } int getValue() { return value; } }; } // namespace example ``` In the solution, the namespace "example" is completed by defining a class "MyClass" with a private membe...
magicoder
cpp
You are tasked with implementing a simple stack data structure using a linked list in C++. The stack should support the following operations: 1. `push`: Add an element to the top of the stack. 2. `pop`: Remove the element from the top of the stack and return its value. 3. `top`: Return the value of the element at the t...
```cpp #include <iostream> class Node { public: int data; Node* next; Node(int val) : data(val), next(nullptr) {} }; class Stack { private: Node* topNode; public: Stack() : topNode(nullptr) {} void push(int val) { Node* newNode = new Node(val); newNode->next = topNode; ...
magicoder
cpp
You are tasked with creating a program that categorizes a person's body weight based on their BMI (Body Mass Index). The BMI is calculated using the formula: BMI = weight (kg) / (height (m) * height (m)). The categorization is as follows: - If the BMI is less than 18, the person is categorized as "Underweight". - If th...
```python def calculate_bmi_category(weight, height): bmi = weight / (height * height) if bmi < 18: return "Underweight" elif 18 <= bmi <= 25: return "Normal" else: return "Overweight" ``` The `calculate_bmi_category` function calculates the BMI using the provided weight and heig...
magicoder
python
You are tasked with creating a script to automate the setup and execution of a data processing pipeline using Docker. Your script should handle the creation of a directory, setting the current working directory, and running a Docker container with specific configurations. Write a Bash script that accomplishes the foll...
```bash #!/bin/bash # Create the test-output directory if it does not exist mkdir -p test-output # Store the current user's directory in the USERDIR variable USERDIR=$(pwd) # Determine the directory of the script being executed and store it in SCRIPT_DIR SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/n...
magicoder
shell
You are tasked with creating a script to automate the compilation of MonoGame Effect files. The script takes a filename as an argument, extracts the name without the extension, and then compiles the effect file to a specified output file using the MonoGame Effect compiler (`mgfxc`). The script uses Wine to run the Mono...
```bash #!/bin/bash FILENAME=$1 NAME=$(echo "$FILENAME" | cut -f 1 -d '.') OUTPUT="${NAME}.mgfx" echo "Received file ${FILENAME}" echo "Compiling Effect ${FILENAME} to ${OUTPUT}" MGFXC_WINE_PATH=/home/wine/.winemonogame /home/wine/.dotnet/tools/mgfxc $FILENAME $OUTPUT ``` The provided Bash script accomplishes the com...
magicoder
shell
You are tasked with implementing a custom type binder in C#. The type binder is responsible for resolving type names to actual Type objects. Your goal is to create a class that inherits from a base class and implements the abstract method `BindToType`. The method should take in an assembly name and a type name, and ret...
```csharp using System; public abstract class TypeBinderBase { public abstract Type BindToType(string assemblyName, string typeName); } public class CustomTypeBinder : TypeBinderBase { public override Type BindToType(string assemblyName, string typeName) { // Resolve the type name to a Type object...
magicoder
csharp
You are tasked with implementing a Python class that can parse XML data and extract specific elements. Your task is to complete the implementation of the `CreateFromDocument` class, which should be able to parse the given XML string and create an instance with attributes corresponding to the XML elements. The XML stri...
```python from xml.etree.ElementTree import fromstring class CreateFromDocument: def __init__(self, xml_string): root = fromstring(xml_string) self.description = root.text self.sub_description = root.find('sub-description').text if root.find('sub-description') is not None else None ...
magicoder
python
You are tasked with implementing a Python class that represents a user and a function to remove user data from a database. The user class should have attributes for user ID and username, and the function should remove the user data from the database. Your task is to complete the implementation of the User class and the...
```python class User: def __init__(self, user_id, username): self.id = user_id self.username = username def __str__(self): return f"<User {self.id}: {self.username}>" def remove_data_from_db(users): """ Simulates the process of removing user data from a database. Args:...
magicoder
python
You are working on a Python package for managing a collection of items. The package consists of several modules, including `add.py`, `remove.py`, and `fetch.py`, each containing functions for adding, removing, and fetching items from the collection, respectively. Your task is to implement a function in the main module...
```python from typing import List, Tuple, Any from .add import add_item from .remove import remove_item from .fetch import fetch_item def perform_operations(operations: List[Tuple[str, Any]]) -> List[Any]: results = [] for action, item in operations: if action == "add": add_item(item) ...
magicoder
python
You are working on a Python package that contains various finite element analysis functions for structural engineering. The package includes a module named `finite_element` which contains a list of functions that perform different types of finite element analysis. The list of functions is stored in the `__all__` variab...
```python def categorize_finite_element_functions(functions): categorized_functions = {'H8': [], 'Q4': [], 'Q5': []} for function in functions: if function.startswith('H8'): categorized_functions['H8'].append(function) elif function.startswith('Q4'): categorized_func...
magicoder
python
You are working on a testing framework for a scientific computing library. The framework allows running specifications defined in YAML files and verifying the output of the computations. The `run_spec_no_output` function is used to execute a specification without expecting any specific output. The function returns a re...
```python class ReturnCodeError(Exception): def __init__(self, message): self.message = message def verify_return_code(yaml_file, expected_return_code): result = run_spec_no_output(yaml_file) if result.ret != expected_return_code: raise ReturnCodeError(f"Unexpected return code: {result.ret}...
magicoder
python
You are tasked with implementing a Python function that calculates the sum of all prime numbers within a given range. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. The function should take two integer parameters, `start` and `end`, representing the inclusive ra...
```python def sum_of_primes(start, end): def is_prime(num): if num < 2: return False for i in range(2, int(num ** 0.5) + 1): if num % i == 0: return False return True prime_sum = 0 for num in range(max(2, start), end + 1): if is_prime(...
magicoder
python
You are working on a data visualization project and need to create a function to generate line plots with specific configurations. The code snippet provided is a part of the function that you are developing. The function `lineplot` is used to create line plots, and it takes several parameters including `ubudget_sector`...
```python def lineplot(ubudget_sector, keys, day, style, xlims, xticks, legend, legend_kw, ylabel): # Your implementation of lineplot function # Assuming legend_kw is a dictionary with other legend configurations # Check if grp.col is 0 if grp.col == 0: legend = True if nm == 'ubudget':...
magicoder
python
You are tasked with implementing a custom operator in RxJS to handle distinct value changes based on shallow equality comparison. Additionally, you need to set default props for a controlled input component in TypeScript. Implement a custom RxJS operator `distinctUntilChanged` that uses the `shallowEqual` function for...
```typescript // Custom RxJS operator distinctUntilChanged with shallowEqual comparison const distinctUntilChanged = (comparer: (x: any, y: any) => boolean) => { return (source: Observable<any>) => new Observable<any>((observer) => { let previousValue: any; return source.subscribe({ next(value...
magicoder
typescript
You are tasked with creating a function that animates the transition of an image in a UIImageView. The function should take in the necessary parameters to configure the animation and execute the transition. Your goal is to implement the function that performs the animation using the given code snippet as a reference. ...
```swift func animateImageTransition(with options: UIView.AnimationOptions, animations: ((UIImageView, UIImage) -> Void)?, completion: ((Bool) -> Void)?) { UIView.transition(with: imageView, duration: 0.5, options: options, animations: { animations?(...
magicoder
swift
You are tasked with implementing a Python function that calculates the total number of unique words in a given text file. The function should ignore punctuation and consider words with different capitalizations as the same word. Additionally, the function should exclude any common English stop words (e.g., "the", "and"...
```python import string def count_unique_words(file_path: str) -> int: # Read the file and convert its content to lowercase with open(file_path, 'r') as file: content = file.read().lower() # Remove punctuation from the content content = content.translate(str.maketrans('', '', string.punctuatio...
magicoder
python
You are tasked with creating a JavaScript function that dynamically generates a list of checkboxes and labels based on the data retrieved from a Firestore database. The function should take an array of objects as input, where each object represents a document from the database and contains a `title` attribute. The func...
```javascript function generateCheckboxes(data, containerId) { var container = $('#' + containerId); // Get the container element by ID data.forEach(function(doc) { var inputs = container.find('input'); var id = inputs.length + 1; $('<input />', { type: 'checkbox', name: 'category[]', i...
magicoder
javascript
You are tasked with creating a Python function that generates a unique temporary file path for a ZIP file. You will need to utilize the `pytest` library to create fixtures for this task. Write a function called `generate_zip_path` that takes no arguments and returns a unique temporary file path for a ZIP file. The fun...
```python import pytest import tempfile from pathlib import Path @pytest.fixture def zip_path(tmp_path): return tmp_path / "Unihan.zip" def generate_zip_path(): with tempfile.TemporaryDirectory() as temp_dir: temp_path = Path(temp_dir) / "Unihan.zip" return str(temp_path) # Test the generate_...
magicoder
python
You are given a list of candy names as strings. Your task is to write a function to sort the candy names in lexicographical order, ignoring the case of the letters. Additionally, the function should remove any duplicate candy names and return the sorted list of unique candy names. Function Signature: `def sort_unique_...
```python from typing import List def sort_unique_candies(candies: List[str]) -> List[str]: # Convert all candy names to lowercase for case-insensitive sorting candies = [candy.lower() for candy in candies] # Remove duplicates by converting the list to a set and then back to a list unique_candies ...
magicoder
python
You are tasked with implementing a function that processes 3D mesh data to calculate and set smooth normals for each vertex. The input to the function is a mesh object `newMesh` containing loops and polygons. The function should perform the following steps: 1. Create an array `clnors` of type 'f' (float) with initial v...
```python import array def calculate_smooth_normals(newMesh): # Step 1: Create an array of type 'f' with initial values of 0.0 clnors = array.array('f', [0.0] * (len(newMesh.loops) * 3)) # Step 2: Populate the clnors array with the normals of the loops in newMesh newMesh.loops.foreach_get("normal", cl...
magicoder
python
You are tasked with implementing an access control system for a bot application. The given code snippet defines the access controls for various bot commands. Each command is associated with a set of allowed users or groups. The `ACCESS_CONTROLS` dictionary maps each command to its corresponding access control settings....
```python ACCESS_CONTROLS = { 'restart': {'allowusers': BOT_ADMINS}, 'status': {'allowusers': BOT_ADMINS}, 'uptime': {'allowusers': BOT_ADMINS}, 'history': {'allowusers': BOT_ADMINS}, 'log tail': {'allowusers': BOT_ADMINS}, 'shutdown': {'allowusers': None}, 'status_gc': {'allowusers': None},...
magicoder
python
You are tasked with creating a Django migration for a travel application. The application has a model called `AccommodationPrice`, and you need to alter a field within this model. The field alteration involves changing the data type or constraints of a specific attribute in the `AccommodationPrice` model. Your task is...
```python from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('travelling', '0006_auto_20181128_1524'), ] operations = [ migrations.AlterField( model_name='accommodationprice', name='your_field_name', # Replace 'your_f...
magicoder
python
You are tasked with implementing a function that can parse a given file path and extract specific information from it. The file path follows a specific format, and your function should be able to handle various cases and extract the required details. Write a function `parseFilePath` that takes a file path as a string ...
```swift func parseFilePath(_ filePath: String) -> [String: String] { var fileInfo: [String: String] = [:] let components = filePath.components(separatedBy: "/") if components.count >= 2 { let path = components.dropLast().joined(separator: "/") let fileWithExtension = components.last! ...
magicoder
swift
You are tasked with implementing a class for registering auxiliary data types in a data processing system. The system should prevent registering two auxiliary data types with the same name but incompatible types. Your task is to design and implement the registration mechanism and ensure that attempting to register a du...
```cpp #include <iostream> #include <string> #include <unordered_map> #include <cassert> // Define the AuxDataContainer class class AuxDataContainer { public: // Define a type for the auxiliary data template <typename T> struct AuxDataType { static const std::string name; // Static member to hold ...
magicoder
cpp
You are tasked with designing a Rust program to manage and interact with systemd units using the provided modules. The `manager` module contains functionality for managing systemd units, the `service` module contains service-related functionality, the `systemd1_api` module provides an interface to interact with systemd...
```rust use manager::Manager; use service::Service; use systemd1_api::Systemd1Api; use systemdunit::SystemdUnit; fn main() { // Load a systemd unit file let unit_file = SystemdUnit::load("path_to_unit_file.service"); // Start a specific systemd service let service = Service::new("service_name"); m...
magicoder
rust
You are tasked with creating a program that simulates a comment and reply system. The program should allow users to post comments and reply to existing comments. Each comment has a user ID associated with it, and users can only delete their own comments. Replies to comments are stored in an array within the comment obj...
```php class CommentSystem { private $comments = []; public function addComment($userId, $commentText) { $comment = new Comment($userId, $commentText); $this->comments[] = $comment; } public function addReply($commentId, $replyText) { foreach ($this->comments as $comment) { ...
magicoder
php
You are tasked with implementing a custom exception class for handling errors in a GraphQL server. The exception class should be designed to provide detailed information about the error, including the GraphQL query, the specific field causing the error, and the error message. Your task is to create a custom exception ...
```csharp using System; public class GraphQLServerException : Exception { public string Query { get; } public string Field { get; } public string ErrorMessage { get; } public GraphQLServerException(string query, string field, string errorMessage) { Query = query; Field = field; ...
magicoder
csharp
You are tasked with implementing a function to build a hierarchical structure from a collection of Markdown blocks. Each block has a specified level, and the function should construct the structure based on the levels of the blocks. The function should take into account the nesting of blocks and update the current leve...
```csharp using System; using System.Collections.Generic; public class MarkdownBlock { public int Level { get; set; } // Other properties of MarkdownBlock } public class Solution { public int BuildBlock(MarkdownBlock block, Stack<MarkdownBlock> stack, int currentLevel) { if (block.Level > curr...
magicoder
csharp
You are tasked with implementing a custom data structure called `CustomStack` that simulates the behavior of a stack with additional functionality. The `CustomStack` should support the following operations: 1. `push(x)`: Add an element `x` to the top of the stack. 2. `pop()`: Remove the element at the top of the stack ...
```java class CustomStack { private int[] stack; private int top; public CustomStack(int maxSize) { stack = new int[maxSize]; top = -1; } public void push(int x) { if (top < stack.length - 1) { top++; stack[top] = x; } } ...
magicoder
java
You are tasked with implementing a Python function that processes a binary data buffer to extract and manipulate specific sets of double-precision floating-point values. The buffer contains serialized data representing various sets of double values, and your function needs to unpack and store these values in a specific...
```python import struct import copy class RobotState: def __init__(self): self.q_target = [] self.qd_target = [] self.qdd_target = [] def process_buffer(buf): rs = RobotState() offset = 0 # Unpack and store the first set of double values in rs.q_target rs.q_target = li...
magicoder
python
You are tasked with implementing a JIT (Just-In-Time) compiler for a simple programming language. The JIT compiler will take an Abstract Syntax Tree (AST) generated from the source code and produce machine code that can be executed directly by the CPU. Your task is to write a function that takes the AST as input and ge...
```rust fn jit_compile(ast: &AST) -> Result<MachineCode, CompilationError> { let mut machine_code = MachineCode::new(); for node in ast.traverse() { match node { Node::Expression(expr) => { let compiled_expr = compile_expression(expr)?; machine_code.append(co...
magicoder
rust
You are tasked with implementing a Python function that processes a given C++ class definition using the Clang library. The function should extract relevant information from the class definition and return a dictionary containing specific details about the class. The function signature is as follows: ```python def pro...
```python import clang.cindex def process_class_definition(node, scope_prefix, header_file): classdef = { "name": node.spelling, "scope_prefix": scope_prefix, "header_file": header_file, "base_class": None, "members": [] } for child in node.get_children(): i...
magicoder
python
You are tasked with creating a Python function that processes a given list of file paths and returns a dictionary containing the count of files grouped by their file extensions. The function should handle both absolute and relative file paths and should consider only the last part of the file name as the extension (e.g...
```python from typing import List, Dict import os def count_file_extensions(file_paths: List[str]) -> Dict[str, int]: file_extension_count = {} for file_path in file_paths: file_name = os.path.basename(file_path) _, file_extension = os.path.splitext(file_name) file_extension = file_exte...
magicoder
python
You are tasked with designing a Java class that represents a notification data structure for a media streaming application. The class should encapsulate various attributes related to a notification, including the action, flags, URI, MIME type, and additional key-value pairs as extras. Additionally, the class should con...
```java package org.acestream.engine.notification; import java.util.Map; import androidx.annotation.Keep; @Keep public class NotificationData { public String action; public int flags; public String uri; public String mime; public Map<String, String> extras; public BrowserIntentData target_url;...
magicoder
java
You are tasked with creating a Python script that generates a heatmap based on a given set of data points. The heatmap should visually represent the density of the data points in a 2D space. To accomplish this, you will need to implement a function that takes in the data points and produces a heatmap image. Your task ...
```python import numpy as np import ctypes def generate_heatmap(data_points, image_size): # Convert data points to C-compatible format data_array = np.array(data_points, dtype=np.float32) data_ptr = data_array.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) num_points = len(data_points) # Call the ...
magicoder
python
You are tasked with implementing a storage system for a web application. The system should support multiple storage backends, such as in-memory hash maps and Redis databases. The provided code snippet is a part of a Rust module that defines the storage interfaces and their implementations. Your task is to create a tra...
```rust // Define the Storage trait pub trait Storage { fn get(&self, key: &str) -> Option<String>; fn set(&mut self, key: &str, value: &str) -> Result<(), String>; } // Implement the Storage trait for in-memory hash map storage pub struct HashMapStorage { data: std::collections::HashMap<String, String>, }...
magicoder
rust
You are tasked with implementing a data structure to manage a network of interconnected ports. Each port can have multiple downstream ports, and when a port is updated, all its downstream ports should be updated as well. Your task is to create a Rust implementation for this data structure. You are given a code snippet...
```rust use std::cell::RefCell; use std::rc::Rc; struct PortCell<T> { value: RefCell<T>, downstreams: RefCell<Vec<Rc<Port<T>>>>, } impl<T> PortCell<T> { fn new(value: T) -> Self { PortCell { value: RefCell::new(value), downstreams: RefCell::new(Vec::new()), } } ...
magicoder
rust
You are tasked with implementing a Python class that represents a 2D rectangular grid world as a Gym environment. The grid world consists of cells, each of which can be in one of three states: empty, occupied by an obstacle, or containing a goal. The environment should support the following functionalities: 1. Initiali...
```python class GridWorldEnv: def __init__(self, rows, cols, obstacles, goals): self.rows = rows self.cols = cols self.obstacles = obstacles self.goals = goals def get_state(self, row, col) -> str: if (row, col) in self.obstacles: return "obstacle" el...
magicoder
python
You are tasked with creating a program to manage a library's collection of books and their respective authors. The program should allow users to add new books, add new authors, associate authors with books, and retrieve information about books and their authors. You are given the following code snippet as a starting p...
```csharp public class Book { public int BookId { get; set; } public string Title { get; set; } // Other properties and methods may be present here } public class BooksAuthors { public int BookId { get; set; } public int AuthorId { get; set; } public Book Book { get; set; } public Author Au...
magicoder
csharp
You are tasked with creating a Python class that manages settings loaded from a YAML file. Your goal is to implement the `SettingsModel` class, which should have the ability to load settings from a YAML file and provide functionality to retrieve the next URL from the loaded settings. The `SettingsModel` class should h...
```python import yaml class SettingsModel: def __init__(self): self.filename = None self.settings = {} def load_settings(self): with open(self.filename, 'r') as file: self.settings = yaml.load(file, Loader=yaml.FullLoader) def next_url(self): if 'urls' in self....
magicoder
python
You are tasked with creating a script to automate the deployment process for a web application. The script should perform several tasks in a specific order and handle potential errors gracefully. Your task is to write a shell script that accomplishes the following: 1. Run the command `app/console assetic:dump`. 2. Pri...
```bash #!/bin/bash # Function to handle errors handle_error() { echo "Error occurred: $1" exit 1 } # Run the command app/console assetic:dump echo "Running: app/console assetic:dump" if ! app/console assetic:dump; then handle_error "Failed to run assetic:dump" fi # Print the message --> Dump JS Routing... ech...
magicoder
shell
You are tasked with implementing a dependency resolution algorithm for a software package manager. The package manager maintains a list of dependencies for each package, where each dependency is represented as a tuple containing the name of the dependency and the version. The goal is to resolve the dependencies in a wa...
```python def resolve_dependencies(dependencies): graph = {} for package, version in dependencies: if package not in graph: graph[package] = set() graph[package].add(version) def dfs(package): if package in visited: return visited.add(package) ...
magicoder
python
You are tasked with implementing a memory management system for a video game console emulator. The system involves managing program (PRG) and character (CHR) memory pages. The provided code snippet is a part of the memory management module and contains a method for selecting a CHR memory page. The `select_chr_page` me...
```rust impl MemoryManager { fn select_chr_page(&mut self, slot: u16, page: u16, chr_memory_type: ChrMemoryType) { let proto = self.base_mapper(); let mask = proto.prg_mask; let start_slot = 0; // Define the start_slot value let end_slot = 3; // Define the end_slot value le...
magicoder
rust
You are tasked with implementing a generic type conversion system in C#. The system should allow for setting default type converters and adding conditional type converters based on certain criteria. Your task is to implement the `TypeConverterManager` class, which should provide the following functionality: 1. `SetDe...
```csharp using System; using System.Collections.Generic; using System.Reflection; public class ValueConverter<TType> { // Implementation of the type converter for a specific type // ... } public class ConverterTypeCollection { public Definition DefaultConverter { get; set; } // Other properties and m...
magicoder
csharp
You are tasked with creating a program to interact with a smart device management system using the Google Smart Device Management API. Your program needs to implement a function to retrieve and display a list of devices associated with a specific user. You are provided with a code snippet that includes a function `dum...
```rust use serde_json::Value; use reqwest::Error; static ENDPOINT: &str = "https://smartdevicemanagement.googleapis.com"; fn dump_list(list: &Vec<Value>, prefix: &str) { for value in list { println!("{} {:?}", prefix, value); } } fn list_devices(user_id: &str) -> Result<Vec<Value>, Error> { let ...
magicoder
rust
You are tasked with creating a script to update configuration settings in a file based on a given associative array of key-value pairs. The script should read the existing configuration file, search for each key, and update its corresponding value if the key exists. If the key does not exist, the script should add a ne...
```bash #!/bin/bash # Given associative array of key-value pairs declare -A value_of value_of=([key1]=value1 [key2]=value2 [key3]=value3) # Configuration file path CONFFILE="path_to_config_file.conf" # Loop through the associative array and update the configuration file for key in "${!value_of[@]}" do value=${va...
magicoder
shell
You are tasked with implementing a custom memory management system for a programming language. The system should support memory allocation, deallocation, and garbage collection. To achieve this, you need to create a MemoryManager class with the following functionalities: 1. `allocate(size: Int) -> Int`: This method sh...
```swift class MemoryManager { var memory: [Bool] init(size: Int) { memory = Array(repeating: false, count: size) } func allocate(size: Int) -> Int { var start = -1 var count = 0 for i in 0..<memory.count { if memory[i] { cou...
magicoder
swift
You are given a task to implement a data structure that supports two types of operations: 1. Update: Change the value at a specific position. 2. Query: Retrieve the sum of values within a given range. You need to implement a class `CustomArray` that supports the following operations: 1. `void change(int pos, int val)...
```cpp #include <iostream> #include <vector> using namespace std; class CustomArray { private: vector<int> arr; public: CustomArray(int n) : arr(n, 0) {} void change(int pos, int val) { arr[pos] = val; } int get(int l, int r) { int sum = 0; for (int i = l; i <= r; i++) { ...
magicoder
cpp
You are tasked with creating a Python function that dynamically patches a given function to replace specific bytecode operations with new ones. You will need to implement a function that takes in the original function, the index of the bytecode operation to be replaced, and the new bytecode operation, and then returns ...
```python from bytepatches.ops import Opcode, sync_ops, LOAD_FAST, STORE_FAST, JumpOp, LOAD_NAME, STORE_NAME from bytepatches.parser import Parser from bytepatches.utils import patch_function, make_bytecode def patch_bytecode(original_function, index, new_operation): # Parse the original function's bytecode pa...
magicoder
python
You are tasked with implementing a dependency injection container in TypeScript. Dependency injection is a design pattern in which a class receives its dependencies from external sources rather than creating them itself. In this problem, you will create a simple dependency injection container using TypeScript. Your ta...
```typescript // Define the Module interface interface Module { registerBindings(container: Container): void; } // Define the Container class class Container { private bindings: Map<string, any> = new Map(); bind<T>(key: string): BindingBuilder<T> { return new BindingBuilder<T>(key, this); } load(modul...
magicoder
typescript
You are tasked with implementing a custom dependency injection provider in a TypeScript application. The application uses Angular's dependency injection system, and you need to create a factory function that asynchronously provides an instance of the `AgendaService` class. Your task is to complete the implementation o...
```typescript { provide: AgendaService, useFactory: async (options) => { // Assuming AgendaService constructor takes options as a parameter const agendaService = new AgendaService(options); // Additional asynchronous initialization logic can be added here return agendaService; } } ```
magicoder
typescript
You are tasked with creating a PHP class that manages the configuration of form fields for a web application. The class should allow for the addition of various types of form fields and their corresponding attributes. Your task is to implement the `FormConfigurator` class with the following requirements: 1. The class ...
```php class FormConfigurator { private $configuration = []; public function addField($fieldName, $attributes) { $this->configuration[$fieldName] = $attributes; } public function getConfiguration() { return $this->configuration; } } // Example usage $formConfigurator = new...
magicoder
php
You are tasked with creating a program to encrypt and decrypt files using a custom encryption algorithm. The program should take three command-line arguments: the source file to be encrypted/decrypted, the destination file for the result, and a key for the encryption/decryption process. The key must be between 7 and 11...
```python import sys def encrypt_file(source_file, destination_file, key): try: with open(source_file, 'rb') as f_source, open(destination_file, 'wb') as f_dest: key_bytes = key.encode('utf-8') key_length = len(key_bytes) key_index = 0 while True: ...
magicoder
python
You are tasked with creating a program that extracts and counts the unique keywords from the `content` attribute of the `<meta>` tag in an HTML document. The `content` attribute contains a comma-separated list of keywords related to educational institutions in the state of New Mexico. Your program should parse the `con...
```python from collections import Counter import re # Sample content attribute from the meta tag content_attribute = "New Mexico, NM, College, University, Transfer, Higher Ed, UNM, ENMU, NMSU, NM Tech, WNMU, NMHU, IAIA, Navajo Tech, NNMC, CNM, CCC, Dine, Roswell, Ruidoso, LCC, Mesalands, NM Junior College, NMMI, NMSU ...
magicoder
python
You are tasked with implementing a function that calculates the total number of unique paths to reach the bottom-right corner of a grid from the top-left corner. You can only move either down or to the right at any point in time. The grid is represented by a 2D array where 1 indicates an obstacle and 0 indicates an emp...
```python from typing import List def unique_paths_with_obstacles(obstacle_grid: List[List[int]]) -> int: if obstacle_grid[0][0] == 1 or obstacle_grid[-1][-1] == 1: return 0 m, n = len(obstacle_grid), len(obstacle_grid[0]) dp = [[0] * n for _ in range(m)] dp[0][0] = 1 - obstacle_grid[0][0] ...
magicoder
python
You are tasked with creating a program that reads a text file and counts the occurrences of each word in the file. Your program should ignore punctuation and consider words in a case-insensitive manner. The program should then output the unique words along with their respective counts in alphabetical order. For exampl...
```python import string def count_word_occurrences(file_name): word_count = {} with open(file_name, 'r') as file: for line in file: line = line.lower().translate(str.maketrans('', '', string.punctuation)) words = line.split() for word in words: if wor...
magicoder
python
You are tasked with implementing a function that will display a grid of images using the matplotlib library in Python. The function should take a list of images and the number of images to display per row as input, and then generate a grid of subplots with the images displayed in each subplot. The function signature s...
```python import numpy as np import matplotlib.pyplot as plt def display_image_grid(images, images_per_row): num_images = len(images) grid_size = int(np.sqrt(num_images)) # Calculate the grid size based on the number of images fig, ax_array = plt.subplots(nrows=grid_size, ncols=grid_size, sharex=True, sha...
magicoder
python
You are given a string containing a series of parentheses. Each opening parenthesis "(" should be matched with a corresponding closing parenthesis ")" in the correct order. Your task is to write a function that determines whether the parentheses in the string are balanced. Write a function `isBalancedParentheses` that...
```python def isBalancedParentheses(s): stack = [] for char in s: if char == '(': stack.append(char) elif char == ')': if not stack: return False # Unmatched closing parenthesis stack.pop() return len(stack) == 0 # True if all parentheses...
magicoder
python
You are working on a natural language processing (NLP) project and need to train a model to classify sentences. The training process involves using the Vowpal Wabbit (VW) machine learning tool and Python scripts for performance evaluation. The code snippet provided is a part of the training and testing pipeline for the...
```python import subprocess def train_and_evaluate_model(weight, feature, dev_input_file, test_input_file, model_output_file, prediction_output_file): if feature: vw_command = f"vw --compressed -d {dev_input_file} --early_terminate 100 -k --keep l --keep g --keep {feature} -q gt -q ga -b 28 --loss_function...
magicoder
python
You are tasked with creating a Python program to scrape and analyze data from a web page using the Selenium library. The web page in question is the "https://movie.douban.com/typerank?type_name=剧情&type=11&interval_id=100:90&action=" which contains a list of top-rated drama movies on Douban. Your program should perform ...
```python from selenium import webdriver import time # Open the web page in a headless browser driver = webdriver.PhantomJS(executable_path=r'E:\Documents\Apps\phantomjs-2.1.1-windows\bin\phantomjs.exe') driver.get("https://movie.douban.com/typerank?type_name=剧情&type=11&interval_id=100:90&action=") # Wait for the pag...
magicoder
python
You are tasked with implementing a filtering mechanism for a list of `WorldCountry` objects based on certain criteria. Each `WorldCountry` object has properties for `Population` and `Area`, and a `Region` property indicating the region it belongs to. The filtering mechanism should allow filtering based on population an...
```csharp public class WorldCountry { public string Name { get; set; } public int Population { get; set; } public int Area { get; set; } public string Region { get; set; } } public class FilterCriteria { public int PopulationMin { get; set; } public int PopulationMax { get; set; } public in...
magicoder
csharp
You are tasked with creating a Python function that interacts with a SQLite database to manage image and face data. The database contains two tables: `images` and `faces`. The `images` table stores information about images, while the `faces` table stores information about faces detected in those images. The provided co...
```python import sqlite3 def add_image_with_faces(conn, image_id, image_path, detected_faces): try: c = conn.cursor() # Insert image record into images table c.execute(f"INSERT INTO images (image_id, image_path) VALUES (?, ?)", (image_id, image_path)) # Insert detected faces into ...
magicoder
python
You are tasked with designing a system to process and categorize incoming orders from different regions using Apache Kafka. The system should consist of producers for sending orders to specific topics, and consumers for processing and categorizing the orders based on their origin. Additionally, error handling should be...
To solve this problem, you can create the following Kafka topics, producers, and consumers, and implement the commands to manage the Kafka services: 1. Create Kafka Topics: - Create the following Kafka topics to handle orders from different regions: - xml-order-topic: Topic for sending all incoming orders. ...
magicoder
python
You are tasked with implementing a simplified version of a log replication system based on the Raft consensus algorithm. In Raft, a leader node is responsible for coordinating the replication of log entries across a cluster of nodes. The provided code snippet is a function that handles the processing of a "Ready" messa...
```cpp void flushReady(ReplicatedLogImpl *rl, yaraft::Ready *rd) { yaraft::pb::HardState *hs = nullptr; std::unique_ptr<yaraft::Ready> g(rd); // Check if the current node is the leader if (rd->currentLeader == rl->Id()) { // Process log entries and replicate to followers if (!rd->entries.empty()) { ...
magicoder
cpp
You are tasked with implementing a function that converts a given number into its English word representation. The function should support both integers and floating-point numbers. The conversion should handle numbers up to 999,999,999,999 (inclusive) and should correctly handle negative numbers. The output should not ...
```python from typing import Union ONES = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'] TEENS = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'] TENS = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'ei...
magicoder
python
You are tasked with implementing a function that calculates the squared distance between a moving segment and a moving triangle in 3D space. The provided code snippet is part of a larger program and shows the calculation of the squared distance between a segment and a triangle after both have been moved by certain tran...
```cpp template <typename Real> Real CalculateSquaredDistance(const Triangle3<Real>* mTriangle, Real t, const Vector3<Real>& velocity1, const Segment3<Real>* mSegment) { // Calculate the moved vertices of the triangle Vector3<Real> movedV0 = mTriangle->V[0] + t * velocity1; Vector3<Real> movedV1 = mTriangle...
magicoder
cpp
You are tasked with implementing a custom error handling system for a new programming language. The language supports defining custom error types with associated data. The provided code snippet shows a part of the error handling system, where custom error types are defined using the `#[error]` attribute. Your task is ...
```rust fn generate_error_handling_code(error_definitions: &[(String, Vec<String>)]) -> String { let mut code = String::new(); code.push_str("fn handle_error(error: &Error) {\n"); code.push_str(" match error {\n"); for (error_type, fields) in error_definitions { code.push_str(&format!(" ...
magicoder
rust
You are tasked with implementing a class hierarchy for different types of elements in a document editor. The elements include `ListElement`, `BulletedElement`, `NumberedElement`, and `CheckboxElement`. Each element has specific properties and behaviors that need to be implemented. Your task is to create a class hierar...
```java // Base class representing an element class Element { // Common properties and methods shared by all elements } // Subclass representing a list element class ListElement extends Element { private List<String> items; public void addItem(String item) { items.add(item); } } // Subclass r...
magicoder
java
You are given a code snippet that involves two arrays, `X_arai` and `Y_arai`, and two other arrays, `X_IZZI_MD` and `Y_IZZI_MD`. The code snippet assigns the values of `X_arai[i]` and `Y_arai[i]` to the last elements of `X_IZZI_MD` and `Y_IZZI_MD` respectively. Your task is to write a function that performs the same op...
```python def assignLastElement(X_arai, Y_arai, X_IZZI_MD, Y_IZZI_MD): X_IZZI_MD[-1] = X_arai[-1] Y_IZZI_MD[-1] = Y_arai[-1] return X_IZZI_MD, Y_IZZI_MD # Test the function X_arai = [1, 2, 3] Y_arai = [4, 5, 6] X_IZZI_MD = [7, 8, 9] Y_IZZI_MD = [10, 11, 12] modified_X_IZZI_MD, modified_Y_IZZI_MD = assignLa...
magicoder
python
You are tasked with creating a script to automate the installation of a specific version of Go programming language on a Linux system. The script should download the Go distribution, extract it to the appropriate directory, and create a symbolic link to the Go executable in the system's binary directory. Your script s...
```bash #!/bin/bash # Check if the version argument is provided if [ -z "$1" ]; then echo "Usage: $0 <go_version>" exit 1 fi # Assign the version argument to a variable GO_VERSION=$1 # Download the Go distribution tarball curl -L https://golang.org/dl/go$GO_VERSION.linux-amd64.tar.gz -o /tmp/go.tar.gz # Extract...
magicoder
shell
You are tasked with simulating a simplified version of a secure firmware update process for a trusted platform module (TPM). The process involves updating the firmware of a TPM chip with a new manifest and fragment files, and then reading out the metadata of the updated TPM. You are given a code snippet that demonstra...
```python import subprocess # Step 1: Load manifest and fragment files into the TPM manifest_file = "manifest_e140_p3_i.dat" fragment_file = "fragment_e140_p3_i.dat" tpm_id = "0xE140" exepath = "/path/to/executables" # Replace with actual path load_command = f"{exepath}/trustm_protected_update -k {tpm_id} -m {manife...
magicoder
python
You are tasked with creating a Python function that processes data from a pandas DataFrame and generates a color map for visualization. The function will take in a file path to a results file, a scoring method, and a color map name as input parameters. The function should read the data from the results file, extract un...
```python import pandas as pd import numpy as np import matplotlib.pyplot as plt def generate_color_map(results: str, scorer: str, cmap_name: str) -> None: df = pd.read_hdf(results) # Read data from the results file joints = list(np.unique(df.columns.get_level_values(1))) # Extract unique column values c...
magicoder
python
You are tasked with implementing a shopping cart feature for an e-commerce website. The provided code snippet includes the definition of the `ShopCartProps` interface and the `ShopCart` component. The `ShopCart` component is responsible for rendering the shopping cart items and providing functionality to remove items, ...
```typescript import React from 'react'; import ShopCartList from './ShopCartList'; interface ShopCartProps { cart: Image[]; total: number; length: number; removeFromCart: (item: Image) => void; clearCart: () => void; UseDiscountCode: (code: keyof Record<string, number>) => void; } const ShopCart: React.F...
magicoder
typescript
You are tasked with creating a Python function that processes a list of input file paths and extracts specific information from each path. The input file paths are in the format "LFN:/lhcb/MC/\<year\>/ALLSTREAMS.DST/\<file_id\>/\<file_id\>_\<part_id\>_2.AllStreams.dst", where \<year\> is the year of the data, \<file_id...
```python def extract_file_info(file_paths): file_info = {} for i, path in enumerate(file_paths): parts = path.split('/') year = parts[4] file_id, part_id = parts[6].split('_')[0], parts[6].split('_')[1] file_info[f'File{i+1}'] = {'Year': year, 'File ID': file_id, 'Part ID': part...
magicoder
python
You are tasked with implementing a simplified version of a command pattern in Java. The command pattern is a behavioral design pattern that turns a request into a stand-alone object that contains all information about the request. This allows for parameterizing clients with queues, requests, and operations. Your task i...
```java public interface Command { void execute(); } public class Light { public void turnOn() { System.out.println("Light is on"); } public void turnOff() { System.out.println("Light is off"); } } public class LightOnCommand implements Command { private Light light; publ...
magicoder
java
You are tasked with creating a program that checks the availability of a list of subdomains for a given domain. The program should take the domain name as a command-line argument and then iterate through a list of subdomains to check if they are accessible. If a subdomain is accessible, the program should print a messa...
```python import sys import requests from typing import List def check_subdomains(subdomains: List[str], domain: str) -> None: for sub in subdomains: url_to_check = f"http://{sub}.{domain}" try: response = requests.get(url_to_check) if response.status_code == 200: ...
magicoder
python
You are tasked with implementing a mesh generation algorithm that utilizes geo-references to create a mesh for a geographical area. The geo-references are represented as a set of latitude and longitude coordinates. The goal is to create a mesh that accurately represents the geographical features of the specified area. ...
```python class GeoReference: def __init__(self, latitude, longitude): self.latitude = latitude self.longitude = longitude class MeshGeoReference: def __init__(self, latitude, longitude): self.latitude = latitude self.longitude = longitude class Mesh: def generateMesh(self,...
magicoder
python