query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with creating a custom hook in React that manages the state of a modal component. The modal should be able to detect if it is in fullscreen mode, handle outside clicks to close itself, and adapt its behavior for mobile devices. Additionally, the hook should provide a selector function to access the modal...
```javascript import { useState, useEffect } from 'react'; export function useModal() { const [isFullscreen, setIsFullscreen] = useState(false); const [isMobile, setIsMobile] = useState(false); const [modalState, setModalState] = useState(/* initial modal state */); const checkIsFullscreen = () => { setIs...
magicoder
javascript
You are tasked with implementing a queue setup runner for a messaging system. The provided code snippet outlines the interface `IQueueSetupRunner`, which defines the structure for setting up and running a queue and its associated worker. Your task is to create a class `QueueSetupRunner` that implements the `IQueueSetu...
```typescript import { Queue } from 'queue-library'; // Assuming the existence of a queue library import { Worker } from 'worker-library'; // Assuming the existence of a worker library class QueueSetupRunner implements IQueueSetupRunner { Queue: Queue<any, any, string>; Worker: Worker<any, void, string>; Q...
magicoder
typescript
You are tasked with implementing a function to locate a dynamic library file in a macOS environment using Python. The function should utilize the `dyld_find` method to obtain the real path of the specified dynamic library file. If the `dyld_find` method raises a `ValueError`, the function should handle the exception an...
```python import os import sys import unittest def dyld_find(dylib: str) -> str: # Placeholder for the dyld_find method pass def locate_dynamic_library(dylib: str) -> str: try: return os.path.realpath(dyld_find(dylib)) except ValueError: raise ValueError('%s not found' % dylib) class ...
magicoder
python
You are tasked with implementing an image processing algorithm to enhance the sharpness of an image. The algorithm involves applying a Gaussian blur to the original image and then subtracting the blurred image from the original to obtain a sharper version. The formula for obtaining the sharper image is given by: sharp...
```python import numpy as np from scipy.ndimage import gaussian_filter def enhance_sharpness(image: np.ndarray, a: float, b: float) -> np.ndarray: blurred = gaussian_filter(image, sigma=10, mode='reflect') sharper = np.clip(image * a - blurred * b, 0, 1.0) return sharper ``` The `enhance_sharpness` functio...
magicoder
python
You are tasked with implementing a rendering engine for a 3D game. The game requires support for rendering textures on cube-shaped objects using OpenGL 2.1. The code snippet provided defines a macro `GT_Rendering_TextureCube_OpenGL21` which indicates the specific rendering mode to be used for this purpose. Your task i...
```c #include <OpenGL/gl.h> typedef struct { // Texture data structure // Include necessary fields for texture data } Texture; void renderTextureOnCube(Texture* texture) { // Set up the rendering mode based on the defined macro #ifdef GT_Rendering_TextureCube_OpenGL21 // Set up OpenGL 2.1 spec...
magicoder
c
You are working on a PHP application that utilizes the repository pattern for data access. The code snippet provided is a part of the repository implementation for managing comorbidities in the application. Your task is to implement a method within the `ComorbidadeRepositoryEloquent` class that retrieves all comorbidit...
```php namespace App\Repositories; use Prettus\Repository\Eloquent\BaseRepository; use Prettus\Repository\Criteria\RequestCriteria; use App\Repositories\ComorbidadeRepository; use App\Entities\Comorbidade; use App\Validators\ComorbidadeValidator; class ComorbidadeRepositoryEloquent extends BaseRepository implements C...
magicoder
php
You are tasked with implementing a function that calculates the dot product of two given vectors using the Accelerate framework in Swift. The Accelerate framework provides high-performance functions for mathematical operations on large datasets. The dot product of two vectors is the sum of the products of their corresp...
```swift import Accelerate func calculateDotProduct(_ vector1: [Double], _ vector2: [Double]) -> Double { precondition(vector1.count == vector2.count, "Vectors must have the same length") var result: Double = 0 vDSP_dotprD(vector1, 1, vector2, 1, &result, vDSP_Length(vector1.count)) return re...
magicoder
swift
You are tasked with creating a Python function that retrieves data from multiple network devices using gNMI (gRPC Network Management Interface). The function should take a list of network device details and a gNMI path as input, and then fetch the data from each device using the gNMI client. The retrieved data should b...
```python from gnmi.client import gNMIclient def retrieve_gnmi_data(hosts: list, paths: str) -> dict: data_dict = {} for host in hosts: with gNMIclient(target=(host["ip_address"], host["port"]), username=host["username"], password=host["password"], insecure=True) as gc: ...
magicoder
python
You are tasked with creating a custom annotation processor for a Java application. The application uses a custom annotation called `StorageReference` to mark fields in classes. The `StorageReference` annotation has two boolean attributes: `mapKey` and `mapValue`, with default values of `true` and `false` respectively. ...
```java import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.annotation.processing.SupportedSourceVersion; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; impor...
magicoder
java
You are tasked with implementing a Python function that simulates a simplified version of the `itertools` module. The `itertools` module provides various functions for creating iterators for efficient looping. Your task is to create a function that mimics the behavior of the `itertools.cycle` function. The `itertools....
```python def custom_cycle(iterable): while True: for element in iterable: yield element ``` The `custom_cycle` function uses a generator to yield elements from the input iterable indefinitely. It employs an infinite loop to repeatedly iterate through the elements of the input iterable, yieldin...
magicoder
python
You are working on a bioinformatics project and need to develop a Python script to analyze molecular dynamics trajectories. The code snippet provided initializes a molecular dynamics universe using the `mda.Universe` class and calculates the FH distances using the `Calc_FH_Dists` function. However, there are some incom...
```python import numpy as np import mda def calculate_R1_R2(distances): """ Calculate the R1 and R2 values for each distance value. Parameters: distances (ndarray): Array of distance values Returns: r1_values (ndarray): Array of R1 values r2_values (ndarray): Array of R2 values ...
magicoder
python
You are given a class `Node` representing a node in a tree structure. Each node has a pointer to its parent and a vector of children. Your task is to write a function `findMaxHeight` that takes a vector of nodes and returns the maximum height of the tree formed by these nodes. The height of a tree is defined as the le...
```cpp #include <vector> #include <algorithm> class Node { public: Node* parent; std::vector<Node*> children; void setParent(Node *theParent) { parent = theParent; parent->children.push_back(this); } }; int getHeight(Node* node) { if (node == nullptr) { return 0; } ...
magicoder
cpp
You are tasked with implementing a menu-driven program for array manipulation and sorting. The menu options allow the user to perform various operations on an array, including multiplication, sorting, and printing. The menu options are displayed as shown in the provided code snippet. Your task is to implement the func...
```python class ArrayManipulator: def __init__(self, array): self.array = array def _read(self, message): # Display the message to the user def multiply_array(self): factor = int(input("Enter the number to multiply the array by: ")) self.array = [element * factor for elemen...
magicoder
python
You are tasked with implementing a Python function that generates all possible subsets of a given list and then filters these subsets based on certain criteria. Your task is to complete the implementation of the function `generate_subsets` according to the following specifications: Function Signature: ```python def ge...
```python def generate_subsets(*args, exclude_empty=False) -> list: def all_subsets(lst): if not lst: return [[]] subsets = all_subsets(lst[1:]) return subsets + [subset + [lst[0]] for subset in subsets] listtmp = all_subsets(list(args)) if not args or (exclude_empty and...
magicoder
python
You are tasked with creating a Python class that processes and analyzes 3D point cloud data from the S3DIS dataset. The S3DIS dataset contains indoor point cloud data from various environments, such as offices, homes, and schools. Your class should be able to load the dataset, preprocess the point cloud data, and provi...
```python from datasets.s3dis import S3DIS import numpy as np class PointCloudAnalyzer: def __init__(self, dataset_path): self.dataset = S3DIS(dataset_path) self.loaded_data = None def load_data(self, room_number): self.loaded_data = self.dataset.load_point_cloud(room_number) def ...
magicoder
python
You are given a dictionary `data_dict` containing two keys: "sentence" and "label". The "sentence" key maps to a list of lists, where each inner list represents a sentence as a sequence of integers. The "label" key maps to a list of integers representing labels for each sentence. Your task is to write a function that t...
```python def extract_unique_sentences(data_dict): unique_sentences = {} for i in range(len(data_dict["sentence"])): sentence_tuple = tuple(data_dict["sentence"][i]) label = data_dict["label"][i] if sentence_tuple in unique_sentences: unique_sentences[sentence_tuple].append(l...
magicoder
python
You are tasked with creating a PHP function that processes a catalog of products and returns a specific output based on certain conditions. The catalog is represented as an associative array, where each key-value pair represents a product and its corresponding details. Your function should take this catalog array as in...
```php function processCatalog($catalog) { $totalProducts = count($catalog); $totalPrice = 0; $highestPrice = 0; $lowestPrice = PHP_INT_MAX; $highestPricedProduct = null; $lowestPricedProduct = null; foreach ($catalog as $product) { $totalPrice += $product['price']; if ...
magicoder
php
You are tasked with implementing a function to analyze a given code snippet and identify potential issues related to variable definitions and usage. The code snippet provided is a simplified representation of a static code analysis tool. The tool processes a set of code lines and identifies variable definitions and the...
```python def analyze_variable_usage(analysis): defined_variables = set() used_variables = set() issues = {} for line_num, line in analysis.lines.items(): if line.var: defined_variables.add(line.var_name) else: used_variables.update(get_variables_used_in_line(lin...
magicoder
python
You are tasked with creating a program that can analyze a given HTML file and count the occurrences of specific HTML tags within it. Your program should be able to handle nested tags and should provide the count of each tag found in the file. For this problem, you are given a sample HTML file snippet as follows: ```h...
```python from bs4 import BeautifulSoup def count_html_tags(html_snippet): soup = BeautifulSoup(html_snippet, 'html.parser') tag_counts = {} for tag in soup.find_all(): tag_name = tag.name if tag_name not in tag_counts: tag_counts[tag_name] = 1 else: tag_coun...
magicoder
python
You are tasked with creating a script to automate the process of extracting and executing a compressed file containing a shell script. Your script should handle the decompression of the file, extraction of its contents, setting executable permissions, and executing the shell script with any provided command-line argume...
```bash #!/bin/bash # Decompress the file bzip2 -d disttar.tar.bz2 # Extract the contents tar -xf disttar.tar # Set executable permissions chmod +x triana.sh # Execute the shell script with command-line arguments ./triana.sh $* ``` Save the above script in a file, for example, `automate_extraction.sh`, and make it...
magicoder
shell
You are working on a baking application that interfaces with a storage system to manage bakes and their attempts. The provided code snippet is part of a class that handles interactions with the storage system. Your task is to implement a method that filters and lists bakes based on certain criteria. You need to implem...
```python from typing import AsyncIterator, Optional, AbstractSet, List import datetime class Bake: pass # Placeholder for the Bake class class Attempt: pass # Placeholder for the Attempt class class YourClass: async def list_bakes( self, tags: AbstractSet[str] = frozenset(), si...
magicoder
python
You are tasked with implementing a class that simulates a simple notification system. The system should allow users to subscribe to different types of notifications and receive notifications when they are published. Each notification has a type and a message. Create a class `NotificationSystem` with the following meth...
```python class NotificationSystem: def __init__(self): self.subscriptions = {} def subscribe(self, user, notificationType): if notificationType not in self.subscriptions: self.subscriptions[notificationType] = set() self.subscriptions[notificationType].add(user) def un...
magicoder
python
You are tasked with creating a data validation system for a company's financial data. The system should enforce specific constraints on the properties of a `Company` class. The properties to be validated are `Description`, `RevenueUSD`, and `CEO`. The validation rules are as follows: 1. `Description` should have a max...
```csharp using System.Collections.Generic; using System.ComponentModel.DataAnnotations; public class CompanyValidator { public List<string> ValidateCompany(Company company) { var validationResults = new List<ValidationResult>(); var validationContext = new ValidationContext(company); ...
magicoder
csharp
You are tasked with implementing a function to read and process image data from an OpenEXR file format. The given code snippet contains a partial implementation of a function to write image data to an OpenEXR file. Your task is to complete the implementation by writing a function to read image data from an OpenEXR file...
```cpp #include <ImfRgbaFile.h> #include <ImfArray.h> #include <ImfNamespace.h> #include <ImfRgba.h> using namespace Imf; using namespace Imath; float* ReadEXR(const char *name, int& xRes, int& yRes) { RgbaInputFile file(name); Box2i dw = file.dataWindow(); xRes = dw.max.x - dw.min.x + 1; yRes = dw.ma...
magicoder
cpp
You are tasked with implementing a simplified version of a framebuffer attachment system for a graphics rendering API. The provided code snippet is a part of a class method that attaches a specified "Aov" (Arbitrary Output Variable) to the framebuffer. The method has the following behavior: - If the current Aov is not ...
```cpp void HdRprApiFramebuffer::AttachAs(lava::Aov aov) { if (m_aov != kAovNone || aov == kAovNone) { LAVA_ERROR_CHECK(m_context->SetAOV(m_aov, nullptr), "Failed to detach aov framebuffer"); } if (aov != kAovNone) { LAVA_ERROR_CHECK_THROW(m_context->SetAOV(aov, m_rprFb), "Failed to attach ...
magicoder
cpp
You are tasked with implementing a file management system for temporary Python files within a Swift struct. The struct `HTMLSummaryRenderer` is intended to serve as a summary renderer for HTML content. It contains a private property `tempPyFile` which is initialized with the path of a temporary Python file. Your task ...
```swift import Foundation protocol SummaryRenderer { // Protocol definition } public struct HTMLSummaryRenderer: SummaryRenderer { private let tempPyFile: URL init() { let dirPath = FileManager.default.temporaryDirectory tempPyFile = dirPath.appendingPathComponent(UUID().uuidString).appe...
magicoder
swift
You are tasked with implementing a spider class that simulates the movement of a spider on a 2D plane. The spider can move in four directions: up, down, left, and right. The spider starts at the origin (0, 0) on the plane and can move a specified number of steps in each direction. The spider's position is represented b...
```java public class Spider { private int x; private int y; public Spider() { this.x = 0; this.y = 0; } public void moveUp(int steps) { this.y += steps; } public void moveDown(int steps) { this.y -= steps; } public void moveLeft(int steps) { ...
magicoder
java
You are tasked with creating a Python function that generates an analysis index in Elasticsearch. The function should take in a list of fields and their data types, and then create an index with the specified fields in Elasticsearch. The function should handle potential errors and return the result of the index creatio...
```python from elasticsearch import Elasticsearch def create_analysis_index(fields): es = Elasticsearch() # Assuming Elasticsearch instance is already set up and accessible body = { "mappings": { "properties": { field: {"type": data_type} for field, data_type in fields.item...
magicoder
python
You are tasked with implementing a credit card number validation function. The function should take a credit card number as input and return a boolean value indicating whether the number is valid according to the Luhn algorithm and matches the pattern of a specific credit card provider. The Luhn algorithm is used to v...
```python import re def validate_credit_card(card_number: str, provider: str) -> bool: def luhn_checksum(card_number): digits = [int(x) for x in card_number] odd_digits = digits[-1::-2] even_digits = digits[-2::-2] checksum = sum(odd_digits) for digit in even_digits: ...
magicoder
python
You are tasked with creating a function to determine if the number of nodes in a distributed system that are in the process of recovering from a failure is less than a specified quorum. The function `assert_minority_of_nodes_recovering` takes two parameters: `quorum`, an integer representing the minimum number of nodes...
```rust pub enum VrState { Normal, Recovery(u64), } pub fn assert_minority_of_nodes_recovering(quorum: usize, states: &[VrState]) -> Result<(), String> { let mut recovering_count = 0; for state in states { if let VrState::Recovery(_) = *state { recovering_count += 1; } }...
magicoder
rust
You are tasked with creating a function that processes an order detail and generates an HTML table to display the order information. The function should take in an associative array representing the order details and return a string containing the HTML code for the table. The order details array will have the followin...
```php function generateOrderTable($orderDetails) { $html = '<div class="container order my-4"> <div class="row align-items-center"> <div class="col-sm-10"> <h4>Order detail</h4> <table class="w-100">'; foreach ($orderDetai...
magicoder
php
You are tasked with implementing a function that parses and extracts information from an SVG (Scalable Vector Graphics) code snippet. The SVG snippet represents a transformation and a group element within an SVG file. Your task is to write a function that takes the SVG snippet as input and extracts the following infor...
```python import re def parse_svg_snippet(svg_snippet: str) -> dict: pattern = r'transform="(\w+)\(([\d.,\s]+)\)"\s*>\s*<g id="(\w+)">' match = re.search(pattern, svg_snippet) if match: transformation_type = match.group(1) transformation_parameters = match.group(2).split(', ') group...
magicoder
python
You are tasked with implementing a data structure that supports the following operations efficiently: 1. `append(color)`: Add the specified color to the end of the data structure. 2. `appendleft(color)`: Add the specified color to the beginning of the data structure. 3. `pop()`: Remove and return the last color from t...
```python from collections import deque class ColorQueue: def __init__(self): self._colors = deque() def append(self, color): self._colors.append(color) def appendleft(self, color): self._colors.appendleft(color) def pop(self): return self._colors.pop() def pople...
magicoder
python
You are tasked with implementing a generic repository pattern using Entity Framework Core for a help desk application. The provided code snippet is a partial implementation of the `EfCoreTagRepository` class, which is responsible for interacting with the database to perform CRUD operations on `Tag` entities. Your task...
```csharp namespace Acme.HelpDesk.Tags { public class EfCoreTagRepository : EfCoreRepository<HelpDeskDbContext, Tag, Guid>, ITagRepository { public EfCoreTagRepository(IDbContextProvider<HelpDeskDbContext> dbContextProvider) : base(dbContextProvider) { } public Tag ...
magicoder
csharp
You are tasked with implementing a function that processes a CSV file and returns the average value of a specified column. The CSV file contains data in the form of rows and columns, with the first row containing the column headers. The function should take the file path and the column name as input and return the aver...
```cpp #include <fstream> #include <sstream> #include <iostream> #include <vector> #include <unordered_map> double calculateAverageFromCSV(const std::string& filePath, const std::string& columnName) { std::ifstream file(filePath); if (!file.is_open()) { std::cerr << "Error: Unable to open file " << fil...
magicoder
cpp
You are tasked with implementing a simple currency conversion system in Python. Your task is to create a class `CurrencyConverter` that can convert an amount from one currency to another. The class should handle two custom exceptions: `InvalidAmountError` and `CurrencyMismatchError`. The `CurrencyConverter` class shou...
```python class InvalidAmountError(ValueError): def __init__(self): super().__init__("Invalid amount for currency") class CurrencyMismatchError(ValueError): pass class CurrencyConverter: def __init__(self, exchange_rates): self.exchange_rates = exchange_rates def convert(self, amoun...
magicoder
python
You are tasked with creating a program that analyzes the information provided in the code snippets related to the game Among Us. The snippets contain details about the number of vents and rooms in two different maps, MIRA HQ and Polus. Your program should extract and process this information to generate a summary repor...
```python import re def analyze_among_us_maps(code_snippet): map_info = {} # Extract information for MIRA HQ mira_vents_match = re.search(r"There are a total of __\*\*(\d+)\*\*__ vents on this map", code_snippet) mira_guide_link_match = re.search(r"Here it is__:\n(https://[^\s]+)", code_snippet) ...
magicoder
python
You are tasked with simulating the behavior of a web page's JavaScript execution using a simplified model. Your goal is to implement a function that emulates the behavior of the `requestAnimationFrame` function and a function that waits for a JavaScript condition to be true. You are provided with the following code sn...
```javascript // Simulated requestAnimationFrame function function myRequestAnimationFrame(callback) { setTimeout(callback, 0); // Simulate immediate execution } // Simulated WaitForJavaScriptCondition function function waitForCondition(condition) { return new Promise((resolve) => { const interval = setInterva...
magicoder
javascript
You are tasked with creating a Python function that interacts with a C library using the `ctypes` module. The C library provides functionality for parsing and processing Markdown text. Your goal is to implement a Python function that can utilize this C library to parse a given Markdown string and return the resulting H...
```python from ctypes import CDLL, c_char_p, c_size_t, c_int from pathlib import Path import platform def _libcmark(): system = platform.system() if system == 'Darwin': # Load the C library on macOS libcmark = CDLL("lib/cmark.dylib") elif system == 'Windows': # Load the C library o...
magicoder
python
You are tasked with implementing a function that converts a given Swift array into a JavaScript array using the N-API library. The N-API library provides a set of functions for interacting with JavaScript objects and values from native addon modules in Node.js. You are provided with a partial code snippet that demonst...
```swift import NAPI func convertToJSArray(_ env: napi_env, _ inputArray: [Int]) throws -> napi_value { var result: napi_value? let status = napi_create_array_with_length(env, inputArray.count, &result) guard status == napi_ok else { throw NAPI.Error(status) } for (index, element) in inputArray.enume...
magicoder
swift
You are tasked with implementing a state class for an AI system in a game server. The state class, `EquippedEntityState`, is responsible for tracking the entity currently equipped in the active hand of a game character. Your goal is to complete the implementation of the `EquippedEntityState` class by defining the neces...
```csharp namespace Content.Server.AI.WorldState.States.Inventory { /// <summary> /// AKA what's in active hand /// </summary> [UsedImplicitly] public sealed class EquippedEntityState : StateData<IEntity> { // Add a property to store the currently equipped entity public IEntity E...
magicoder
csharp
You are tasked with implementing a custom breakpoint handler for a specific architecture. The provided code snippet is a part of a larger system that handles breakpoints in a low-level context. Your goal is to complete the implementation of the `breakpoint_program_exited` function for the ARM and AArch64 architectures....
```rust pub const SOLID_BP_CSABORT: usize = 16; #[inline(always)] pub fn breakpoint_program_exited(tid: usize) { unsafe { match () { #[cfg(target_arch = "arm")] () => asm!("bkpt #{}", const SOLID_BP_CSABORT, in("r0") tid), #[cfg(target_arch = "aarch64")] () =...
magicoder
rust
You are tasked with implementing a function that processes an enum definition in a Rust program. The enum definition is represented as a code snippet, and your task is to extract information about the enum variants and their associated data. You are given a code snippet that represents a part of a Rust program: ```ru...
```rust use std::collections::HashMap; struct EnumInfo { variants: Vec<String>, associated_data: HashMap<String, Vec<String>>, } fn resolve_enum_def(enum_definition: &str) -> EnumInfo { let mut variants = Vec::new(); let mut associated_data = HashMap::new(); let lines: Vec<&str> = enum_definition...
magicoder
rust
You are tasked with implementing a Python C++ extension module for a media player application. The provided code snippet is a part of the C++ code for the module. The `Py_INCREF` function is used to increment the reference count of a Python object, and `reinterpret_cast` is used to convert a pointer to one type to a po...
```cpp static PyObject* _exit_MediaPlayer(py::wrapper::Windows::Media::Playback::MediaPlayer* self) noexcept { // Add code to handle the exit process of the media player // Perform any necessary cleanup and resource release // Example: releasing resources and handling errors if (self) { // Perf...
magicoder
cpp
You are tasked with implementing a custom exception class for handling host-related errors in a networking application. The provided code snippet is a static method within a class that returns a new instance of the class with a specific error message. Your task is to create the custom exception class and implement the ...
```php class HostException extends Exception { public static function hostDoesNotExist(string $hostName): self { return new static("The host named `{$hostName}` does not exist."); } } ``` In the solution, we define a custom exception class `HostException` that extends the base PHP `Exception` class...
magicoder
php
You are tasked with implementing a class to manage a table in a graphical user interface (GUI) application. The table is represented by a 2D grid with rows and columns. The provided code snippet is a part of the initialization process for the table. The `deleteTable` is an instance of a class that represents the table ...
```python class TableManager: def __init__(self, deleteTable): self.deleteTable = deleteTable self.deleteTable.setColumnCount(9) self.deleteTable.setRowCount(0) item = QtWidgets.QTableWidgetItem() self.deleteTable.setHorizontalHeaderItem(0, item) item = QtWidgets.QTa...
magicoder
python
You are tasked with implementing a Python decorator that allows overriding of function parameters at call time. The decorator should take care of handling the parameter overrides and ensure that the function is called with the correct set of parameters. You are given the following code snippet as a starting point: ```...
```python def override_params(func): def wrapper(*args, **kwargs): if len(args) < 2 or not isinstance(args[1], dict): raise ValueError("Second argument must be a dictionary for parameter overrides") original_args = list(args) original_kwargs = kwargs.copy() overl...
magicoder
python
You are given a Python class `LinkedList` which represents a singly linked list. The class has the following attributes and methods: - `head`: a reference to the first node in the linked list - `remove(value)`: a method that removes the first occurrence of the specified value from the linked list - `prilst`: a list tha...
```python class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None self.prilst = [] def remove(self, value): current = self.head prev = None found = False while current an...
magicoder
python
You are tasked with implementing a file identity generator tool that can optionally quarantine duplicate files. The tool should also have the ability to generate full file hashes, prevent hashing the contents of files, hash only the container, and provide an option to silence the output. Your task is to implement the ...
```python import argparse import os import hashlib import shutil def file_identity_generator(allow_quarantine, long_hash, raw, silent): # Process command-line arguments parser = argparse.ArgumentParser(description="Generates File Identities with an option to quarantine duplicates") parser.add_argument("--a...
magicoder
python
You are tasked with creating a PHP class that represents a destination and allows for the manipulation of destination data. The class should include methods for setting and getting the destination's name, location, description, and image. Your task is to complete the `destinasi` class by adding the necessary methods t...
```php class destinasi extends Model { protected $table = 'destinasis'; protected $fillable = ['namadestinasi','lokasidestinasi','deskripsi','gambardestinasi']; protected $name; protected $location; protected $description; protected $image; public function setName($name) { $this->name = $name; } ...
magicoder
php
You are tasked with creating a command-line tool to generate documentation for GraphQL schemas. The tool should take a schema file as input and generate documentation in a specified output directory. The tool should also have an option to force overwrite existing documentation in the output directory. Your task is to ...
```javascript const fs = require('fs'); const path = require('path'); const readline = require('readline'); function generateDocumentation(schemaFile, outputDir, forceOverwrite) { // Validate schema file existence if (!fs.existsSync(schemaFile)) { console.error(`Error: Schema file '${schemaFile}' not found.`);...
magicoder
javascript
You are tasked with creating a Python class that simulates a command line wrapper. The class, `CommandWrapper`, is responsible for executing a command and logging its output. The class has the following attributes: - `out_log`: A string representing the file path for the standard output log. If `None`, the output will ...
The `launch` method of the `CommandWrapper` class is implemented to construct the command, execute it, and handle the output and logging based on the attributes provided. The method uses the `subprocess` module to execute the command and handle the output redirection. It also appends the command and its exit code to th...
magicoder
python
You are tasked with implementing a function to perform a deep copy of a multi-dimensional array structure in C. The array structure is defined as follows: ```c typedef struct { size_t dims; // number of dimensions size_t *size; // array of dimension sizes void *data; // pointer to the array data } Array; `...
```c #include <stdlib.h> #include <string.h> typedef struct { size_t dims; // number of dimensions size_t *size; // array of dimension sizes void *data; // pointer to the array data } Array; Array* deepCopyArray(const Array *src) { Array *dst = (Array*)malloc(sizeof(Array)); if (dst == NULL) { ...
magicoder
c
You are tasked with implementing a custom exception class and handling it within a given code snippet. The code snippet provided is a part of a constructor in a C# class. The `_commitStorage` variable is being assigned a value, which is checked for null using the null-coalescing operator (`??`). If the value is null, a...
```csharp using System; public class CommitStorageNullException : ArgumentNullException { public CommitStorageNullException(string paramName) : base(paramName, "Commit storage cannot be null.") { } } public class ExampleClass { private readonly object _commitStorage; public ExampleClass(object co...
magicoder
csharp
You are tasked with implementing a simple JWT (JSON Web Token) authentication system in Python. Your goal is to create three functions: `obtain_jwt_token`, `refresh_jwt_token`, and `verify_jwt_token`, which will handle the generation, refreshing, and verification of JWT tokens, respectively. The `obtain_jwt_token` fun...
```python import jwt from datetime import datetime, timedelta JWT_SECRET_KEY = "my_secret_key" def obtain_jwt_token(username, password): # Check if the username and password are valid (dummy validation for demonstration) if username == "user" and password == "password": payload = { "userna...
magicoder
python
You are tasked with implementing a simplified version of a button handling system in a Swift application. The provided code snippet is part of a class that manages button interactions. The `buttonPressed` method is called when a button is pressed, and it is overridden by a subclass to define specific behavior for each ...
```swift // Define a protocol for button behavior protocol Button { func buttonPressed() } // Implement a class for a round button conforming to the Button protocol class RoundButton: Button { func buttonPressed() { print("Round button pressed") } } // Implement a class for a square button conform...
magicoder
swift
You are tasked with creating a Python decorator that adds functionality to a web application built using the Django framework. The decorator should check if a user is authenticated before allowing access to a specific view function. If the user is authenticated, the view function should be executed as normal. If the us...
```python from django import http from functools import wraps def my_decorator(func): '''自定义的装饰器:判断是否登录,如果登录,执行func ,未登录,返回json''' @wraps(func) def wrapper(request, *args, **kwargs): if request.user.is_authenticated: # If the user is authenticated, execute the view function ...
magicoder
python
You are tasked with implementing a trait for a client in a Rust application. The trait, `ClientBase`, is defined in the `mitrid_core` and `crypto` modules and has several associated types and methods. Your goal is to create a struct `Client` that implements this trait and satisfies all its requirements. The `ClientBas...
```rust use mitrid_core::io::Client as ClientBase; use crypto::Digest; use io::Address; use io::ClientTransport; // Define the Client struct #[derive(Clone)] pub struct Client; // Implement the ClientBase trait for the Client struct impl ClientBase<ClientTransport, Address, (), Digest, Vec<u8>> for Client { // Im...
magicoder
rust
You are tasked with implementing a validation function in TypeScript that composes multiple validation functions into a single validation function. The provided code snippet offers a starting point for the `composeValidations` function, which takes an arbitrary number of validation functions as arguments and returns a ...
```typescript export function composeValidations(...validations: ((value: any) => string | undefined)[]) { return (value: any) => { for (const validation of validations) { const result = validation(value); if (result !== undefined) { return result; } } return undefined; }; } c...
magicoder
typescript
You are tasked with implementing a Flask route that authorizes access to a web application based on the user's GitHub credentials. The provided code snippet is a part of a Flask application and includes a Blueprint for handling authorization. The Blueprint is named "auth_protected" and is intended to be used for protec...
```python from flask import jsonify @auth_protected.route('/authorize', methods=['POST']) def authorize_user(): data = request.get_json() if 'username' in data and 'token' in data: github_username = data['username'] github_token = data['token'] try: github = Github(github_to...
magicoder
python
You are tasked with creating a Python program that simulates a countdown with a twist. The program should display a countdown from 10 to 1, with a delay of 1 second between each count. However, instead of displaying the numbers in a regular sequence, the program should alternate between displaying the numbers in ascend...
```python from time import sleep ascending = True for i in range(10, 0, -1): print(i) sleep(1) if ascending: i -= 1 else: i += 1 ascending = not ascending print('Yeey!!') ``` The program starts by setting the `ascending` flag to `True`. It then enters a loop that iterates from 10 ...
magicoder
python
You are tasked with creating a Python function that connects to a database and imports data from it. Your function should handle potential connection issues by implementing a retry mechanism with a specified delay between retries. Write a function `import_data_from_db` that takes the following parameters: - `db_con`: ...
```python import time import sqlalchemy as sqla def import_data_from_db(db_con, retry_count, delay): attempt = 1 while attempt <= retry_count: try: print('Connecting to {}'.format(db_con)) engine = sqla.create_engine(db_con, isolation_level="AUTOCOMMIT") imported_dat...
magicoder
python
You are tasked with creating a Python function that converts a multi-page PDF into a series of images. The function should take the file path of the PDF as input and save each page of the PDF as a separate JPEG image. You should use the `convert_from_path` function from the `pdf2image` library to achieve this. The fun...
```python from pdf2image import convert_from_path import os def convert_pdf_to_images(pdf_path: str) -> None: # Convert pages into images pages = convert_from_path(pdf_path) # Save the pages in JPEG format for i, page in enumerate(pages): image_path = f'page_{i+1}.jpg' page.save(image_...
magicoder
python
You are tasked with creating a Python program to automate the process of formatting an Excel spreadsheet. Your program should read data from a given input file, adjust the column widths based on the maximum length of the data in each column, and then save the formatted spreadsheet to a specified output file. Your prog...
```python import openpyxl # Step 1: Read data from the input Excel file input_file_path = 'input.xlsx' output_file_path = '/tmp/MC-Templates.xlsx' wb = openpyxl.load_workbook(input_file_path) ws = wb.active # Step 2: Iterate through each column to adjust column widths for column_cells in ws.columns: length = max(...
magicoder
python
You are tasked with implementing a custom authentication guard for a Node.js application using NestJS. The application uses a local strategy for authentication, and the guard needs to extend the `AuthGuard` class provided by NestJS. Your goal is to create a custom `Guard` class that extends the `AuthGuard` and triggers...
```typescript import { Injectable } from '@nestjs/common'; import { AuthGuard } from '@nestjs/passport'; @Injectable() export class Guard extends AuthGuard('local') { async canActivate(context: ExecutionContext): Promise<boolean> { const request = context.switchToHttp().getRequest(); // Perform any additiona...
magicoder
typescript
You are tasked with creating a Python class that manages user information using the Bonita platform. The class should be able to initialize a Bonita client and perform various user management operations. Your task is to complete the implementation of the `User` class by adding methods for user creation, retrieval, upda...
```python from .base import Base from bonita.api.bonita_client import BonitaClient class User(Base): """Manage user""" def run(self): self.bonita_client = BonitaClient(self.loadConfiguration()) def create_user(self, user_data): # Implement user creation logic using BonitaClient pa...
magicoder
python
You are tasked with implementing a function that extracts the session name from a given string. The session name is defined as the substring between the first occurrence of the characters "session_" and the subsequent occurrence of the characters "_id". If the session name cannot be inferred from the input string, the ...
```python def extract_session_name(input_string): start_index = input_string.find("session_") if start_index != -1: end_index = input_string.find("_id", start_index) if end_index != -1: session_name = input_string[start_index + len("session_"):end_index] return session_na...
magicoder
python
You are tasked with implementing a custom dataset class for a computer vision project. The dataset will contain images that are semi-aligned, meaning that each image is a pair of two sub-images, where one sub-image is a cropped portion of the other. Your goal is to create a custom dataset class that loads and preproces...
```python from PIL import Image import os import torch from torch.utils.data import Dataset class SemiAlignedDataset(Dataset): def __init__(self, root_dir, transform=None): self.root_dir = root_dir self.transform = transform self.image_pairs = os.listdir(root_dir) def __len__(self): ...
magicoder
python
You are given a partial implementation of a unit testing framework in C++. The provided code snippet is part of the main function that runs the test cases and reports the results. Your task is to complete the implementation of the `UnitTests` class and the `run_test_case` function to enable the framework to execute and...
```cpp #include <iostream> #include <string> #include <vector> class UnitTests { public: UnitTests(void (*test_func)(void), const char* test_name) : test_func(test_func), test_name(test_name) {} int run_test_cases(const std::string& tc_id, int& tests_ran) { int failed_tests = 0; if (tc_id.empt...
magicoder
cpp
You are tasked with implementing a class `MatrixSolver` that can perform certain operations on matrices. The class should have a method `get(row, col)` that returns the value at the specified row and column of the matrix. Additionally, the class should support the creation of two instances, `ms1` and `ms2`, and the cod...
```javascript class MatrixSolver { constructor(matrix) { this.matrix = matrix; } get(row, col) { if (row < 0 || col < 0 || row >= this.matrix.length || col >= this.matrix[0].length) { return 0; // Assuming out-of-bounds access returns 0 } return this.matrix[row][col]; } } // Test cases c...
magicoder
javascript
You are tasked with implementing a simplified version of the Arduino Serial library in C. The Arduino Serial library provides a way for Arduino boards to communicate with the computer via a serial connection. Your task is to create a C program that simulates the basic functionality of this library for sending and recei...
```c #include <stdio.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <termios.h> int serial_port; int init_serial(const char *port, speed_t baud_rate) { serial_port = open(port, O_RDWR); if (serial_port < 0) { perror("Error opening serial port"); retur...
magicoder
c
You are tasked with implementing a simplified version of a request store using MobX, a popular state management library for React applications. The request store is responsible for managing asynchronous requests and their associated state. Your goal is to create a class that represents the request store and its functio...
```typescript import { makeAutoObservable, runInAction } from 'mobx' import { CancellablePromise } from 'real-cancellable-promise' export class RequestStore { requests: CancellablePromise<any>[] = [] error: string = '' isLoading: boolean = false constructor() { makeAutoObservable(this) } addRequest(r...
magicoder
typescript
You are tasked with implementing a thread-safe queue using a mutex and condition variable in C++. The queue should support the following operations: 1. `push`: Add an element to the queue. 2. `pop`: Remove and return the front element from the queue. If the queue is empty, block until an element is available. 3. `empty...
```cpp #include <mutex> #include <condition_variable> #include <queue> template <typename T> class ThreadSafeQueue { public: void push(const T& value) { std::unique_lock<std::mutex> lock(m_mutex); m_queue.push(value); lock.unlock(); // Unlock before notifying to avoid waking up the waiting...
magicoder
cpp
You are tasked with creating a program that simulates a simple access control system for a command-line interface. The system will use a set of checks to allow or deny a user's access to a command. Your goal is to implement the logic for the access control system using Rust. You are given the following code snippet as...
```rust use std::collections::HashSet; use std::fmt; use serenity::futures::future::BoxFuture; use serenity::model::channel::Message; struct AccessControl { checks: HashSet<Box<dyn Fn(&Message) -> bool>>, } impl AccessControl { fn new() -> Self { AccessControl { checks: HashSet::new(), ...
magicoder
rust
You are given a list of positive integers representing the lengths of different files. Your task is to merge these files into a single file. The cost of merging two files is equal to the sum of their lengths. You need to determine the minimum cost of merging all the files into a single file. For example, given the lis...
```python from typing import List def min_merge_length(file_lengths: List[int]) -> int: total_cost = 0 while len(file_lengths) > 1: file_lengths.sort() # Sort the list to merge the smallest files first merge_cost = file_lengths[0] + file_lengths[1] # Calculate the cost of merging the smallest...
magicoder
python
You are tasked with creating a Python function that merges a given configuration dictionary with a set of default values. The default values are provided in a nested dictionary structure, and the function should recursively merge the default values with the given configuration, prioritizing the values in the configurat...
```python def merge_config_defaults(config: dict, defaults: dict) -> dict: merged = defaults.copy() for key, value in config.items(): if isinstance(value, dict) and key in defaults and isinstance(defaults[key], dict): merged[key] = merge_config_defaults(value, defaults[key]) else: ...
magicoder
python
You are tasked with creating a filtering system for a product catalog. The provided code snippet is a part of a Django web application that handles the filtering of products based on user input. The `advanced_filter` function takes a request object and filters the products based on the user's specified criteria. The fu...
```python def advanced_filter_with_price(request): """Used to filter out products based on various criteria including price range""" products = Product.objects.all() # Apply existing filters for name, type, and company if request.GET.get("name_filter"): products = products.filter(name__icontain...
magicoder
python
You are tasked with creating a program that simulates a simple text decryption tool. The program should take an encrypted text as input and decrypt it using a specific algorithm. The decryption algorithm involves reversing the characters of the input text and displaying the decrypted text in a GUI window. You are prov...
```python import tkinter as tk def decrypt_text(encrypted_text): decrypted_text = encrypted_text[::-1] # Reverse the characters of the encrypted text return decrypted_text def display_decrypted_text(encrypted_text): root = tk.Tk() secondframe = tk.Frame(root) secondframe.pack() text_decr...
magicoder
python
You are tasked with creating a Django migration for a new model that includes a custom field. The custom field should be a subclass of `django.db.models.Field` and should store a specific type of data. Your task is to implement the custom field and use it in the migration to create the new model. Create a custom field...
```python # CustomIntegerField definition from django.core.exceptions import ValidationError from django.db import models class CustomIntegerField(models.Field): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def validate(self, value, model_instance): if not isinstance(...
magicoder
python
You are tasked with creating a Bash script that takes two input numbers from the user and calculates their product. However, the given code snippet contains some errors that need to be fixed before the script can function properly. Your task is to identify and correct these errors to ensure the script runs as intended....
The corrected code snippet is as follows: ```bash #!/bin/bash echo -e "You SHOULD input 2 numbers; program will cross these two numbers" read -p "first number: " first read -p "second number: " second total=$(( $first * $second )) echo "The product of $first and $second is: $total" ``` Explanation: 1. The shebang ...
magicoder
shell
You are tasked with creating a program that reads and processes data from two files: "config/labels.txt" and "config/train.txt". The "labels.txt" file contains a list of labels, with each label on a separate line. The "train.txt" file contains a list of image file paths, with each path on a separate line. Your program ...
```python def countNonEmptyLines(labels_file_path, images_file_path): classes_qtd = 0 images_qtd = 0 with open(labels_file_path, 'r') as labels_file: for line in labels_file: if line.strip(): classes_qtd += 1 with open(images_file_path, 'r') as images_file: ...
magicoder
python
You are tasked with implementing a function that takes a list of strings as input and returns the frequency of each word in the list. A word is defined as a sequence of non-whitespace characters. The function should ignore case sensitivity and consider words with different cases as the same word. The output should be a...
```python def word_frequency(words): frequency = {} for word in words: word = word.lower() if word in frequency: frequency[word] += 1 else: frequency[word] = 1 return frequency input_list = ["Lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipiscing...
magicoder
python
You are tasked with creating a Python function that resizes an input image using the OpenCV library and then displays the resized image in a window. Your function should take the input image file path, target width, and target height as parameters, and it should use the INTER_AREA interpolation method for resizing. The...
```python import cv2 def resize_and_display_image(image_path: str, target_width: int, target_height: int) -> None: # Read the input image image = cv2.imread(image_path) # Resize the image using INTER_AREA interpolation resized_image = cv2.resize(image, (target_width, target_height), interpolation=cv2....
magicoder
python
You are given a string representing a series of coordinates in the format "x1-y1,x2-y2,x3-y3...". Each coordinate pair represents a point on a 2D plane. Your task is to write a function to calculate the total distance traveled when moving from the first point to the last point in the given order. The distance between ...
```python import math def calculateTotalDistance(coordinates: str) -> float: points = coordinates.split(',') total_distance = 0.0 for i in range(len(points) - 1): x1, y1 = map(float, points[i].split('-')) x2, y2 = map(float, points[i + 1].split('-')) distance = math.sqrt((x2 - x1) *...
magicoder
python
You are working on a computer graphics project that involves processing RGB point clouds for direct rendering. The code snippet provided is a part of a larger program that processes RGB point clouds and performs rasterization and blending for visualization. Your task is to implement a function that takes in RGB point c...
```python import torch def rasterize_and_blend(pcs_rgb, n_views, pointcloud_source="joint"): # Get RGB pointcloud as well for direct rendering pcs_rgb = [rgb.view(B, 3, -1).permute(0, 2, 1).contiguous() for rgb in pcs_rgb] rasterized_and_blended_pcs = [] for i in range(n_views): if pointcloud_...
magicoder
python
You are tasked with implementing a chatbot system that processes user input and responds accordingly. The chatbot has a method `addChat` to add messages to the chat interface. It also has a method `processInput` that takes user input and processes it. If the input matches a recognized command, the chatbot should perfor...
```java public boolean processInput(String input) { if (recognizedCommands.contains(input)) { // Perform action corresponding to recognized command performAction(input); return true; } else { chatBox.addChat("Unrecognized command: " + input, errorColor); return false; ...
magicoder
java
You are tasked with implementing a function that processes mentions in a given text. A mention is a reference to a user or entity, typically denoted by a username preceded by the "@" symbol. The function should handle the removal of mentions based on certain conditions. You are given a Swift code snippet that demonstr...
```swift func processMentions(in text: String, removeEntireMention: Bool) -> String { var processedText = text let mentionRegex = try! NSRegularExpression(pattern: "@\\w+", options: []) let matches = mentionRegex.matches(in: text, options: [], range: NSRange(location: 0, length: text.utf16.count)) for ...
magicoder
swift
You are tasked with implementing a Python decorator that disables tracking for specific views in a web application. The decorator should be able to wrap any view function and prevent it from being tracked for analytics or other monitoring purposes. You need to create a decorator function `do_not_track` that takes a si...
```python import typing def do_not_track(view: typing.Callable) -> typing.Callable: """View decorator to disable tracking""" def wrapper(*args, **kwargs): # Disable tracking logic goes here return view(*args, **kwargs) return wrapper ``` The `do_not_track` decorator function takes a view f...
magicoder
python
You are given a list of integers representing the parameters `n`, `h`, `a`, `b`, and `k`, followed by `k` lines of input. Each line contains four integers: `ta`, `fa`, `tb`, and `fb`. The function `f(l)` is defined to calculate the minimum time required to move from point `ta` to `tb` while picking up a package at poin...
def f(l): dist = lambda a, b: a - b if a > b else b - a global a, b ta, fa, tb, fb = l ht = dist(ta, tb) if (fa >= a and fa <= b) or (fb >= a and fb <= b) or ht == 0: return ht + dist(fa, fb) return ht + min(dist(fa, a) + dist(fb, a), dist(fa, b) + dist(fb, b) n, h, a, b, k = list(map(i...
magicoder
python
You are tasked with implementing a priority queue system for a messaging application. The application has a `Task` class that represents a task to be processed, and it has a `queue` property that returns the priority queue for processing tasks. The priority queue is managed by a bot and is represented by the `coda` att...
```python class Task: def __init__(self, *args, **kwargs): # Initialize the task with arbitrary arguments and keyword arguments super(Task, self).__init__(*args, **kwargs) @property def queue(self): # Return the priority queue for processing tasks return self.event.client.bo...
magicoder
python
You are tasked with implementing a matrix class in C++ to perform various operations. The matrix class should support addition, subtraction, and multiplication of matrices. Additionally, the class should provide a method to transpose the matrix. You are given a code snippet that initializes an instance of the matrix cl...
```cpp #include <iostream> #include <vector> class Matrix { private: std::vector<std::vector<int>> data; public: Matrix(const std::vector<std::vector<int>>& input) : data(input) {} Matrix operator+(const Matrix& other) const { std::vector<std::vector<int>> result; for (size_t i = 0; i < d...
magicoder
cpp
You are tasked with creating a script to monitor the CPU usage of a Linux system and store the information in a file. The script should check if the system is running on a Linux platform and then run the `top` command with the `-H` option to display individual threads. The output should be redirected to a file named "t...
```bash #!/bin/bash outputdir="/path/to/output/directory" echo "Running top with threads (Linux only)" if [ "$(uname)" == "Darwin" ]; then echo "This is a Mac. Not running top -H." elif [ "$(expr substr $(uname -s) 1 5)" == "Linux" ]; then top -b -n1 -H >> $outputdir/top_threads.txt fi ``` The provided Bash ...
magicoder
shell
You are tasked with implementing a function to determine the result transition for a given event and operation in a boolean operation system. The result transition can be one of the following: `In`, `Out`, or `None`. Additionally, you need to handle the debugging feature by printing the result transition if the `debug-...
```rust // Define the ResultTransition enum enum ResultTransition { In, Out, None, } // Define the Event and Operation structs struct Event { // Define the fields of the Event struct } struct Operation { // Define the fields of the Operation struct } impl Event { // Define the set_result_tran...
magicoder
rust
You are tasked with implementing a simple radio station management system in Python. The system should allow users to start and stop the radio station, as well as display the station name and its corresponding URL. You are provided with a partial code snippet that demonstrates the usage of the radio station management ...
```python class RadioStation: def __init__(self, station_name, url): self.station_name = station_name self.url = url self.is_running = False def start(self): self.is_running = True def stop(self): self.is_running = False class View: def show_station(self, stati...
magicoder
python
You are tasked with creating a Python program that simulates a simple counting mechanism using the ROS (Robot Operating System) framework. The provided code snippet initializes a ROS node named 'count' and publishes a sequence of incremented numbers to a topic named 'count_up' at a rate of 20 Hz. Your task is to comple...
```python import rospy from std_msgs.msg import Int32 def callback(data): rospy.loginfo("Received: %d", data.data) def listener(): rospy.init_node('listener', anonymous=True) rospy.Subscriber('count_up', Int32, callback) rospy.spin() if __name__ == '__main__': listener() ``` In the solution, a RO...
magicoder
python
You are tasked with creating a custom data collection system for a company's network infrastructure. The system should be able to collect various metrics from different network devices and store them for analysis. To achieve this, you need to implement a Python module that utilizes the `diamond.collector` library to co...
```python import diamond.collector class NetworkMetricsCollector(diamond.collector.Collector): def collect(self): # Connect to network devices to collect CPU and memory usage metrics devices = self.get_network_devices() for device in devices: cpu_usage = self.get_cpu_usage(devi...
magicoder
python
You are tasked with implementing a dependency injection container for a DNS management system. The container is configured using the following code snippet: ```csharp .AddTransient<IDnsNameServerProvider, LinuxDnsNameServerProvider>() .AddTransient(CreateDnsResolverWrapper) .AddTransient<IEnvironmentVariables, Environ...
```csharp using System; using System.Collections.Generic; public interface IDependencyResolver { T Resolve<T>(); object Resolve(Type type); } public class DependencyContainer : IDependencyResolver { private readonly Dictionary<Type, Func<object>> _transientRegistrations = new Dictionary<Type, Func<object>...
magicoder
csharp
You are tasked with implementing a custom output stream class that computes an Adler32 CRC checksum for the data being written to it and passes the data along to an underlying output stream. The Adler-32 is a checksum algorithm which was invented by Mark Adler in 1995, and is a modification of the Fletcher checksum. It...
```cpp #include <iostream> #include <vector> class crc32_ostream : public llvm::raw_ostream { private: llvm::raw_ostream &underlying_stream; std::vector<uint8_t> data_buffer; const uint32_t MOD_ADLER = 65521; public: crc32_ostream(llvm::raw_ostream &underlying) : underlying_stream(underlying) {} ...
magicoder
cpp
You are tasked with implementing a role-based access control system for a Kubernetes cluster. The system should support self-subject rules review and subject access review, which are essential for determining the permissions a user has within the cluster. You are provided with the following code snippet, which outline...
```java public Response createAuthorizationV1beta1SelfSubjectRulesReview(IoK8sApiAuthorizationV1beta1SelfSubjectRulesReview body, String dryRun, String fieldManager, String pretty) { // Implement logic to validate self-subject rules review body and determine user permissions // Example logic: if (userHasPer...
magicoder
java
You are given a code snippet that uses a functional programming approach. The code snippet is written in a hypothetical language that supports functional programming constructs. The snippet uses a `from` function to create a sequence from a given array `{ 1, 2, 1, 1 }`, then applies a `drop_while` operation to remove e...
```python def dropWhile(sequence, predicate): result = [] drop = True for item in sequence: if drop and predicate(item): continue else: drop = False result.append(item) return result # Test the dropWhile function input_sequence = [1, 2, 1, 1] predicat...
magicoder
python