query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with implementing a simple color conversion library in Rust. The library should provide a public interface for color operations and expose functionality for working with different color spaces. The code snippet provided indicates that the library should re-export all items from the modules `color` and `c...
```rust // Define the color module mod color { // Define the Color trait for color operations pub trait Color { // Define color-related functions here } // Implement the Color trait for specific color types pub struct RgbColor { // Implement RgbColor } pub struct HslColor {...
magicoder
rust
You are tasked with creating a Python program that reads an RSS feed from a given URL, decodes the content using base64, and then saves the decoded content to a file. Your program should handle any errors that may occur during the process and provide appropriate error messages. Your program should perform the followin...
```python import base64 import feedparser import os def main(): url = input("Enter the URL of the RSS feed: ") try: feed = feedparser.parse(url) if 'content' in feed.entries[0]: encoded_content = feed.entries[0].content[0].value decoded_content = base64.b64decode(encoded...
magicoder
python
You are tasked with creating a program that analyzes a given text file to count the occurrences of each unique word. Your program should ignore punctuation and consider words regardless of their case (i.e., "Hello" and "hello" should be considered the same word). Additionally, the program should output the top N most f...
```python from typing import List, Tuple import re from collections import Counter def top_n_words(file_path: str, n: int) -> List[Tuple[str, int]]: with open(file_path, 'r') as file: text = file.read().lower() words = re.findall(r'\b\w+\b', text) word_counts = Counter(words) top_n ...
magicoder
python
You are tasked with implementing a command-line argument parser for a Python server application. The application is designed to accept various command-line arguments to configure its behavior. Your task is to create a Python function that parses the command-line arguments and sets the corresponding configuration option...
```python import argparse from tornado.ioloop import IOLoop def parse_command_line_arguments(): parser = argparse.ArgumentParser() parser.add_argument('--debug', action='store_true', help='Run in debug mode') parser.add_argument('--port', type=int, default=8080, help='Server port') parser.add_argument(...
magicoder
python
You are tasked with implementing a function that finds the maximum value among two given integers. However, there's a catch - you are not allowed to use any comparison operators (e.g., >, <, ==) or ternary operators (e.g., a ? b : c) in your solution. Your task is to devise an algorithm that can determine the maximum v...
```python def findMax(a, b): diff = a - b sign = (diff >> 31) & 0x1 # Extracting the sign bit (0 for positive, 1 for negative) return a - diff * sign # If a is greater, sign is 0 and a - 0 * diff = a; if b is greater, sign is 1 and a - 1 * diff = a - diff = b ``` The solution leverages bitwise operations...
magicoder
python
You are tasked with creating a Python program that organizes and manages the import statements for a machine learning library. The library consists of various modules and submodules, and the program needs to ensure that the imports are correctly structured and organized. The program should also define a class called `p...
```python def organize_imports(): imports = [ "import combo.search.score", "from .. import utility", "from ... import blm", "from ... import gp", "from ... import predictor", "from ...blm import predictor as blm_predictor", "from ...gp import predictor as gp_p...
magicoder
python
You are tasked with creating a Python function that simulates a simplified version of a debugger communication system. The function will take in a list of integers representing debugger pipes and a list of strings representing debugger arguments. The function should execute the debugger command using the provided pipes...
```python import os import sys from typing import List def simulate_debugger(hippy_pipes: List[int], hippy_args: List[str]) -> None: read_fd1, write_fd1 = os.pipe() read_fd2, write_fd2 = os.pipe() pid = os.fork() if pid == 0: # Child process os.close(read_fd1) os.close(write_fd2) ...
magicoder
python
You are tasked with implementing a simplified version of a memory management system. The system should support allocating and freeing memory blocks, and it should also be able to defragment the memory to ensure efficient memory usage. You are given a class `MemoryManager` with the following methods: - `allocate(size)`...
```cpp #include <iostream> #include <vector> #include <algorithm> class MemoryManager { private: std::vector<char> memory; std::vector<std::pair<size_t, size_t>> allocatedBlocks; public: MemoryManager(size_t size) : memory(size, 0) {} char* allocate(size_t size) { for (size_t i = 0; i < memor...
magicoder
cpp
You are tasked with implementing a class that manages file snapshots and provides methods for manipulating and retrieving snapshot information. The class should support adding, removing, and retrieving file snapshots, as well as calculating the hash of a list of file snapshots. You are given a partial implementation o...
```python class SnapshotManager: def __init__(self, src): self.src = src self.relative_path_to_snapshotfile = {} self.hexdigest_to_snapshotfiles = {} def _remove_snapshotfile(self, snapshotfile: SnapshotFile): assert self.relative_path_to_snapshotfile[snapshotfile.relative_path]...
magicoder
python
You are given a code snippet from a file named `keywords.gperf` which appears to be a part of a lexical analyzer or parser generator. The snippet contains a list of keywords along with their associated tokens and syntax properties. Each keyword is followed by its associated token and syntax properties, separated by com...
```python import re def parseKeywords(code_snippet): keyword_pattern = r'{"(.*?)",\s+(T_\w+),\s+(SYNTAX_\w+(\s*\|\s*SYNTAX_\w+)*)}' matches = re.findall(keyword_pattern, code_snippet) keywords_map = {} for match in matches: keyword = match[0] token = match[1] syntax_properties ...
magicoder
python
You are tasked with implementing a custom error handling mechanism for a Python bot application. The bot has a function that takes in arguments with annotations, and it needs to raise a specific error if any argument is not annotated. Your task is to create a function that checks if the function arguments have annotati...
```python class ArgError(Exception): def __init__(self, message, details): super().__init__(message) self.details = details def check_annotations(func) -> None: import inspect import signature as sig # Assuming the signature module is imported func_signature = inspect.signature(func) ...
magicoder
python
You are tasked with implementing a program that processes a given license agreement text and extracts the permissions granted within it. The license agreement text is a string containing a series of permissions separated by commas. Each permission is a combination of verbs and nouns, representing actions and objects, r...
To solve this problem, we can use a simple parsing algorithm to extract the verbs and nouns from the license agreement text. We can split the text by commas to obtain individual permissions and then further split each permission by spaces to separate the verbs and nouns. Here's a Python solution to extract the verbs a...
magicoder
python
You are tasked with creating a custom loss function for a neural network model using TensorFlow and Keras. The loss function should be a modified version of the mean squared error (MSE) loss, incorporating an additional parameter to adjust the loss calculation. Your task is to implement the custom loss function and tes...
```python import tensorflow as tf import numpy as np def custom_loss(scale_factor): def loss_function(y_true, y_pred): mse = tf.keras.losses.mean_squared_error(y_true, y_pred) scaled_loss = scale_factor * mse return scaled_loss return loss_function class CustomModel: def create_mod...
magicoder
python
You are tasked with creating a Python program that utilizes sockets to implement a simple network time protocol (NTP) client. The NTP client will connect to a specified NTP server and retrieve the current time from the server. The program should then calculate and display the round-trip time (RTT) for the NTP request a...
```python import socket import struct import time NTP_SERVER = "pool.ntp.org" NTP_PORT = 123 NTP_PACKET_FORMAT = "!12I" NTP_DELTA = 2208988800 # 70 years in seconds def ntp_client(ntp_server): client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) client.settimeout(5.0) # Set socket timeout to 5 seconds ...
magicoder
python
You are working on a project that involves integrating a third-party SMS service into a Python application. The third-party service provider offers an SDK called `ronglian_sms_sdk` for sending SMS messages. Additionally, the project uses Celery for asynchronous task processing, and the main Celery app is defined in `ce...
```python from ronglian_sms_sdk import SmsSDK from celery_tasks.main import app # Define the Celery task for sending SMS @app.task def send_sms_task(recipient_number, message_content): # Initialize the SMS SDK with your account credentials sdk = SmsSDK('your_account_id', 'your_account_token', 'your_app_id') ...
magicoder
python
You are working for a financial institution that deals with a large volume of financial data. Your task is to create a Python function that calculates the Black-Scholes option pricing model for European call and put options. The Black-Scholes model is a mathematical model used for pricing options contracts, and it take...
```python import numpy as np def black_scholes_option_price(S, K, r, T, sigma, option_type): d1 = (np.log(S / K) + (r + 0.5 * sigma**2) * T) / (sigma * np.sqrt(T)) d2 = d1 - sigma * np.sqrt(T) if option_type == 'call': option_price = S * np.exp(-0.5 * d1**2) / np.sqrt(2 * np.pi) - K * np.exp(-r * ...
magicoder
python
You are tasked with implementing a function to generate unique sample IDs for a research project. The sample IDs follow a specific format: "YYYY-GCRSR-XXXX", where "YYYY" is the year, "GCRSR" is a project code, and "XXXX" is a unique 4-digit identifier. The function should generate a specified number of unique sample I...
```python import random def generate_sample_ids(year, project_code, num_samples): id_list = list(range(1, num_samples + 1)) random.shuffle(id_list) sample_ids = ['{}-{}-{:04d}'.format(year, project_code, id_num) for id_num in id_list] return sample_ids ``` The `generate_sample_ids` function ...
magicoder
python
You are tasked with implementing a TCP gender changer tool in Rust. The tool should be able to connect to a local server and a Listen/Listen server, and it should have the ability to automatically reconnect to the local server. The tool should also support debug logging. Your task is to implement the main functionalit...
```rust use std::net::TcpStream; use std::time::Duration; use clap::{App, Arg, SubCommand}; fn main() { let matches = App::new("TCP Gender Changer, rust version") .subcommand(SubCommand::with_name("-C") .arg(Arg::with_name("local-server").short("s").help("the host and port of the local server")...
magicoder
rust
You are tasked with implementing a simplified version of a symbol table for a programming language compiler. The symbol table is used to store information about variables and their corresponding values within a specific scope. Your task is to create a data structure and methods to manage this symbol table. You are giv...
```rust use std::collections::HashMap; struct Var { // Define the structure of Var as per the requirements // For example: // value: i32, // type: String, } impl Frame { pub fn new(fun: llvm::Value) -> Self { Frame { env: HashMap::new(), fun, } } pu...
magicoder
rust
You are tasked with implementing a Python class for configuring email settings. Your task is to complete the `MailConfig` class by adding the necessary methods and attributes to handle email configuration. The `MailConfig` class should have the following attributes and methods: - Attributes: - `_mfrom`: A string rep...
```python class MailConfig: def __init__(self, mfrom, sendconfig, subject="[buildbot] {severity}: {project} -- {target}"): self._mfrom = mfrom self.sendconfig = sendconfig self.subject = subject def set_sendconfig(self, config): ...
magicoder
python
You are tasked with implementing a custom navigation system for a mobile application. The system should handle the preparation before navigating from one view controller to another. Specifically, you need to implement the `prepare(for segue: UIStoryboardSegue, sender: Any?)` method in a Swift view controller. The `pre...
```swift func prepare(for segue: UIStoryboardSegue, sender: Any?, destinationVC: UIViewController) { guard let segueIdentifier = segue.identifier else { return } switch segueIdentifier { case "FirstSegueIdentifier": if let firstDestinationVC = destinationVC as? FirstViewController {...
magicoder
swift
You are tasked with creating a script to automate the setup of a Kubernetes cluster and the installation of Helm on a Linux system. The script should perform the following tasks: 1. Copy the Kubernetes admin configuration file from `/etc/kubernetes/admin.conf` to the user's home directory at `$HOME/.kube/config`. 2. A...
```bash #!/bin/bash # Copy Kubernetes admin configuration cp -i /etc/kubernetes/admin.conf $HOME/.kube/config if [ $? -ne 0 ]; then echo "Error: Failed to copy Kubernetes admin configuration" exit 1 fi # Apply Flannel networking plugin kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/2140ac876ef1...
magicoder
shell
You are tasked with implementing a function that processes and submits Iroha Special Instructions to Iroha peers. The function should handle the submission of multiple instructions and allow the specification of metadata for the transaction. Your task is to design and implement the function according to the given requi...
```rust use iroha::prelude::*; // Import necessary Iroha library modules fn submit_all_with_metadata(instructions: Vec<Instruction>, metadata: Metadata) -> Result<String, String> { // Create a new transaction builder let mut transaction = Transaction::new_with_signature( metadata.clone(), // Clone the ...
magicoder
rust
You are tasked with implementing a function that identifies independent types within a given array of types. Independent types are those that do not depend on any other type within the array. In this context, a type is considered to be dependent on another type if it directly references it in some way. You are provide...
```php protected function getIndependentTypes(array $types): array { $dependencies = []; $independentTypes = []; // Create a map of dependencies for each type foreach ($types as $type) { $dependencies[$type] = []; } // Identify dependencies for each type foreach ($types as $type) {...
magicoder
php
You are tasked with creating a utility function to merge and export all the functions and variables from multiple modules in a specific directory. The function should take the directory path as input and export all the contents of the modules within that directory. Write a function `mergeAndExportModules` that takes a...
```javascript // mergeAndExportModules.js const fs = require('fs'); const path = require('path'); function mergeAndExportModules(directoryPath) { const moduleFiles = fs.readdirSync(directoryPath).filter(file => file.endsWith('.js')); let exportStatements = ''; moduleFiles.forEach(file => { const moduleNam...
magicoder
javascript
You are tasked with creating a Python script that automates the process of downloading and installing Android Studio and the Android SDK. Your script should be able to handle the entire process, including downloading the necessary files, installing the software, and setting up the environment variables. Your script sh...
```python import os import platform import subprocess import requests import zipfile import shutil def is_android_studio_installed(): if platform.system() == "Windows": return os.path.exists("C:\\Program Files\\Android\\Android Studio") elif platform.system() == "Darwin": return os.path.exists(...
magicoder
python
You are tasked with creating a custom React hook that fetches BOS (Balance of Satoshis) score history for a given node. The BOS score is a metric used to evaluate the economic health of a Lightning Network node. The provided code snippet is a part of this custom hook and uses Apollo Client for GraphQL queries. The `us...
```javascript import { useQuery } from '@apollo/client'; import { GET_NODE_BOS_HISTORY } from './graphql'; // Assuming the GraphQL query is defined in a separate file const useGetNodeBosHistoryQuery = ({ skip, variables, onError }) => { const { pubkey } = variables; const { data, loading, error } = useQuery(GET_N...
magicoder
javascript
You are tasked with creating a Python program to draw a colorful geometric pattern using the turtle graphics library. The program should utilize the provided code snippet as a starting point and extend it to produce the desired pattern. Your program should draw a series of nested polygons, each with a different color ...
```python from turtle import TurtleScreen, RawTurtle, Canvas # Create a canvas and a turtle screen canvas = Canvas() screen = TurtleScreen(canvas) # Initialize a turtle object trtl = RawTurtle(screen) # Hide turtle animation for faster drawing screen.tracer(False) # Set the background color to white screen.bgcolor(...
magicoder
python
You are working on a speech recognition project and need to fine-tune a pre-trained model for your specific use case. You have come across the `wav2vec2_hug_base_960` function, which is used to load a pre-trained model for fine-tuning. The function takes variable positional and keyword arguments and sets the `ckpt` key...
```python import torch from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor class Wav2Vec2FineTuner: def __init__(self, pre_trained_checkpoint): self.pre_trained_checkpoint = pre_trained_checkpoint self.model = None self.processor = None def load_model(self): self.process...
magicoder
python
You are tasked with creating a Python program that interacts with the Wikipedia API to retrieve and display random articles. Your program should prompt the user for input to determine whether they want to open the random article in a web browser. If the user chooses to do so, the program should use the `webbrowser` mod...
```python import wikipedia import webbrowser def getPage(): try: random_article = wikipedia.random() print("Random Article Title:", random_article) web_browser = input("Do you want to open this in your web browser? (y/n) ") if web_browser.lower() == 'y': wiki_load = wik...
magicoder
python
You are tasked with creating a program that processes and validates XML annotations in a given PHP class. The program should be able to identify and extract specific information from the annotations, and then perform validation checks based on the extracted data. You are given a PHP class with XML annotations, as show...
To solve this problem, you can use PHP's reflection capabilities to extract and process the annotations from the given PHP class. Here's a sample solution to achieve this: ```php class AnnotationProcessor { public function processAnnotations($className) { $reflectionClass = new ReflectionClass($classNa...
magicoder
php
You are given an array of integers of length N, where the elements are in the range from 1 to N. There are exactly two elements that appear once and all the other elements appear exactly twice. You need to find the two elements that appear only once. Write a function `findMissingAndRepeating` that takes in an array of...
```java class Solution { public int[] findMissingAndRepeating(int[] nums) { int n = nums.length; int xor = 0; for (int num : nums) { xor ^= num; } int rightmostSetBit = xor & -xor; int x = 0, y = 0; for (int num : nums) { ...
magicoder
java
You are tasked with implementing a unit testing framework for a lease management system. The system includes different concrete lease managers, such as `MySqlLeaseMgr`. However, there are currently no unit tests for these lease managers because the only testable method, `parse`, has been moved to its own class called `...
```java import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; public class LeaseManagerTest { @Test public void testMySqlLeaseMgr() { // Create test data and initialize MySqlLeaseMgr MySqlLeaseMgr leaseMgr = new MySqlLeaseMgr(/* pass necessary parameters */); ...
magicoder
java
You are tasked with implementing a routing system for a web application that allows users to interact with Hitori puzzle boards. Hitori is a logic puzzle that involves shading cells in a grid such that no number appears more than once in any row or column, and no shaded cells are adjacent to each other, even diagonally...
```python # Define the routes for managing Hitori puzzle boards and solutions config.add_route('hitori_boards_list', '/hitori_boards', request_method='GET') config.add_route('hitori_board_details', '/hitori_boards/{board_id:\d+}', request_method='GET') config.add_route('hitori_board_solve', '/hitori_boards/{board_id:\d...
magicoder
python
You are given a code snippet that appears to be a part of a programming language interpreter or compiler. Your task is to analyze the given code and identify the specific programming language constructs and operations being performed. Based on this analysis, you need to determine the purpose and functionality of the co...
The given code snippet appears to be a part of a stack-based programming language interpreter or compiler. The code snippet contains a series of nested arrays and a block of operations that manipulate the stack and perform comparisons and string manipulations. The code snippet seems to be performing operations on a st...
magicoder
python
You are tasked with implementing a simplified file management system in Python. Your goal is to create a class that manages a collection of files, allowing for the creation, retrieval, and deletion of files. The class should also keep track of the number of files and the keys associated with each file. Your task is to...
```python class FileManager: def __init__(self, base_path: str): self.base_path = base_path self.files = {} self.count = 0 self.keys = [] def create_file(self, key: str): path = f"{self.base_path}/{key}.txt" self.files[key] = open(path, 'w', encoding='utf8') ...
magicoder
python
You are tasked with creating a program that simulates a simple game of dice. The game involves rolling two dice and summing the values. The program should allow the user to input the number of times they want to roll the dice and then simulate the rolls accordingly. After simulating the rolls, the program should displa...
```python import random def roll_dice(): return random.randint(1, 6) def simulate_dice_rolls(num_rolls): results = {} for _ in range(num_rolls): roll1 = roll_dice() roll2 = roll_dice() total = roll1 + roll2 if total in results: results[total] += 1 else: ...
magicoder
python
You are tasked with implementing a function to efficiently copy a portion of an image from a source buffer to a destination buffer. The source image is represented by the `src` object, which contains configuration information such as horizontal and vertical resolutions. The destination buffer is represented by the `dst...
```cpp void CopyImage(const Image& src, const Image& dst, const Position& pos) { const auto src_width = src.config_.horizontal_resolution; const auto src_height = src.config_.vertical_resolution; const int copy_start_dst_x = std::max(pos.x, 0); const int copy_start_dst_y = std::max(pos.y, 0); const int copy_...
magicoder
cpp
You are given a snippet of code that appears to be incomplete. Your task is to complete the code by implementing a function that calculates the sum of all even numbers in a given array. The incomplete code snippet is as follows: ```java public class ArraySum { public static void main(String[] args) { int[]...
```java public class ArraySum { public static void main(String[] args) { int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int result = sumOfEvenNumbers(numbers); System.out.println("Sum of even numbers: " + result); } // Completed function static int sumOfEvenNumbers(int[] arr) ...
magicoder
java
You are tasked with implementing a logging utility for a software build system. The provided code snippet is a part of a test suite for this logging utility. The utility is expected to log messages and handle debug mode, where debug messages are only printed when debug mode is enabled. Your task is to write a function...
```python class Logger: def __init__(self, log_file): self.log_file = log_file self.debug_mode = False def log(self, message, log_level='info'): with open(self.log_file, 'a') as file: file.write(f"[{log_level.upper()}] {message}\n") def enable_debug_mode(self): ...
magicoder
python
You are tasked with implementing a custom reporter for a diagnostic runner in PHP. The diagnostic runner is responsible for running a series of checks to ensure the health and functionality of a system. Your custom reporter will be responsible for reporting the results of these checks. Your custom reporter should exte...
```php use ZendDiagnostics\Check\CheckInterface; use ZendDiagnostics\Result\ResultInterface; class CustomReporter extends AbstractReporter { public function onStart(ArrayObject $checks, $runnerConfig) { // Implement logic to handle the start of the diagnostic checks echo "Diagnostic checks star...
magicoder
php
You are tasked with implementing a command pattern for a mock boat racing simulation. The provided code snippet is the beginning of a command factory package for creating commands to control mock boats in a mock race. The `MockBoat` class represents a boat participating in the race, and the `MockRace` class represents...
```java // Define the Command interface public interface Command { void execute(); } // Create concrete command classes public class AccelerateCommand implements Command { private MockBoat boat; public AccelerateCommand(MockBoat boat) { this.boat = boat; } @Override public void execut...
magicoder
java
You are tasked with implementing a class hierarchy for representing Swagger schema components in a PHP application. The provided code snippet is a partial implementation of a class representing a path parameter in the Swagger schema. Your task is to complete the implementation of the `PathParameter` class and its relat...
```php namespace Draw\Swagger\Schema; use JMS\Serializer\Annotation as JMS; /** * Represents a path parameter in the Swagger schema. * * @JMS\ExclusionPolicy("all") */ class PathParameter extends BaseParameter { /** * The name of the parameter. * * @var string * @JMS\Type("string") */...
magicoder
php
You are given a class with two properties: `Int` and `String`. The `Int` property is an array of integers, and the `String` property is an array of strings. The class also contains a method that populates the `String` array based on the values in the `Int` array. The method iterates through the `Int` array and construc...
```csharp public static int CalculateStringLengthSum(StringArrayBuilder builder) { int sum = 0; foreach (string str in builder.String) { sum += str.Length; } return sum; } ```
magicoder
csharp
You are working on a continuous integration (CI) pipeline for a web application hosted on Vercel. The CI pipeline is triggered whenever a new commit is made to the repository. You need to ensure that the pipeline only runs when the commit is made to a specific branch called "stream-data". To achieve this, you decide to...
```bash #!/bin/bash if [[ $VERCEL_GIT_COMMIT_REF != "stream-data" ]]; then echo "Error: CI pipeline can only run for commits to the 'stream-data' branch." exit 1 fi ``` In the solution, the bash script checks the value of the `VERCEL_GIT_COMMIT_REF` environment variable using the conditional statement `if [[ $VER...
magicoder
shell
You are tasked with implementing a program to parse and analyze a series of nested status messages. Each status message is represented by the keywords "The status should be" followed by a status value, and ends with the keyword "End". The status value can be one of the following: "success" or "failure". The program sho...
```python def analyzeStatus(status: str) -> str: stack = [] for line in status.split('\n'): if line.startswith("The status should be"): stack.append(line.split()[-1]) elif line == "End": if "failure" in stack: return "failure" stack.pop() r...
magicoder
python
You are tasked with creating a simple user authentication system using PHP. Your goal is to implement a User class that extends the Authenticatable class and utilizes the Notifiable trait for notifications. Additionally, you need to incorporate the Auth facade for user authentication. Your task is to complete the User...
```php use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Support\Facades\Auth; class User extends Authenticatable { use Notifiable; protected $fillable = ['name', 'email', 'password']; public function notify($instance) { $this->not...
magicoder
php
You are tasked with creating a function to calculate the percentage change between two sets of benchmark results. Each benchmark result consists of a benchmark name and a numeric value. The function should take in two arrays of benchmark results, where each result is represented as an object with properties `benchmarkN...
```javascript function calculatePercentageChange(oldResults, newResults) { const result = []; oldResults.forEach(oldResult => { const newResult = newResults.find(r => r.benchmarkName === oldResult.benchmarkName); if (newResult) { const percentageChange = ((newResult.value - oldResult.value) / oldResu...
magicoder
javascript
You are tasked with implementing a simple game using C++. The game involves a player navigating through a maze to reach the end point. The maze is represented as a 2D grid, where the player starts at a designated starting point and must navigate through the maze to reach the end point. The player can move in four direc...
```cpp #include <iostream> #include <vector> #include <queue> void run_game() { int N, M; std::cin >> N >> M; // Input dimensions of the maze std::vector<std::vector<char>> maze(N, std::vector<char>(M)); int start_x, start_y, end_x, end_y; // Input the maze grid for (int i = 0; i < N; i++) { ...
magicoder
cpp
You are working on a seismic data processing application and need to implement a function to process seismic observations. The function receives a list of seismic observations `st_obs`, an event `event`, and a boolean `noise` indicating whether to process noise data. The seismic observations are represented as a list o...
```python def process_seismic_observations(st_obs, event, noise): # Replace the channel name of the third seismic observation st_obs[2].stats.channel = st_obs[2].stats.channel.replace("X", "H") # Trim the start and end times of the third seismic observation st_obs[2].trim(starttime=event.origin_time, e...
magicoder
python
You are tasked with implementing a resource management system for file operations in C++. The system should handle file creation, writing, and automatic cleanup upon exiting the scope. Your task is to create a class that manages file resources and provides a mechanism for writing to these files. You are provided with ...
```cpp #include <iostream> #include <fstream> #include <memory> #include <string> #include <codecvt> #include <locale> class File { private: std::string filePath; public: File(const std::string& path) : filePath(path) {} std::ofstream getWriteStream() { return std::ofstream(filePath); } ...
magicoder
cpp
You are tasked with implementing a file adapter in Rust that can be used in both native and web assembly (WASM) environments. The file adapter should provide a unified interface for reading and writing files, and it should be able to handle the differences in file system access between native and web assembly environme...
```rust use std::io; use std::fs::File; use std::io::prelude::*; #[cfg(target_arch = "wasm32")] use wasm_bindgen::prelude::*; struct FileAdapter { // Add any necessary fields here } impl FileAdapter { fn new() -> Result<Box<Self>, io::Error> { #[cfg(not(target_arch = "wasm32"))] { ...
magicoder
rust
You are given a string containing parentheses and other characters. Your task is to write a function that determines whether the parentheses in the string are balanced. A string is considered balanced if it consists of pairs of opening and closing parentheses, with each opening parenthesis having a corresponding closin...
```python def is_balanced_parentheses(s: str) -> bool: stack = [] opening_brackets = {'(', '[', '{'} closing_brackets = {')', ']', '}'} bracket_pairs = {'(': ')', '[': ']', '{': '}'} for char in s: if char in opening_brackets: stack.append(char) elif char in closing_brac...
magicoder
python
You are tasked with creating a custom validation rule for Laravel's Eloquent models. The rule should ensure that a given attribute's value is unique among rows where a specific column has a certain value. For example, you may want to ensure that a user's email is unique among all users with a specific role. Your task ...
To implement the `unique_for_column_value` custom validation rule in Laravel, you can follow these steps: 1. Create a new custom validation rule using the `make` method of the `Validator` facade. This rule should accept the required parameters and perform the necessary database query to check for uniqueness. 2. Defin...
magicoder
php
You are working on a project that involves optimizing the performance of a computational task. The task involves performing a large number of floating-point operations, and you have a constraint on the maximum number of floating-point operations per second (FLOPS) that your system can handle. Additionally, you have a l...
```python from itertools import combinations from typing import List def select_tasks(max_flops, max_epochs, select_num, tasks) -> List[int]: max_flops_subset = 0 selected_tasks = [] for i in range(1, select_num + 1): for subset in combinations(range(len(tasks)), i): total_flops = sum(...
magicoder
python
You are tasked with creating a Python program that simulates a simple text-based game. The game involves a player navigating through a series of rooms, each with its own description and potential actions. The player can move between rooms, interact with objects, and make decisions that affect the outcome of the game. ...
```python # Define color codes for text formatting cores = {'azul': '\033[1;34m', 'limpa': '\033[m', 'pretoebranco': '\033[7;30m'} # Define the rooms and their descriptions rooms = { 'hallway': { 'description': f"{cores['azul']}You are standing in a dimly lit hallway. To the north, a door leads to the cour...
magicoder
python
You are tasked with implementing a class method for handling message deletion in a Discord bot. The method should take in several parameters and perform the necessary actions to delete a message. Below is the code snippet for the method signature: ```python MESSAGE_DELETE = 72 def __init__(self, client_bind: DiscordC...
```python MESSAGE_DELETE = 72 def __init__(self, client_bind: DiscordClientAsync, id: str, user_id: str, target_id: str, action_type: int, reason: str = None): super().__init__(client_bind, id) if action_type == MESSAGE_DELETE: # Perform message deletion logic here if user_id == target_id: ...
magicoder
python
You are tasked with creating an AI agent to navigate a simulated environment using reinforcement learning. The environment is represented by a grid, and the agent can move in four directions: up, down, left, and right. The agent receives a reward for reaching a goal state and incurs a penalty for hitting obstacles. The...
```python import swarm_env import numpy as np # Initialize the environment env = swarm_env.Environment() # Initialize Q-table with zeros num_states = env.observation_space.n num_actions = env.action_space.n Q = np.zeros((num_states, num_actions)) # Set hyperparameters alpha = 0.1 # Learning rate gamma = 0.9 # Disc...
magicoder
python
You are tasked with implementing a generic function in Swift that calculates the product of two numbers using a custom multiplication operation. The custom multiplication operation is defined as follows: ```swift func customMultiply<T>(_ a: T, _ b: T) -> T { // Your implementation of custom multiplication goes her...
```swift // Problem Description: Implementing a generic function for custom multiplication // Solution: // Define a custom protocol for types that support custom multiplication protocol CustomMultiplicable { static func *(lhs: Self, rhs: Self) -> Self } // Implement custom multiplication for integers extension I...
magicoder
swift
You are tasked with implementing a function to reverse the order of directories found in a given list and then delete the directories in the reversed order. The function should take a list of directories as input and return the list of directories in reverse order. Additionally, it should print each directory in the re...
```python def reverse_and_delete_dirs(dirsFound): print("ordering dirs...") dirsToDelete = [] # Reverse the order of directories reversedDirs = dirsFound[::-1] # Print and append directories to dirsToDelete for directory in reversedDirs: print(directory) dirsToDelete.append(di...
magicoder
python
You are tasked with creating a script to automate the setup process for a data science environment using Anaconda and Python. Your script should activate a specific conda environment and then install the required Python packages from a given requirements file. Write a Python script that takes two command-line argument...
```python import subprocess import sys import os def activate_conda_environment(env_name): try: subprocess.run(['conda', 'activate', env_name], check=True, shell=True) except subprocess.CalledProcessError: print(f"Error: Conda environment '{env_name}' does not exist.") sys.exit(1) def ...
magicoder
python
You are tasked with creating a program that simulates a simple text-based game. The game involves a player navigating through a grid-based world, collecting items, and avoiding obstacles. The player's goal is to reach the exit point while collecting as many items as possible. The grid-based world is represented by a 2...
```python from typing import List def gameSimulation(grid: List[List[str]]) -> int: rows, cols = len(grid), len(grid[0]) directions = [(0, 1), (0, -1), (1, 0), (-1, 0)] def is_valid_move(x, y): return 0 <= x < rows and 0 <= y < cols and grid[x][y] != '#' def dfs(x, y, items_collected): ...
magicoder
python
You are tasked with implementing a function that calculates the volumes of hexahedral elements in a finite element analysis. The function takes in the coordinates of the element nodes, performs Gaussian quadrature to integrate over the element, and returns the volumes of the hexahedral elements. The code snippet provi...
```python import numpy as np def volumes_H8(ecoords, qpos, qweight): volumes = 0 for i in range(len(qpos)): xi, eta, zeta = qpos[i] weight = qweight[i] dN_dxi = np.array([ [-0.125 * (1 - eta) * (1 - zeta), 0.125 * (1 - eta) * (1 - zeta), 0.125 * (1 + eta) * (1 - zeta), -0.12...
magicoder
python
You are tasked with creating a Python class that simulates a spectral synthesis wrapper for astronomical data analysis. The class should be able to retrieve and process spectral data based on input parameters such as effective temperature (teff), surface gravity (logg), and wavelength range (wstart and wend). Additiona...
```python import wrapper class SynspecWrapper: def __init__(self, teff, logg, wstart, wend): self.teff = teff self.logg = logg self.wstart = wstart self.wend = wend @property def spectrum(self): # Replace this with actual retrieval and processing of spectral data ...
magicoder
python
You are tasked with implementing a function that calculates the sum of all even Fibonacci numbers up to a given limit. The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. For example, the first few numbers in the Fibonacci sequence are ...
```typescript function evenFibonacciSum(limit: number): number { let sum = 0; let prev = 1; let curr = 1; while (curr <= limit) { if (curr % 2 === 0) { sum += curr; } let next = prev + curr; prev = curr; curr = next; } return sum; } ``` The ...
magicoder
typescript
You are tasked with implementing a context manager in Python to manage terminal settings for a command-line interface (CLI) application. The context manager should handle the following operations: 1. Set the terminal to use an alternate screen buffer. 2. If the terminal is not echoing input and the operating system is...
```python import sys import termios import tty import contextlib @contextlib.contextmanager def terminal_settings_manager(): original_settings = termios.tcgetattr(sys.stdin) try: tty.setcbreak(sys.stdin.fileno()) sys.stdout.write("\033[?1049h") # Set the terminal to use an alternate screen buf...
magicoder
python
You are tasked with simulating the configuration of a virtual tunnel endpoint (VTEP) for a software-defined networking (SDN) environment. The VTEP is responsible for managing logical switches, binding virtual machines to these switches, and setting up remote connections for inter-host communication. Your task is to wr...
```python from typing import List, Dict, Any def simulate_vtep_config(commands: List[str]) -> Dict[str, Any]: vtep_state = { "logical_switches": {}, "vm_bindings": {}, "unicast_remotes": {}, "multicast_remotes": {} } for command in commands: tokens = command.split()...
magicoder
python
You are tasked with implementing a custom exception class and using it within a Python program. Your task is to create a class called `MethodNotImplementedException` that inherits from the built-in `Exception` class. This custom exception will be raised when a method is called that has not been implemented in a subclas...
```python class MethodNotImplementedException(Exception): pass from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def calculate_area(self): raise MethodNotImplementedException("calculate_area() method is not implemented") class Circle(Shape): def __init__(self, radius): ...
magicoder
python
You are tasked with implementing a UML (Unified Modeling Language) modeling system that supports various UML elements such as stereotypes, behaviors, data types, associations, interfaces, and deployments. The provided code snippet includes the necessary header files and a namespace declaration for the UML library. You...
```cpp #include <iostream> #include <unordered_map> #include <vector> // Define a unique identifier for UML elements typedef int ElementId; namespace UML { class UMLModelElement { private: ElementId id; std::unordered_map<std::string, std::string> stereotypes; std::vector<std::string> ...
magicoder
cpp
You are tasked with creating a function that retrieves a list of users from a Firebase authentication service and returns a specific subset of user data. The function should handle the asynchronous nature of the data retrieval and ensure that the response is formatted correctly. Write a function `retrieveUsers` that t...
```javascript import admin from 'firebase-admin'; const serviceAccount = require('path/to/serviceAccountKey.json'); admin.initializeApp({ credential: admin.credential.cert(serviceAccount) }); const retrieveUsers = async (limit) => { try { const userRecords = await admin.auth().listUsers(limit); const for...
magicoder
javascript
You are tasked with implementing a function that processes pattern mappings in a Rust program. The function takes in a list of pattern mappings and processes them according to certain rules. Each pattern mapping can be of three types: `Exact`, `SubPattern`, or `Default`. The function should handle these mappings as fol...
```rust fn process_mappings(mappings: &[hir::PatternMapping]) { let mut failed = false; let mut default: Option<&hir::PatternMapping> = None; let cx = Context; for mapping in mappings { match mapping { hir::PatternMapping::Exact { pattern, to } => { if pattern == exp...
magicoder
rust
You are tasked with implementing a generic class that selects the output of a BizTalk transform for unit testing purposes. The class should be able to work with any transform derived from the `TransformBase` class. Your task is to complete the implementation of the `TransformFixtureOutputSelector<TTransform>` class. T...
```csharp using System; using System.IO; using Microsoft.XLANGs.BaseTypes; namespace Be.Stateless.BizTalk.Unit.Transform { internal class TransformFixtureOutputSelector<TTransform> : ITransformFixtureOutputSelector where TTransform : TransformBase, new() { public Stream SelectOutput(Stream inpu...
magicoder
csharp
You are working on a robotics project and need to implement a function to calculate the inverse kinematics for a robotic arm. The function should take in the robot model, data, initial joint configuration `q0`, and a frame identifier `fid`. The code snippet provided is a part of the implementation using the Pinocchio l...
```python import pinocchio import numpy as np def calculate_inverse_kinematics(robot_model, data, q0, fid): # Compute forward kinematics pinocchio.framesForwardKinematics(robot_model, data, q0) # Obtain the Jacobian matrix for the specified frame Ji = pinocchio.getFrameJacobian(robot_model, data, ...
magicoder
python
You are tasked with implementing a parallelized job execution function that takes a list of jobs and their corresponding durations as input and returns a pandas DataFrame or Series containing the job names and their respective completion times. The function should utilize parallel processing to execute the jobs concurr...
```python import pandas as pd from concurrent.futures import ProcessPoolExecutor def execute_job(job): """ Execute a single job and return the job name and completion time """ job_name, duration = job # Simulate job execution by sleeping for the specified duration import time time.sleep(dur...
magicoder
python
You are tasked with implementing a function that generates a set of evenly spaced numbers within a given range, but with a twist. The function should create two sets of numbers, each with a different number of elements, and then combine them into a single array. The first set should contain a specified number of elemen...
```python import numpy as np def generate_combined_array(start, end, num_first, num_second): midpoint = start + (end - start) * (num_first / (num_first + num_second)) first_set = np.linspace(start, midpoint, num_first, endpoint=False) second_set = np.linspace(midpoint, end, num_second, endpoint=True) c...
magicoder
python
You are tasked with implementing a program to manage a collection of geometric shapes using object-oriented programming in C++. The program should support the creation and manipulation of various geometric shapes, including circles, rectangles, and triangles. Each shape should have methods to calculate its area and per...
```cpp #include <iostream> #include <cmath> class Shape { public: virtual double area() = 0; virtual double perimeter() = 0; virtual void displayDetails() = 0; }; class Circle : public Shape { private: double radius; public: Circle(double r) : radius(r) {} double area() override { re...
magicoder
cpp
You are tasked with implementing a class to manage time-series data insertion. The class should support adding data points with timestamps and values, and provide a method to retrieve the average value for a given time range. You need to implement the following methods for the `TestTimeseriesDataInsert` class: 1. `ad...
```python class TestTimeseriesDataInsert: def __init__(self): self.data = [] def add_data(self, timestamp, value): self.data.append((timestamp, value)) def get_average_value(self, start_time, end_time): total = 0 count = 0 for timestamp, value in self.data: ...
magicoder
python
You are tasked with creating a function to analyze network connection data and generate a message for each network device based on the duration of connection gaps. The function should take in a pandas DataFrame `network_tests` containing network connection test results and a string `flxbx` representing the hostname of ...
```python import pandas as pd def get_timedelta_info(td): days = td.days hours, remainder = divmod(td.seconds, 3600) minutes, seconds = divmod(remainder, 60) return days, hours, minutes, seconds def generate_network_message(network_tests, flxbx): device_data = network_tests[network_tests['hostname...
magicoder
python
You are tasked with creating a Swift function that processes bill payments using the BPAY system. The function should handle the payment process and error handling based on the provided code snippet. Your task is to implement the `bpayPayment` function that takes in the payment details and a completion handler. The co...
```swift import Foundation enum DataError: Error { enum DataErrorType { case api } enum DataErrorSubType { case invalidData } case apiError(type: DataErrorType, subType: DataErrorSubType) } class Payments { let service: PaymentService init(service: PaymentService)...
magicoder
swift
You are tasked with creating a program that reads a file and counts the number of lines containing a specific word. The program should take a file path and a target word as input, and then output the count of lines containing the target word. You are provided with a code snippet that opens a file and reads its content...
```rust use std::fs::File; use std::io::{self, BufRead}; use std::path::Path; fn read_lines(filename: &str) -> io::Result<io::Lines<io::BufReader<File>>> { let file = File::open(filename)?; Ok(io::BufReader::new(file).lines()) } fn main() { println!("Enter the file path: "); let mut file_path = String...
magicoder
rust
You are working on a meteorological data processing system that includes a class `echo_classifn` with methods for applying various convective criteria to radar reflectivity data. One such method is `apply_convective_criterion1`, which takes in radar reflectivity data, parameters, and grid metadata to produce a flag mat...
```python import numpy def apply_convective_criterion2(reflectivity_matrix_dbz, peakedness_neigh_metres, max_peakedness_height_m_asl, halve_resolution_for_peakedness, min_composite_refl_dbz, grid_metadata_dict): # Your implementation here # Example implementation using a simple threshold-based criterion co...
magicoder
python
You are tasked with creating a class that calculates the scaling factor for a given DPI (dots per inch) value. The DPI scaling factor is used to adjust the size of graphical elements on a display based on the screen's DPI setting. Your task is to implement a method that takes a DPI value as input and returns the corres...
```csharp public float CalculateScalingFactor(int dpiValue) { if (dpiValue <= 0) { throw new ArgumentException("DPI value must be greater than 0"); } return dpiValue / DEFAULT_DPI; } ``` The `CalculateScalingFactor()` method takes an integer `dpiValue` as input and first checks if the value is...
magicoder
csharp
You are working on an image processing application that involves loading input images and applying a mask to them. The given code snippet is a part of this application and involves processing the input images and creating a masked input for further processing. Your task is to implement a function that takes an origina...
```python import cv2 import numpy as np from PIL import Image import torchvision.transforms.functional as TF import torch def create_masked_input(original_image, threshold): # Loading Input and Mask # Assuming self.set_input() loads img_m, img_c, img_truth, and mask img_m, img_c, img_truth, mask = self.set...
magicoder
python
You are tasked with implementing a sparse gamma list data structure in C#. A sparse gamma list is a data structure that represents a list of non-negative integers in a memory-efficient manner. It is particularly useful when dealing with large lists containing mostly small integers. The sparse gamma list is initialized...
```csharp using System; using System.Collections.Generic; public class SparseGammaList { /// <summary> /// Default tolerance for sparsity approximation /// </summary> public static double DefaultTolerance = 0.01; private List<int> denseList; private Dictionary<int, int> sparseList; private...
magicoder
csharp
You are tasked with implementing a Python function that processes a list of application command interaction data options and returns the count of each type of option present in the list. The interaction data options are represented by the following classes: `_ApplicationCommandInteractionDataOptionString`, `_Applicatio...
```python from typing import List, Dict, Union class _ApplicationCommandInteractionDataOptionString: pass class _ApplicationCommandInteractionDataOptionInteger: pass class _ApplicationCommandInteractionDataOptionSubcommand: pass class _ApplicationCommandInteractionDataOptionBoolean: pass def count_...
magicoder
python
You are tasked with creating a Swift program to process and display stock search results obtained from an API. The provided code snippet includes a Swift struct `SearchResults` that conforms to the `Decodable` protocol. It contains a property `bestMatches` which is an array of `AssetModel` instances. Each `AssetModel` ...
```swift import Foundation struct AssetModel: Decodable { let symbol: String let name: String let type: String let region: String } struct SearchResults: Decodable { let bestMatches: [AssetModel] } func displayStockSearchResults(_ searchResults: SearchResults) { if searchResults.bestMatches.i...
magicoder
swift
You are tasked with implementing a function to perform arithmetic operations on a specific type of field used in elliptic curve cryptography. The field in question is the X448 field, which is used in the RFC 7748 standard for Diffie-Hellman key exchange. Your task is to implement a function `x448FieldAdd` that takes t...
```cpp #include <array> std::array<uint64_t, 5> x448FieldAdd(const std::array<uint64_t, 5>& x, const std::array<uint64_t, 5>& y) { const uint64_t P = (1ULL << 56) - 1; // Prime number 2^448 - 2^224 - 1 std::array<uint64_t, 5> result; uint64_t carry = 0; for (int i = 0; i < 5; ++i) { uint64_t x...
magicoder
cpp
You are tasked with creating a program that simulates the behavior of a simplified shell script interpreter. The interpreter will process a given script and execute the commands based on the defined conditions. The script contains a conditional statement that checks the value of the variable `servname` and sets the var...
To solve this problem, you can use a programming language such as Python to implement the shell script interpreter. Here's a Python solution to parse the script and set the value of `gmagick` based on the conditional statement: ```python # Define the script snippet script_snippet = ''' # env for graphicsmagick gmagick...
magicoder
python
You are tasked with creating a YouTube video downloader web application using Python and Flask. The application should allow users to input a YouTube video URL and download the corresponding video. To achieve this, you need to implement the `download_video` function in the Flask application. The function should handle ...
```python from flask import Flask, render_template, request, redirect, url_for from pytube import YouTube import os app = Flask(__name__) @app.route("/") def youtube_downloader(): my_css = url_for('static', filename='cover.css') return render_template('index.html', css_path=my_css) @app.route("/download_vide...
magicoder
python
You are tasked with creating a program to manage and display the URLs of various services in a system. The program should allow users to add, update, and retrieve the URLs of different services. Each service is identified by a unique key, and the program should support optional URLs for certain services. You are given...
```java import java.util.HashMap; import java.util.Map; public class ServiceURLManager { private Map<String, String> serviceURLs; public ServiceURLManager() { this.serviceURLs = new HashMap<>(); } public void addServiceURL(String key, String url, String description) { serviceURLs.put(...
magicoder
java
You are tasked with implementing a function to calculate the scaled L2 distance between two sets of vectors. The scaled L2 distance is defined as the L2 norm of the element-wise differences between the vectors, where each dimension of the difference is scaled by a corresponding scaling factor. The problem involves crea...
```python import torch from torch.autograd import Variable import encoding.functions # Assuming the scaled_l2 function is defined in encoding.functions def scaled_l2_distance(X, C, S): # Expand dimensions to enable broadcasting X_expanded = X.unsqueeze(2) # Shape: (B, N, 1, D) C_expanded = C.unsqueeze(1)...
magicoder
python
You are tasked with creating a Python program to implement a simple spam filter using the Naive Bayes algorithm. The program should take two command-line arguments: `--train_set` for the path to the training dataset and `--test_set` for the path to the test dataset. The training dataset contains labeled email data, whe...
```python import argparse import pandas as pd from sklearn.feature_extraction.text import CountVectorizer from sklearn.naive_bayes import MultinomialNB def main(): parser = argparse.ArgumentParser(description='Homework 3: Antispam') parser.add_argument('--train_set', required=True, help='kaggle_train_data_tab....
magicoder
python
You are tasked with implementing a program to process images for a Braille printer's OCR (Optical Character Recognition) system. The program should utilize the Python Imaging Library (PIL) to perform image enhancement and prepare the image for OCR processing. Your task is to complete the `process_image` function in th...
```python # ocr.py from PIL import Image, ImageEnhance def process_image(input_image_path, output_image_path): # Open the input image input_image = Image.open(input_image_path) # Enhance the image for improved contrast and sharpness enhanced_image = ImageEnhance.Contrast(input_image).enhance(1.5) ...
magicoder
python
You are tasked with implementing a convolutional neural network (CNN) layer using Python. Your goal is to create a class that performs the convolution operation on input images using a set of learnable filters (also known as kernels). The class should support both single and batch input images and should handle the cal...
```python import numpy as np class ConvolutionLayer: def __init__(self, num_filters, kernel_size, stride): self.num_filters = num_filters self.kernel_size = kernel_size self.stride = stride self.weights = np.random.randn(num_filters, kernel_size[0], kernel_size[1]) def forward(...
magicoder
python
You are tasked with implementing a Texture class for a game engine. The class should have a method `LoadTexture` that loads a texture from a file and sets its parameters. The method should use OpenGL calls to generate and configure the texture. Your task is to complete the `LoadTexture` method to ensure that the textur...
```cpp void Texture::LoadTexture(const std::string& file) { // Generate a texture ID GLCall(glGenTextures(1, &m_RendererID)); // Bind the texture for configuration Bind(); // Load the texture from file using appropriate library (not shown here) // Set texture parameters GLCall(glTexParame...
magicoder
cpp
You are tasked with implementing a Python class that generates a sequence of dates based on a given start year. The class should have a method to initialize a dictionary with specific key-value pairs and another method to generate dates based on the start year. You need to implement the following class: ```python cla...
```python from datetime import datetime, timedelta class DateGenerator: def __init__(self, API_KEY, latitude, longitude): # Initialize a dictionary with specific key-value pairs self.DICT = dict(api_key=API_KEY, latitude=latitude, longitude=longitude) # Initialize a date generator based on ...
magicoder
python
You are tasked with creating a program that parses and extracts information from a string containing metadata about a GitHub repository. The metadata string contains the repository name, the username of the owner, and the number of stars the repository has received. Your program should extract this information and form...
```python import re def parse_github_metadata(metadata: str) -> dict: pattern = r'<reponame>(.*?)<gh_stars>(\d+)[\s\S]*?Copyright \(C\) (\d+)-(\d+) (.*?),' match = re.search(pattern, metadata) if match: repository_name = match.group(1) stars_count = int(match.group(2)) description ...
magicoder
python
You are tasked with implementing a function that simulates a simple version control system. The function will take in a series of work functions, each representing a change to be committed. The function should return an object representing the state of the system after all the changes have been applied. The function s...
```typescript const versionControl = (commit: Commit): ReturnType<Driver> => { let el: DOMNode; let oldVNode: VNode; let newVNode: VNode; const effects: (() => void)[] = []; const commitWrapper: Commit = (work: Work) => { const tempEl = el; // Store the current element work(); // Apply the change ...
magicoder
typescript
You are tasked with creating a Rust macro that reads data from a file and initializes a static array with the read values. The macro should be able to handle different data types and array sizes. Your task is to implement the `lazy_static_include_array!` macro to achieve this functionality. The macro should take the f...
```rust #[macro_use] extern crate lazy_static; use std::fs::File; use std::io::{BufRead, BufReader}; macro_rules! lazy_static_include_array { (pub $name:ident: [$type:ty; $size:expr] => $file:expr) => { lazy_static! { pub static ref $name: [$type; $size] = { let file = File::op...
magicoder
rust
You are given a tree with n nodes, where each node has a non-negative integer weight associated with it. The tree is rooted at node 1 and the nodes are numbered from 1 to n. Your task is to find the maximum sum of weights of two non-adjacent nodes in the tree. You are provided with a code snippet that performs a depth...
```cpp #include <vector> #include <algorithm> struct Edge { int node; int weight; }; std::vector<std::vector<Edge>> tree; std::vector<bool> vis; void dfs(int node) { vis[node] = true; for (const Edge& edge : tree[node]) { if (!vis[edge.node]) { dfs(edge.node); } } } double maxSumOfNonAdjacen...
magicoder
cpp