query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with creating a program that processes a given Blade template and extracts the content within the `@section('body')` directive. Blade is a templating engine used in the Laravel PHP framework. The content within the `@section('body')` directive represents the main body of a web page and is enclosed within...
```python import re def extractBodyContent(blade_template: str) -> str: body_content = re.search(r"@section\('body'\)\s*([\s\S]*?)@endsection", blade_template) if body_content: return body_content.group(1).strip() else: return "" ``` The `extractBodyContent` function uses the `re` module i...
magicoder
python
You are tasked with creating a command-line interface (CLI) parser for a Python program. The provided code snippet demonstrates the initial steps of setting up the parser and handling the command-line arguments. Your task is to extend this functionality by implementing a function that processes the parsed arguments and...
```python import argparse import sys def add_parser(config): # Implementation of add_parser function is not provided as it is not relevant to the problem def process_arguments(parsed_args): if parsed_args.get('verbose'): print("Verbose mode enabled") if 'file' in parsed_args: try: ...
magicoder
python
You are tasked with creating a script that automates the process of starting a Node.js application using npm. Your script should handle any errors that may occur during the execution of the npm command and provide appropriate feedback to the user. Write a Node.js script that performs the following steps: 1. Executes t...
```javascript const { exec } = require('child_process'); // Execute the npm command to start the Node.js application const npmStartProcess = exec('/usr/bin/npm run start', (error, stdout, stderr) => { if (error) { console.error(`Error starting the application: ${error.message}`); return; } if (stderr) { ...
magicoder
javascript
You are tasked with implementing a virtual machine (VM) compiler that translates a high-level programming language into bytecode for a custom VM. The VM supports a set of instructions and has a specific memory layout. Your goal is to write a function that takes a list of high-level instructions and generates the corres...
```python def compile_to_bytecode(instructions): bytecode = [] for instruction in instructions: parts = instruction.split() if parts[0] == "PUSH": bytecode.append(int(parts[1])) elif parts[0] == "ADD": bytecode.append(1) elif parts[0] == "SUB": ...
magicoder
python
You are tasked with implementing a custom file reader class in Python. The class should be able to read a file and provide methods for reading the file content in different ways. Your task is to create a Python class called `CustomFileReader` with the following specifications: 1. The class should have a constructor th...
```python class CustomFileReader: def __init__(self, file_path): self.file_path = file_path self.file = open(file_path, 'r') def read_as_string(self): with self.file as f: return f.read() def read_as_lines(self): with self.file as f: return f.readlin...
magicoder
python
You are tasked with implementing a custom data processing class in Python for a machine learning project. The class should take a dictionary of features as input and return a dictionary of processed features as output. Your task is to complete the implementation of the `__call__` method in the class. You are given the...
```python import torch from typing import Dict class CustomDataProcessor: def __call__(self, features) -> Dict[str, torch.Tensor]: """ Process the input features and return the processed features. Args: - features: A dictionary containing input features. Returns: -...
magicoder
python
You are tasked with implementing a file storage system that stores entities in separate files, while ensuring unique identifiers for each entity. You are provided with a C++ class `SeparateFileStorage` that inherits from `Storage` and `IDGenerator`. The class has private members `dirPath_`, `entityIDs_`, and `nextID_`,...
```cpp #include <iostream> #include <fstream> #include <set> #include <filesystem> namespace fs = std::filesystem; // Assume the definition of the Entity class class Entity { // Implementation details of the Entity class }; class Storage { // Assume the definition of the Storage class }; class IDGenerator {...
magicoder
cpp
You are tasked with creating a script to automate the management of a specific process on a Linux system. The script should be able to identify and terminate a running process based on certain conditions. Your script should perform the following steps: 1. Use the `ps` command to list all running processes and filter t...
```bash #!/bin/bash # Use ps command to list all running processes and filter the output to find the specific process related to "start.sh" STR=$(ps -ax | grep "./start.sh") # Check if the process is found if [ "$STR" != "" ]; then # Extract the process ID (PID) using sed and terminate the process forcefully usin...
magicoder
shell
You are tasked with implementing an LRU (Least Recently Used) cache, which is a data structure that stores a fixed number of items and evicts the least recently used item when the cache reaches its limit. Your goal is to create a class `LRUCache` that supports the following operations: 1. `LRUCache(int capacity)`: Init...
```cpp #include <list> #include <unordered_map> #include <iostream> class LRUCache { private: int capacity; std::list<int> lruList; std::unordered_map<int, std::list<int>::iterator> cacheMap; public: LRUCache(int capacity) : capacity(capacity) {} void refer(int key) { if (cacheMap.find(ke...
magicoder
cpp
You are tasked with implementing a thread-safe work queue in C++ using the given code snippet as a starting point. The provided code snippet contains a partial implementation of a class that manages a queue of work items. Your task is to complete the implementation of the class by adding the necessary member functions ...
```cpp #include <iostream> #include <thread> void producer(ThreadSafeWorkQueue<int>& workQueue) { for (int i = 0; i < 10; ++i) { workQueue.add(new int(i)); std::this_thread::sleep_for(std::chrono::milliseconds(100)); } } void consumer(ThreadSafeWorkQueue<int>& workQueue) { for (int i = 0; ...
magicoder
cpp
You are working on a research project that involves running multiple trials of a Markov Chain Monte Carlo (MCMC) simulation. The goal is to estimate certain parameters using the MCMC method. You have a set of data points represented by the variable `Ms`, and you want to perform the MCMC simulation for different values ...
```python import numpy as np def run_mcmc_simulation(anms, Ms, n_trials, mcmc_steps, mu): csizes = np.zeros((len(anms), n_trials, Ms.shape[0])) Fs = np.zeros((len(anms), n_trials, Ms.shape[0])) cputs_full = np.zeros(n_trials) chains = np.zeros((n_trials, mcmc_steps, mu.shape[0])) for tr in range(n...
magicoder
python
You are tasked with implementing a custom button class in Python. The class should have specific properties and handle the initialization of these properties. Your task is to complete the implementation of the `Button` class by filling in the missing parts of the code. The `Button` class has the following requirements...
```python class Button(SuperClass): # Replace SuperClass with the actual superclass def __init__(self, children, **kwargs): self.available_properties = ['children', 'id', 'style', 'className', 'disabled', 'dangerDescription', 'href', 'isSelected', 'kind', 'role', 'size', 'tooltipAlignment', 'tooltipPositio...
magicoder
python
You are tasked with creating a Python function that processes a list of tweets and returns the top N most frequently used words in the tweets. You should use the NLTK library to tokenize the tweets and remove stop words. The function should take two parameters: the list of tweets and the value of N, and should return a...
```python from nltk.corpus import stopwords from nltk.tokenize import word_tokenize from collections import Counter import string def topNWordsInTweets(tweets, N): stop_words = set(stopwords.words('english')) word_freq = Counter() for tweet in tweets: tweet = tweet.lower() tweet = twee...
magicoder
python
You are tasked with creating a class that represents an AWS CloudFormation resource for managing triggers in IoT Analytics datasets. Your task is to implement a method within the `Trigger` class that converts an instance of the class into a JSON representation using the Newtonsoft.Json library. The JSON representation ...
```csharp using Newtonsoft.Json; using Comformation.IntrinsicFunctions; namespace Comformation.IoTAnalytics.Dataset { /// <summary> /// AWS::IoTAnalytics::Dataset Trigger /// https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-dataset-trigger.html /// </summary> ...
magicoder
csharp
You are tasked with implementing a function to plot a 3D mesh using the matplotlib library in Python. The function `plot_mesh_general` takes a file path as input and is expected to read the topology data from the file, then create a 3D plot of the mesh using the obtained topology data. The `get_topology` function is a...
```python import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np def plot_mesh_general(path): x, _, tri = get_topology(path) fig = plt.figure(figsize=(8, 8)) ax = fig.add_subplot(111, projection='3d') # Plot the vertices ax.scatter(x[:, 0], x[:, 1], x[:, 2], c='...
magicoder
python
You are tasked with implementing a function that performs a topological sort on a directed graph represented as an adjacency list. The graph consists of nodes labeled from 0 to n-1, where n is the number of nodes. Your function should return a list of nodes in topological order. If the input graph is not a directed acy...
```cpp #include <vector> #include <queue> std::vector<int> topologicalSort(const std::vector<std::vector<int>>& graph) { int n = graph.size(); std::vector<int> inDegree(n, 0); for (const auto& neighbors : graph) { for (int neighbor : neighbors) { inDegree[neighbor]++; } } ...
magicoder
cpp
You are tasked with implementing a function to parse and process a series of 2D polygons from a given input file. The input file contains a list of vertices for each polygon, with each vertex represented by its x and y coordinates. The file format is as follows: - The first line contains an integer N, representing the ...
```python import math def processPolygons(file_path): with open(file_path, 'r') as file: num_polygons = int(file.readline()) for i in range(num_polygons): line = file.readline().split() num_vertices = int(line[0]) vertices = [list(map(float, line[j:j+2])) for j i...
magicoder
python
You are tasked with implementing a function to initialize and populate a 2D array based on the given code snippet. The function should take in the following parameters: - `atom` : a structure containing information about atom types - `nq` : a structure containing information about neighbor lists - `memory` : a memory m...
```cpp void initializeArrays(Atom* atom, Neighbor* nq, Memory* memory) { int ntypes = atom->ntypes; int* iskip = new int[ntypes+1]; int** ijskip = new int*[ntypes+1]; for (int i = 1; i <= ntypes; i++) { iskip[i] = nq->iskip[i]; ijskip[i] = new int[ntypes+1]; } for (int i = 1; i <...
magicoder
cpp
You are given a C# program that processes an array of integers and calculates the sum of specific values. Your task is to understand the given code and complete the missing part to achieve the desired output. The given code snippet is part of a C# program that processes an array of integers. The missing part of the co...
```csharp using System; class Program { static void Main() { int[] array = { 1, 4, 7, 2, 4, 8, 1, 7, 4, 3, 6, 8, 1, 4, 7, 8 }; int count = 0; int sum = 0; foreach (int value in array) { if (value == 1 || value == 4 || value == 7 || value == 8) {...
magicoder
csharp
You are tasked with implementing a Python class that extends a base class and overrides a method to compute a specific expression. Your task is to complete the implementation of the `computeExpression` method in the `ExpressionBuiltinDir1` class. The `computeExpression` method takes a `trace_collection` parameter and s...
```python class ExpressionBuiltinDir1(ExpressionBuiltinSingleArgBase): kind = "EXPRESSION_BUILTIN_DIR1" def computeExpression(self, trace_collection): # Predict and handle cases related to the dir function # Example cases to handle: # 1. Predict attributes for built-in types like int, s...
magicoder
python
You are tasked with implementing a class that handles accepting invitations from a cloud service. The class `AcceptInvitationTask` is responsible for processing the acceptance of invitations and communicating with the cloud service. The `doInBackground` method is part of an asynchronous task and is used to perform back...
```java @Override protected InvitationResult doInBackground(Invitation... invites) { Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://10.0.2.2:11004") .addConverterFactory(GsonConverterFactory.create()) .build(); CloudServiceApi service = retrofit.create(CloudServ...
magicoder
java
You are tasked with implementing a Python class that represents a locator for a geographical location. The locator should have attributes for latitude and longitude, and it should provide a method to calculate the distance between two locators using the Haversine formula. Your task is to complete the implementation of...
```python from math import radians, sin, cos, sqrt, atan2 class Locator: def __init__(self, latitude, longitude): self.latitude = latitude self.longitude = longitude def distance_to(self, other): R = 6371 # Radius of the Earth in kilometers lat1, lon1 = radians(self.latitude),...
magicoder
python
You are tasked with implementing a user authentication system using Python and the Marshmallow library for data serialization. Your goal is to create two classes, `CreateUserSchema` and `UpdateUserSchema`, which will be used to define the schema for creating and updating user data, respectively. The `CreateUserSchema`...
```python from marshmallow import Schema, fields, post_load from hashlib import sha256 class User: def __init__(self, username, password): self.username = username self.password = password class UserSchema(Schema): username = fields.Str() password = fields.Str() class CreateUserSchema(Use...
magicoder
python
You are given a Python class `Particle` with the following attributes and methods: Attributes: - `n_levels()`: Returns the number of energy levels of the particle. - `t()`: Returns the time of the particle. - `z()`: Returns the position of the particle. You need to implement a method `check_energy_levels()` that init...
```python import numpy class Particle: def __init__(self, energy_levels, time, position): self.energy_levels = energy_levels self.time = time self.position = position def n_levels(self): return len(self.energy_levels) def t(self): return self.time def z(self):...
magicoder
python
You are tasked with implementing a role-based access control system for a web application. The system should restrict access to certain URLs based on the roles of the users. You are given a code snippet that demonstrates how the access control system should be tested. The code snippet shows the usage of an `assert_res...
```python class AccessControlSystem: def __init__(self): self.superuser = 'superuser' self.anonymous = 'anonymous' self.regular_user = 'regular_user' self.url_permissions = { '/public': [self.superuser, self.anonymous, self.regular_user], '/admin': [self.super...
magicoder
python
You are working on a Rust compiler and are tasked with implementing a new feature related to evaluating predicate obligations. In the code snippet provided, there are two methods defined within a Rust trait implementation. The methods are used to evaluate whether a given predicate obligation can be satisfied in a given...
```rust fn evaluate_predicate_obligations<'tcx>( obligations: &[PredicateObligation<'tcx>], param_env: &ParamEnv<'tcx>, ) -> bool { obligations.iter().all(|obligation| { evaluate_obligation_no_overflow(param_env, obligation).must_apply_considering_regions() }) } fn evaluate_obligation_no_overfl...
magicoder
rust
You are tasked with implementing a simplified version of a key-reading module for a liquid crystal display (LCD) controller. The LCD controller is interfaced with a microcontroller, and the key-reading module is responsible for reading input from a keypad and transmitting the corresponding key information to the LCD co...
```java char readKey() { // Simulated logic for reading key from the keypad // Replace this with actual code to read the key from the keypad // Example: return getKeyFromKeypad(); return getKeyFromKeypad(); } // Example implementation of getKeyFromKeypad() function char getKeyFromKeypad() { // Simu...
magicoder
java
You are tasked with creating a Python function that simulates a simple game scenario. The game involves a player navigating through a maze using a virtual robot. The robot can move in four directions: up, down, left, and right. The maze is represented as a 2D grid, where the robot's current position is denoted by 'R', ...
```python from typing import List def navigate_maze(maze: List[str], moves: List[str]) -> str: directions = {'U': (-1, 0), 'D': (1, 0), 'L': (0, -1), 'R': (0, 1)} rows, cols = len(maze), len(maze[0]) robot_pos = None for r in range(rows): for c in range(cols): if maze[r][c] == 'R':...
magicoder
python
You are tasked with creating a Python class for solving chemical equilibrium systems using the MINPACK solver. The MINPACK solver is initialized with specific parameters and settings. Your task is to implement the class and its methods to handle chemical equilibrium calculations. Your class should include the followin...
```python import sys from pprint import pprint class ChemicalEquilibriumSolver: def __init__(self, logger): self.logger = logger self.exprs = [] # Placeholder for chemical equilibrium expressions self.jac = [] # Placeholder for Jacobian matrix def print_expressions_and_jacobian(sel...
magicoder
python
You are tasked with implementing a feature for a contact form management system. The system has a `ContactUsController` with a `destroy` method responsible for deleting a contact form entry from the database. The method uses the `ContactUs` model to perform the deletion and then redirects the user to the index page wit...
```php public function destroy(Request $request) { $id = $request->input('id'); // Validate input if (!is_numeric($id)) { return redirect()->back()->with('error', 'Invalid input for ID'); } // Find the contact form entry $contactUsEntry = ContactUs::find($id); // Handle non-existe...
magicoder
php
You are tasked with implementing a class that manages the storage and retrieval of events in a stream using PHP. The class, named `EventStreamManager`, has a constructor that takes two parameters: a `Client` object from the Predis library and a `Serializer` object. The `Client` object represents a connection to a Redis...
```php public function append(Stream $stream) : void { $order = $this->countStoredEventsOfStream($stream) + 1; foreach ($stream->events() as $event) { $storedEvent = new StoredEvent( $order, $stream->name(), $event->data(), $event->occurredAt() );...
magicoder
php
You are tasked with implementing a game-saving feature for a 2D adventure game. The game consists of a player character navigating through various zones, defeating enemies, collecting items, and interacting with objects such as chests. The goal is to create a function that saves the game state, including the player's p...
```python class GameState: def __init__(self, player_position, player_inventory, defeated_enemies, player_stats, zone_chests): self.player_position = player_position self.player_inventory = player_inventory self.defeated_enemies = defeated_enemies self.player_stats = player_stats ...
magicoder
python
You are tasked with creating a SwiftUI application that tracks the number of commits made when editing a text field and displays the current text input along with the focus state of another text field. Your application should consist of the following components: 1. Two `TextField` views: - The first `TextField` sho...
```swift import SwiftUI struct ContentView: View { @State private var text = "" @State private var numCommits = 0 @State private var isFocused = false @State private var emptyString = "" var body: some View { VStack { TextField("Basic text field", text: $text) TextF...
magicoder
swift
You are given a binary tree represented by a class `TreeNode` with the following structure: ``` class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } ``` The `val` field represents the value of the node, and the `left` and `right` fields represent the left and right chi...
```java class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } int ans = 0; public int calculateAbsSum(TreeNode root) { dfs(root); return ans; } public int dfs(TreeNode node) { if (node == null) return 0; int left = df...
magicoder
java
You are working on a computer graphics project and need to implement a function that processes color and direction data using PyTorch. The function takes in two parameters: `color_directional` and `direction`. The `color_directional` parameter represents the color information for directional light, and the `direction` ...
```python import torch import numpy as np def process_color_directional(color_directional, direction, color_ambient, device): if isinstance(color_directional, list) or isinstance(color_directional, tuple): color_directional = torch.tensor(color_directional, dtype=torch.float32, device=device) elif isin...
magicoder
python
You are tasked with creating a dependency resolution algorithm for a package manager. The package manager needs to resolve dependencies for targets within a package, considering both internal and external dependencies. Each target within a package can depend on other targets within the same package, as well as on prod...
```swift func resolveDependencies(configuration: [String], externalDependencies: [String: [String]]) -> [String: [String]] { var resolvedDependencies: [String: [String]] = [:] for entry in configuration { if entry.hasPrefix(".target") || entry.hasPrefix(".testTarget") { let components = ent...
magicoder
swift
You are tasked with implementing a function to measure the quality of seeds in an agricultural environment. The function should take into account the good and bad seeds present and produce a measurement based on specific criteria. You are given the following information: - `bad_seeds_01_env` is an object representing ...
```python def measure_seed_quality(bad_seeds_01_env): measurement = bad_seeds_01_env.good_seeds # Initialize measurement with the good seeds for _ in range(3): # Measure the bad seeds three times measurement = take(2 * len(bad_seeds_01_env.good_seeds), concatv(measurement, measurement)) # Concatenate...
magicoder
python
You are working on a project that involves interacting with Xcode build settings and extracting specific information from the build configuration. Your task is to implement a function that parses the build settings output and extracts the debug directory for a given module. You are provided with a code snippet that de...
```swift public enum BuildSettingsError: Error { case invalidOutput case moduleNotFound } public func getSourceKitModuleInterface(module: String, logger: Logger) throws -> [String: Any] { let config = try execProcess("xcodebuild", ["-project", "*.xcodeproj", "-target", module, "-showBuildSettings", "-confi...
magicoder
swift
You are tasked with creating a custom annotation processor for a Java application. The application uses a framework that requires entities to be annotated with a specific table name for database mapping. Your goal is to implement a processor that will validate and process these annotations to ensure they adhere to the ...
```java import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import javax.tools.Diagnostic; import java.util.Set; @Sup...
magicoder
java
You are tasked with creating a command-line utility that processes a series of command-line arguments to perform various operations on a given file. The utility should support the following options: - `-ander`: This option specifies a specific operation to be performed by the utility. - `-print-pts`: This option indic...
```python import argparse def process_command_line_arguments(): parser = argparse.ArgumentParser(description='Command-line utility for processing file with various options') parser.add_argument('-ander', action='store_true', help='Perform specific operation') parser.add_argument('-print-pts', action='store...
magicoder
python
You are tasked with creating a program to manage the placement of windows on a computer screen. The screen is represented as a 2D grid, and each window is represented by a rectangular area on this grid. Your program should be able to handle the placement of windows, check for overlapping areas, and provide information ...
```python def manageWindows(screen, windows): total_area_covered = 0 overlapping_areas = [] for window in windows: row, col, height, width = window for i in range(row, row + height): for j in range(col, col + width): if screen[i][j] == 1: ...
magicoder
python
You are tasked with creating a Python function that simulates a simplified version of the `import` mechanism. Your function should take a module name, a module specification, and a loader as input, and return the imported module. The function signature should be: ```python def custom_import(name, spec, loader): # ...
```python import importlib.util import sys def custom_import(name, spec, loader): module = importlib.util.module_from_spec(spec) # Create a module from the given specification sys.modules[name] = module # Associate the module with the provided name in sys.modules loader.exec_module(module) # Execute the...
magicoder
python
You are tasked with creating a command-line utility that processes YAML files and performs specific operations based on user input. The utility should support setting, updating, and deleting YAML properties. Your task is to implement the logic for processing the user's commands and modifying the YAML file accordingly. ...
To solve this problem, you can create a command-line utility using a programming language of your choice, such as Python, Go, or Bash. Below is a Python-based solution using the `pyyaml` library to handle YAML processing. ```python import sys import yaml def process_command(yaml_data, command): if command.startsw...
magicoder
python
You are given a 2D matrix of integers and an integer k. Your task is to find the maximum sum of a submatrix that is less than or equal to k. You need to implement the function `max_sum_submatrix` that takes in the following parameters: - A reference to a 2D vector `matrix` of integers, representing the input matrix. -...
```cpp #include <set> #include <vector> #include <climits> using namespace std; int max_sum_submatrix(vector<vector<int>> &matrix, int k) { int m = matrix.size(), n = matrix[0].size(); int maxSum = INT_MIN; for (int left = 0; left < n; ++left) { vector<int> sums(m, 0); for (int right = lef...
magicoder
cpp
You are given a function `hamming(n)` that returns the nth number in the Hamming sequence. The Hamming sequence is a set of numbers in ascending order that only have 2, 3, or 5 as prime factors. The first few numbers in the Hamming sequence are 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24, and so on. The given c...
```python def hamming(n): hamming = {1} # Initialize the Hamming sequence with 1 new_hamming = set() # Initialize a set to store new numbers while len(hamming) < n: for i in hamming: new_hamming.add(i * 2) new_hamming.add(i * 3) new_hamming.add(i * 5) #...
magicoder
python
You are working on a data visualization project and need to create a Python function to generate a composite spectral energy distribution (SED) plot. The SED plot should display the normalized flux ($\lambda$ F$_\lambda$) against the rest wavelength ($\AA$). You have been provided with a code snippet that sets the y-ax...
```python import matplotlib.pyplot as plt from typing import List def generate_composite_sed_plot(rest_wavelength: List[float], normalized_flux: List[float], save_directory: str) -> None: fig, ax = plt.subplots() ax.plot(rest_wavelength, normalized_flux, marker='o', linestyle='-') ax.set_ylim(-1e-16, 9e-16...
magicoder
python
You are tasked with implementing a ViewModel class for a mobile app using the RxSwift framework. The ViewModel will be responsible for fetching and processing data from a remote source and providing it to the UI components. Your task is to complete the implementation of the ViewModel class by adding the necessary meth...
```swift import Foundation import Data import RxSwift class ViewModel { let dataFetcher: DataFetcher init(dataFetcher: DataFetcher) { self.dataFetcher = dataFetcher } func fetchData() -> Observable<DataResponse> { return Observable.create { observer in self.dataFet...
magicoder
swift
You are tasked with creating a program that simulates a simple terminal multiplexer. A terminal multiplexer is a software application that enables multiple terminals to be accessed and controlled from a single terminal. Your program should allow users to create, switch between, and manage multiple virtual terminals wit...
```rust use std::collections::HashMap; struct TerminalMultiplexer { terminals: HashMap<String, String>, active_terminal: String, } impl TerminalMultiplexer { fn new() -> TerminalMultiplexer { let mut terminals = HashMap::new(); terminals.insert("default".to_string(), "".to_string()); ...
magicoder
rust
You are tasked with implementing a simplified version of the ChaCha encryption algorithm in Rust. The ChaCha algorithm is a symmetric encryption algorithm designed to provide high security and performance. Your task is to implement the core functionality of the ChaCha algorithm, including the key setup and encryption p...
```rust // chacha.rs const ROUNDS: usize = 20; pub struct ChaCha { state: [u32; 16], } impl ChaCha { pub fn new(key: [u8; 32], nonce: [u8; 8]) -> ChaCha { let mut state = [0u32; 16]; state[0] = 0x61707865; state[1] = 0x3320646e; state[2] = 0x79622d32; state[3] = 0x6b206...
magicoder
rust
You are working on a database migration script using Alembic, a popular database migration tool for SQLAlchemy. Your task is to write a migration script that modifies the database schema by dropping a column from a table and altering the data type of another column. Given the provided code snippet, you need to complet...
The table and columns to be modified based on the provided code snippet are: - Table: 'airdrop' - Columns: 'stakable_token_name' and 'claimable_amount' The Alembic migration commands to achieve the required database schema modifications are as follows: ```python def upgrade(): # ### commands auto generated by Ale...
magicoder
python
You are tasked with implementing a simple inter-process communication (IPC) mechanism using Python. Your goal is to create a program that utilizes the `os.pipe()` function to establish a unidirectional communication channel between a parent process and a child process. The parent process will write a message to the chi...
```python import os import sys def main(): r, w = os.pipe() pid = os.fork() if pid > 0: # Parent process os.close(r) # Close the read end of the pipe in the parent process message = "Hello, child process!" os.write(w, message.encode()) # Write the message to the pipe os...
magicoder
python
You are tasked with creating a Python program that will recursively search for all files with a specific file extension within a given directory and its subdirectories. Your program should measure the time taken to perform the search and display the total number of files found. You are provided with a code snippet tha...
```python from pathlib import Path from time import perf_counter def search_files_by_extension(basepath, file_extension): start_time = perf_counter() total_files = 0 try: base_dir = Path(basepath) if base_dir.is_dir(): for file in base_dir.rglob(f'*{file_extension}'): ...
magicoder
python
You are tasked with implementing a Python function that simulates a simple HTTP client for making requests to a server. The client is expected to handle various HTTP status codes and raise appropriate exceptions based on the received status codes. Your goal is to create a function that can be used to test the behavior ...
```python class CORSException(Exception): pass def simulate_client_response(endpoint: str, expected_statuses: list, status_messages: dict) -> str: # Simulate the client's behavior based on the received status code received_status_code = make_request_to_server(endpoint) # Assume a function to make the actu...
magicoder
python
You are tasked with implementing a class for handling dynamic link libraries (DLLs) in C++. The class, `dll::Handler`, is responsible for managing the loading and unloading of DLLs. The given code snippet shows a move assignment operator and a constructor for the `dll::Handler` class. Your task is to complete the impl...
```cpp #include <iostream> #include <string> #include <windows.h> namespace dll { class Handler { public: Handler() : m_handler(nullptr) {} Handler(Handler&& o) noexcept : m_handler(std::exchange(o.m_handler, nullptr)), m_libpath(std::move(o.m_libpath)) {} Hand...
magicoder
cpp
You are tasked with creating a Python class that manages SSH keys for cloud services. Your class should be able to generate, update, and store SSH keys in a database. Additionally, it should provide a debugging feature to display verbose information during key management operations. Create a Python class `SSHKeyManage...
```python from cloudmesh.management.configuration.SSHkey import SSHkey from cloudmesh.mongo.DataBaseDecorator import DatabaseUpdate from cloudmesh.common.debug import VERBOSE class SSHKeyManager: def generate_key(self): # Generate a new SSH key pair public_key, private_key = SSHkey.generate() ...
magicoder
python
You are tasked with creating a memory management system for a file-backed memory mapping in Rust. Your goal is to implement a custom drop behavior for a wrapper struct that manages the memory mapping. The provided code snippet shows the implementation of the `Drop` trait for the `FileBackedMemoryDropWrapper` struct. Th...
```rust use std::fs::File; use std::os::unix::io::{AsRawFd, FromRawFd}; use std::ptr; use libc::{c_void, off_t, MAP_FAILED, MAP_SHARED, PROT_READ, PROT_WRITE, ftruncate, mmap, munmap, MAP_ANON}; struct FileBackedMemoryDropWrapper { file: File, address: *mut c_void, mapped_length: usize, } impl FileBackedM...
magicoder
rust
You are tasked with implementing a Python class for training a signal convolutional neural network (SigCNN) using the given code snippet as a reference. The class should handle the initialization of hyperparameters, the initialization of the Weights and Biases (wandb) project, and the training of the SigCNN model. You...
```python from dataclasses import asdict import wandb class SigCnnTrainer: def __init__(self, hp): if not isinstance(hp, SigCnnHp): raise ValueError(f"wrong hyper-parameter class: {hp}") self.hp = hp def _train(self, model, device, data_dir, n_epochs, signal_metadata, submission):...
magicoder
python
You are tasked with creating a script to automate the deployment process for a Node.js application. The deployment process involves restarting the Nginx server, navigating to the application folder, installing dependencies using npm, and starting the Node.js application using pm2 with environment variables updated. Yo...
```bash #!/bin/bash # Restart Nginx server sudo service nginx restart # Navigate to the app folder cd ../.../app/ || { echo "Error: Unable to navigate to the app folder"; exit 1; } # Ensure dependencies are installed npm install || { echo "Error: Failed to install dependencies"; exit 1; } # Run the app.js using pm2...
magicoder
shell
You are tasked with implementing an iterator pattern for a custom collection class in Java. The iterator pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation. Your task is to create the necessary classes to support this pattern and demonstrate ...
```java package designpattern.behavioral.iterator; import java.util.ArrayList; import java.util.List; // Iterator interface interface Iterator { boolean hasNext(); Object next(); } // CustomCollection class class CustomCollection { private List<Object> elements = new ArrayList<>(); void add(Object obj) { ...
magicoder
java
You are working on a project that involves manipulating and querying graph data. Your task is to implement a method that sets variables based on a given map of values and a field name. The method should use reflection to access and modify the private fields of a Query object. You are given a partial code snippet that ...
```java private void setVars(Map<Var, Node> values, String fieldName) { if (values.isEmpty()) { return; } try { Field f = Query.class.getDeclaredField(fieldName); f.setAccessible(true); List<String> orig = (List<String>) f.get(query); List<String> lst = null; ...
magicoder
java
You are tasked with creating a program to manage work shifts for a company. The company has two teams, one for the day shift and the other for the night shift. Each shift lasts for 12 hours. Your task is to implement a class `WorkSchedule` and its associated methods to facilitate the management of shifts. Your program...
```python from datetime import time, timedelta class WorkSchedule: def __init__(self, name, description): self.name = name self.description = description self.shifts = [] def createShift(self, shift_type, shift_name, start_time, duration): shift = { "type": shift_ty...
magicoder
python
You are tasked with creating a program that simulates a simple text-based adventure game. The game will involve the player making choices that lead to different outcomes. The player will navigate through a series of rooms, each with its own set of choices and consequences. The goal is to reach the final room and achiev...
```python class Room: def __init__(self, description, choices, outcomes): self.description = description self.choices = choices self.outcomes = outcomes class TextAdventureGame: def __init__(self): self.rooms = { 'start': Room("You are in a dark forest. You see a pat...
magicoder
python
You are tasked with creating a program to analyze and visualize user access data for a web application. The program should read a dataset containing user access information and generate a bar chart to display the number of users accessing the application on each day. The dataset is in the following format: ``` Date, U...
```python import pandas as pd import matplotlib.pyplot as plt # Read the dataset into a pandas DataFrame data = { 'Date': ['2022-01-01', '2022-01-01', '2022-01-02', '2022-01-02', '2022-01-03', '2022-01-03'], 'User': ['user1', 'user2', 'user3', 'user1', 'user2', 'user4'] } df = pd.DataFrame(data) # Convert the...
magicoder
python
You are working on a firmware for a data acquisition system that includes multiple channels for reading analog signals. The system has a function `conv_settling_time` that calculates the settling time for a given channel. The settling time is the time required for the analog-to-digital converter to stabilize after a ne...
```rust use std::num::NonZeroU16; enum Channel { Channel1, Channel2, Channel3, // ... other channels } struct Error<T> { // Define the error type // For example: // message: String, // code: u32, // source: Option<T>, } struct DataAcquisitionSystem { // Define the data acquisi...
magicoder
rust
You are tasked with implementing a base64 encoding and decoding algorithm. Base64 encoding is a method of encoding binary data into ASCII text format. The encoding process involves taking a sequence of bytes and converting it into a sequence of printable ASCII characters. The decoding process reverses this operation, c...
```java import java.util.Base64; public class Base64EncoderDecoder { public static String encodeToBase64(byte[] data) { return Base64.getEncoder().encodeToString(data); } public static byte[] decodeFromBase64(String base64String) { return Base64.getDecoder().decode(base64String); } ...
magicoder
java
You are tasked with creating a macro in Rust that takes a given input and generates a string representation of the input. The macro should be able to handle various types of input, including integers, floats, strings, and identifiers. Your task is to implement the `stringify` macro, which takes an input and returns it...
```rust macro_rules! stringify { ($input:ident) => { stringify!($input) }; ($input:expr) => { stringify!($input) }; } fn main() { let int_val = 42; let float_val = 3.14; let string_val = "hello"; let identifier = get; println!("{}", stringify!(int_val)); // Output: ...
magicoder
rust
You are tasked with implementing a thread-safe singleton pattern in C#. The singleton pattern ensures that a class has only one instance and provides a global point of access to that instance. Your goal is to create a thread-safe implementation of a shared filter using the singleton pattern. You are provided with a co...
To create a thread-safe singleton pattern, you can use the double-checked locking approach along with the `lock` keyword to ensure that only one instance of the `LittleDifferenceFilter` is created. Here's a modified version of the code snippet to achieve this: ```csharp public class LittleDifferenceFilter { privat...
magicoder
csharp
You are tasked with implementing a function to standardize a given dataset using the Z-score method. The Z-score standardization involves transforming the data such that it has a mean of 0 and a standard deviation of 1. You are provided with a Python code snippet that includes the declaration of a variable `data_std` a...
```python import numpy as np def input_data(data: np.ndarray) -> np.ndarray: """ Standardize the input data using the Z-score method. Parameters: data : numpy.ndarray The input data to be standardized. Returns: numpy.ndarray The standardized data. """ mean = np.mean(d...
magicoder
python
You are tasked with implementing a Python function that simulates a simple image processing operation. The function should take an input image file and create a new image file with a modified color palette. You are provided with a code snippet that closes two file handles and then calls a function named `CreatePalette...
```python def CreatePalette(input_file, output_file): with open(input_file, 'rb') as input_image: # Read the color palette from the input image file color_palette = read_color_palette(input_image) # Modify the color palette to achieve a specific effect (e.g., grayscale conversion, color inv...
magicoder
python
You are tasked with implementing a custom database class in Python that supports reading and writing data. The class should handle exceptions and ensure data integrity. Your task is to complete the implementation of the `Database` class by filling in the missing methods. ```python class Database: def __init__(self...
```python class Database: def __init__(self, connection_string: str): self.connection_string = connection_string # Initialize the database connection using the connection_string def read(self, query: str) -> str: """ Reads data from the database using the provided query. ...
magicoder
python
You are tasked with simulating the behavior of a refractive interface when a collimated beam of light passes through it. A collimated beam is one in which the light rays are parallel, and a refractive interface is the boundary between two different mediums through which light can pass. The simulation should visualize t...
```python import numpy as np import matplotlib.pyplot as plt def refractive_interface_with_collimated_beam(do_plot): # Define refractive indices of the two mediums n1 = 1.5 # Refractive index of medium 1 n2 = 1.0 # Refractive index of medium 2 # Calculate angle of incidence theta_i = 30 # Angle...
magicoder
python
You are tasked with implementing a PHP trait that retrieves a license object from the Keygen.sh API. The trait, named `GetLicenseTrait`, is intended to be used within a larger PHP application for managing software licenses. Your goal is to complete the implementation of the `getLicense` method within this trait, which ...
```php use Keygen\License\License; use Keygen\Util\Debug; use GuzzleHttp\Client; trait GetLicenseTrait { /** * Returns a License object that was retrieved from the Keygen.sh API. * * @param string $licenseKey The license key to retrieve the license for. * @return License The retrieved License o...
magicoder
php
You are tasked with implementing a Python decorator that ensures the successful execution of a function by handling potential exceptions. The decorator should catch specific exceptions and retry the function a specified number of times before re-raising the exception. Your task is to write the `ensure` decorator and ap...
```python def ensure_decorator(max_attempts, exceptions): def decorator(func): def wrapper(*args, **kwargs): attempts = 0 while attempts < max_attempts: try: return func(*args, **kwargs) except exceptions as e: a...
magicoder
python
You are tasked with creating a program that simulates the process of building a software project using the CMake build system. CMake is a popular tool for managing the build process of software using a compiler-independent method. In this problem, you will need to implement a simplified version of the CMake build proce...
```python import os import subprocess def execute_command(command): try: subprocess.run(command, shell=True, check=True) return True, None except subprocess.CalledProcessError as e: return False, e def simulate_build_process(commands): for cmd in commands: if cmd.startswith...
magicoder
python
You are tasked with implementing a multi-threaded arithmetic expression evaluator using the provided `pi` function and the auxiliary functions `set_print` and `set_num_threads`. The `pi` function takes an integer arithmetic expression as a string and returns the result as a string. The `set_print` function is used to e...
```cpp #include <iostream> #include <string> #include <mutex> #include <thread> class ArithmeticEvaluator { public: ArithmeticEvaluator(int max_x) : max_x_(max_x) {} std::string evaluate(const std::string& expr) { std::lock_guard<std::mutex> lock(mutex_); set_print(is_print_); set_num_...
magicoder
cpp
You are tasked with implementing a custom base58 encoding function in JavaScript. Base58 encoding is commonly used in cryptocurrency addresses and other applications where a compact human-readable representation of large numbers is required. The base58 encoding scheme is similar to base64 encoding but excludes characte...
```javascript function createSs58(input, CUSTOM_ENDPOINT_KEY) { const base58Chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; const base = base58Chars.length; let result = ''; while (input >= 1) { result = base58Chars.charAt(input % base) + result; input = Math.floor(input / base); ...
magicoder
javascript
You are tasked with implementing a class hierarchy for handling HTTP response sources. The provided code snippet is a part of a C++ program that defines a class `RedirectResponse` within the `HTTP::RespSource` namespace. The `RedirectResponse` class is used to represent HTTP redirect responses, with the target location...
```cpp #include <iostream> #include <string> namespace HTTP { class Response { protected: int responseCode; public: Response(int code) : responseCode(code) {} void sendResponse() { std::cout << "Response Code: " << responseCode << std::endl; } ...
magicoder
cpp
You are tasked with implementing a simple version of the classic game Pong using Rust. Pong is a two-dimensional sports game that simulates table tennis. The game involves two paddles and a ball, with the goal of each player being to score points by successfully hitting the ball past the opponent's paddle. The game con...
```rust use ggez::{Context, GameResult}; use ggez::event; use ggez::graphics::{self, Color, DrawMode, Rect}; use ggez::input::keyboard; use ggez::nalgebra as na; const WINDOW_WIDTH: f32 = 800.0; const WINDOW_HEIGHT: f32 = 600.0; const PADDLE_WIDTH: f32 = 10.0; const PADDLE_HEIGHT: f32 = 100.0; const PADDLE_SPEED: f32 ...
magicoder
rust
You are tasked with simulating the behavior of a simple computer's CPU. The computer has a memory module and a CPU module. The CPU module contains registers and can execute instructions stored in memory. Your goal is to implement a method for the CPU to execute the BRK (Break) instruction. The BRK instruction is a one...
```python class Memory: def __init__(self, size): self.size = size self.data = [0] * size def write(self, address, value): self.data[address] = value def read(self, address): return self.data[address] class CPU: def __init__(self, memory): self.memory = memory ...
magicoder
python
You are tasked with implementing a conditional generative adversarial network (CGAN) for generating images based on class labels. The provided code snippet is a part of the training process for the CGAN. The discriminator (`D`) is trained to distinguish between real and fake images, while the generator (`G`) is trained...
```python import torch import torch.nn as nn # Function to create one-hot embedding of class labels def one_hot_embedding(label, num_classes): return torch.eye(num_classes)[label].to(label.device) # Generator function G class Generator(nn.Module): def __init__(self, input_size, output_size): super(Gen...
magicoder
python
You are tasked with implementing a function that verifies the resharing dealing process in a distributed key generation (DKG) protocol. The DKG protocol is used to generate a shared public key among a group of participants, and the resharing dealing process involves updating the shared public key when new participants ...
```rust use crate::error::{DkgVerifyReshareDealingError, MalformedDataError, AlgorithmId, PublicKeyBytes}; fn verify_reshare_dealing( resharing_public_coefficients: Vec<PublicKeyBytes>, dealer_index: usize, ) -> Result<(), DkgVerifyReshareDealingError> { let reshared_individual_public_key = individual_publ...
magicoder
rust
You are tasked with implementing a simple online learning algorithm for a binary classification problem. The algorithm uses stochastic gradient descent to update the model parameters and minimize the loss function. However, the code snippet provided contains some commented-out lines and an incomplete implementation. Yo...
```python import numpy as np # Initialize model parameters # For example, initialize weights and bias weights = np.zeros(num_features) # Initialize weights to zeros bias = 0 # Initialize bias to zero # Run algorithm for T time steps for t in range(T): # Sample a data point (x, y) from the dataset x, y = sam...
magicoder
python
You are tasked with implementing a trait system for a role-playing game. Traits are characteristics that define a character's abilities and behavior. Each trait has a type and a value associated with it. Traits can be added, removed, and their values can be modified. Your task is to create a trait system using Swift an...
```swift enum TraitType { case boldness static var all: [TraitType] { return [.boldness] } } struct Trait { let type: TraitType var value: Int init(type: TraitType, value: Int) { self.type = type self.value = value } mutating func increaseValue(by amount: Int)...
magicoder
swift
You are tasked with creating a program that detects a specific template image within a live video feed. The template image is loaded from a file, and the program continuously captures frames from the video feed to search for occurrences of the template. The program should terminate when the user presses the 'q' key. Y...
```python import cv2 # Load the template image template = cv2.imread('images/hazard.png', 0) w, h = template.shape[::-1] # Initialize the video capture capture = cv2.VideoCapture(0) # Assuming the camera is the video source while True: if cv2.waitKey(100) & 0xFF == ord('q'): # Press 'q' to quit cv2.des...
magicoder
python
You are tasked with creating a script to automate the tagging and pushing of Docker images to a remote repository. The provided code snippet is a function `tag_and_push` written in Bash, which takes two parameters: `source` and `target`. The function tags the Docker image specified by `source` with the name `target` an...
```bash #!/bin/bash tag_and_push () { local source=$1 local target=$2 # Base image echo "Pushing ${target} image ..." docker tag ${source} ${target} docker push ${target} } # Define an array of Docker image names images=("myapp:latest" "nginx:stable" "postgres:12") # Iterate through the array and tag/push eac...
magicoder
shell
You are tasked with implementing a function to serialize a given string into a specific format, ensuring that the serialized data does not exceed a specified length. The function should handle the conversion of the string into bytes using a specified encoding, and it should pad the serialized data if necessary to meet ...
```swift extension ID3v1 { static func serialize(tag: String, using encoding: String.Encoding, length: Int) -> Data? { guard let data = tag.data(using: encoding) else { return nil // Return nil if serialization fails } if data.count > length { // Truncate th...
magicoder
swift
You are given a set of coordinates representing points on a 2D plane. Your task is to find the minimum area of a rectangle that can be formed by selecting four distinct points from the given set of coordinates. You are to implement a function `min_rectangle_area(coordinates)` that takes in a list of tuples, where each...
```python def min_rectangle_area(coordinates): minx = float('inf') maxx = float('-inf') miny = float('inf') maxy = float('-inf') minarea = [] for i in range(len(coordinates)): newpx, newpy = coordinates[i] minx = min(minx, newpx) maxx = max(maxx, newpx) miny = mi...
magicoder
python
You are tasked with implementing a simple command-line interpreter that reads commands from the standard input and executes them. Each command is a string of characters, and the interpreter should parse the command into individual arguments and execute the corresponding action. The command-line interpreter should conti...
```c #include <stdio.h> #include <string.h> int get_args_list(const char* command, char* arg_list[]) { int arg_count = 0; const char* delimiters = " \n"; char* token = strtok((char*)command, delimiters); while (token != NULL && arg_count < 128) { if (token[0] == '"') { // Argument ...
magicoder
c
You are tasked with implementing a smart contract for a blockchain-based token system. The contract should include a method for transferring tokens between addresses. The code snippet provided is a part of the transfer function, which is responsible for transferring a specified amount of tokens from the sender's addres...
```rust // Smart contract implementation for token transfer function struct TokenContract { balances: HashMap<Address, u32>, // Mapping of addresses to token balances } impl TokenContract { // Transfer tokens from sender to recipient fn transfer(&mut self, sender: Address, recipient: Address, amount: u32, ...
magicoder
rust
You are tasked with implementing a Python function that processes a dictionary containing musical pitch intervals and returns a new dictionary with the intervals converted to semitones. The input dictionary will have keys representing musical chord types (e.g., "", "m") and values representing the pitch intervals for c...
```python def convert_intervals_to_semitones(intervals: dict) -> dict: semitone_intervals = {} for chord_type, pitch_intervals in intervals.items(): semitones = sum(pitch_intervals) semitone_intervals[chord_type] = semitones return semitone_intervals ``` The `convert_intervals_to_semitones`...
magicoder
python
You are given a set of retrieved documents represented by their document IDs. Your task is to write a function that takes this set of document IDs as input and returns the smallest positive integer that is not present in the set. For example, given the set of retrieved documents: ``` retrieved_documents = {100, 3022, ...
```python def find_smallest_missing_integer(retrieved_documents: set) -> int: smallest_missing = 1 while smallest_missing in retrieved_documents: smallest_missing += 1 return smallest_missing ``` The `find_smallest_missing_integer` function iterates through positive integers starting from 1 until i...
magicoder
python
You are tasked with implementing a function that extracts the video ID from a given video.dtu.dk link. The video ID is the unique identifier for a specific video hosted on the video.dtu.dk platform. The function should take a video.dtu.dk link as input and return the extracted video ID. Additionally, the function shoul...
```python import re def extract_video_id(video_url: str) -> str: # Regular expression pattern to match the video ID pattern = r'/(\w+)$' # Validate the input URL format assert video_url.startswith("https://video.dtu.dk/"), "Invalid video.dtu.dk URL" # Extract the video ID using the regula...
magicoder
python
You are tasked with creating a script to automate the setup of a development environment using RVM (Ruby Version Manager). Your script should ensure that the temporary directory is set, create a new directory within it, switch to that directory, install Ruby version 2.3.4 using RVM, and then list the installed Ruby ver...
```bash #!/bin/bash # Set TMPDIR environment variable to /tmp if not already set export TMPDIR=${TMPDIR:-/tmp} # Create a new directory named "test-remote" within TMPDIR d="$TMPDIR/test-remote" mkdir -p "$d" # Change the current working directory to the "test-remote" directory pushd "$d" || { echo "Error: Unable to ...
magicoder
shell
You are tasked with creating a Python function that interacts with a SQLite database. Your function should perform the following tasks: 1. Check if a database file exists at a given path. 2. If the database file exists, establish a connection to the database using the sqlite3 module. 3. If the database file does not ex...
```python import sqlite3 from os.path import isfile def connect_to_database(path: str) -> sqlite3.Connection: """ Check if a database file exists at the given path. If it exists, establish a connection to the database. If it does not exist, create a new database file at the given path and then establish a ...
magicoder
python
You are tasked with creating a program that analyzes the dependencies of a Swift package and identifies any circular dependencies present. A circular dependency occurs when two or more packages depend on each other directly or indirectly, forming a loop in the dependency graph. Your task is to implement a function `fi...
```swift func findCircularDependencies(_ dependencies: [String: [String]]) -> [[String]] { var visited = Set<String>() var inProgress = Set<String>() var circularDeps: [[String]] = [] func dfs(_ package: String, _ path: [String]) { visited.insert(package) inProgress.insert(package) ...
magicoder
swift
You are given a Python code snippet that aims to create a square matrix and fill it with numbers in a specific pattern. Your task is to complete the code by implementing the logic for filling the square matrix with numbers in a spiral pattern. The input number `INPUT_NUMBER` will determine the size of the square matrix...
```python from math import ceil, sqrt def part1(INPUT_NUMBER): def steps_from_center(): steps = 1 while True: for _ in range(2): yield (0, 1) # right for _ in range(steps): yield (1, 0) # down yield (0, -1) # left ...
magicoder
python
You are tasked with creating a Python function that securely stores an API key and provides a way to access it without exposing the key in the code. Your function should allow the key to be set once and then accessed as needed. Additionally, the function should prevent the key from being overwritten once it has been se...
```python class ApiKeyManager: def __init__(self): self.__api_key = None def set_key(self, key): if self.__api_key is None: self.__api_key = key else: print("Key already set!") def get_key(self): return self.__api_key ``` The `ApiKeyManager` class us...
magicoder
python
You are tasked with implementing a custom validation feature for a Java Swing application. The application uses a `JLayer` component to display various `JComponent` instances, such as text fields, buttons, and labels. Your goal is to create a validation mechanism that visually indicates errors on specific components. ...
```java import javax.swing.*; import javax.swing.plaf.LayerUI; import java.awt.*; public class ValidationUI extends AbstractLayerUI<JComponent> { @Override public void paint(Graphics g, JComponent c) { super.paint(g, c); // Add custom painting for validation indicators, if needed } @O...
magicoder
java
You are given a code snippet that represents a breadth-first search (BFS) algorithm. The code snippet uses an adjacency list representation of a graph and a queue data structure to perform the BFS traversal. The `dist` array is used to store the distance of each vertex from the source vertex, and the `Q` array is used ...
```java public int[] bfs(int[][] e, int s) { int n = e.length; int[] dist = new int[n]; boolean[] visited = new boolean[n]; int[] Q = new int[n]; int frontI = 0, backI = 0; Q[backI++] = s; visited[s] = true; while (frontI < backI) { int v = Q[frontI++]; for (int i = 1; ...
magicoder
java
You are working on a bioinformatics project and need to implement a filtering algorithm for DNA sequence reads. The provided code snippet is part of a larger program that processes DNA sequence data. The `MapqFilter` class is responsible for tagging BSSeqPileupRead objects with a mapq fail flag based on their mapping q...
```python class MapqFilter(Visitor): """Tag BSSeqPileupRead with mapq fail flag Adds mapq_fail flag to BSSeqPileupRead.qflag if BSSeqPileupRead mapping quality is < min_mapq parameter """ def __init__(self, config: ConfigDict) -> None: self.min_mapq = config['basic_quality_filtering']['min_...
magicoder
python