query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with implementing a Python class that interacts with a database using the Django framework. Your task is to complete the `cmdbDao` class by adding methods to perform CRUD (Create, Read, Update, Delete) operations on a specific database table. The `cmdbDao` class should have the following methods: 1. `cr...
```python from django.db import connection class cmdbDao(object): def __init__(self, table_name): self.table_name = table_name def create_record(self, record_data): with connection.cursor() as cursor: fields = ', '.join(record_data.keys()) values = ', '.join(['%s'] * le...
magicoder
python
You are working on a project that involves processing image data for a pose detection system. The code snippet provided initializes an image data generator and loads data from CSV files containing joint coordinates for training and testing. The training and testing images are located in the directories specified by `tr...
```python def generate_augmented_data(generator, train_df, test_df, train_img_dir, test_img_dir): train_images = [] train_joints = [] for index, row in train_df.iterrows(): img_path = os.path.join(train_img_dir, row[0]) img = cv2.imread(img_path) img = cv2.cvtColor(img, cv2.COLOR_BG...
magicoder
python
You are given a code snippet that involves the use of the `Bls12` engine to work with elements `g1` and `g2`. The code snippet also includes commented-out assertions to verify that `g1` and `g2` are not trivial elements. Your task is to write a function that performs these verifications and returns a boolean value indi...
```rust use pairing::bls12_381::{Bls12, G1, G2, Fr}; use pairing::Engine; fn verify_non_trivial(g1: G1, g2: G2) -> bool { let zero_g1 = G1::zero(); let one_g1 = G1::one(); let zero_g2 = G2::zero(); let one_g2 = G2::one(); g1 != zero_g1 && g1 != one_g1 && g2 != zero_g2 && g2 != one_g2 } fn main() ...
magicoder
rust
You are tasked with implementing a C++ class that provides a non-null pointer type, similar to the `not_null` type used in the code snippet below. The `not_null` type ensures that the pointer it wraps is never null, providing a safer alternative to raw pointers. Your task is to create a class `NotNullPtr` that encapsu...
```cpp #include <iostream> #include <stdexcept> template <typename T> class NotNullPtr { public: explicit NotNullPtr(T* ptr) : ptr_(ptr) { if (ptr_ == nullptr) { throw std::invalid_argument("Pointer cannot be null"); } } T& operator*() const { return *ptr_; } T...
magicoder
cpp
You are tasked with creating a Python program that processes a list of strings representing metadata for Python packages. Each string contains information about the programming language compatibility and the topic of the package. Your task is to extract and categorize this information to provide a summary of the progra...
```python from typing import List, Dict, Tuple def process_metadata(metadata_list: List[str]) -> Tuple[Dict[str, int], Dict[str, int]]: programming_language_counts = {} topic_counts = {} for metadata in metadata_list: category, value = metadata.split(' :: ') if category.startswith('Program...
magicoder
python
You are tasked with creating a script to automate the training of a computer vision model using different learning rates and weight decay values. The script should iterate through a set of learning rates and execute the training process for each combination of learning rate and weight decay. Your task is to write a Py...
```python def generate_training_commands(learning_rates, weight_decays, config_file, num_epochs): commands = [] for lr in learning_rates: for wd in weight_decays: command = f"./tools/dist_train.sh {config_file} 4 " \ f"--options optimizer.lr={lr} optimizer.weight_decay=...
magicoder
python
You are given a 2D grid representing a map with obstacles and open spaces. The goal is to calculate the distance of each open space cell in the grid from a given position `pos` and store the distances in a new 2D array. The distance is calculated as the number of steps required to move from the given position `pos` to ...
```python import numpy as np def calculate_distances(grid, pos): row_of_distance_table = np.empty((len(grid), len(grid[0])) row_of_distance_table[:] = np.NaN for x in range(len(grid)): for y in range(len(grid[0])): if grid[x][y] == 0 and (pos[0]+1 == x and pos[1] == y or pos[0]-1 =...
magicoder
python
You are tasked with implementing a class that simulates a simple ticker. The ticker can be in one of two states: "run" or "stop". The class should have methods to start, stop, and resume the ticker. When the ticker is running, it should execute a given function at regular intervals. However, when it is stopped, it shou...
```python import time import threading class Ticker: def __init__(self): self.run_status = "stop" self.func = None self.interval = None self.thread = None def ticker_function(self): while self.run_status == "run": self.func() time.sleep(self.inte...
magicoder
python
You are tasked with creating a ride-sharing application that utilizes Angular for the front-end and interacts with various services. The application includes a component for displaying a list of available rides and a map component for visualizing ride locations. The code snippet provided is a part of the Angular module...
```typescript // RideService implementation import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import { Ride } from '../models/ride'; @Injectable({ providedIn: 'root' }) export class RideService { private apiUrl = 'http://backend-api.co...
magicoder
typescript
You are tasked with implementing a simplified version of a remote procedure call (RPC) framework in C++. The RPC framework will consist of a server and a client, and will allow the client to remotely call functions on the server. Your task is to implement the server side of the RPC framework. The server will expose a ...
```cpp #include <iostream> #include <vector> #include <functional> #include <thread> #include <mutex> #include <condition_variable> #include <queue> class RpcServer { public: void initializeRpcThreadpool(int numThreads) { configureRpcThreadpool(numThreads); } void registerRpcFunction(const std::st...
magicoder
cpp
You are tasked with creating a Python function that simulates the behavior of an asynchronous computation task retrieval system. The function should retrieve a computation task using the provided user ID and project ID. The function should be designed to handle asynchronous operations and should be implemented using th...
```python import asyncio async def get_computation_task(app, user_id, project_id): # Assuming director_v2_api.get_computation_task is an existing asynchronous function task_out = await director_v2_api.get_computation_task(app, user_id, project_id) return task_out ``` In the solution, the `get_computation_...
magicoder
python
You are tasked with creating a version control system for a software development project. Your system should support the ability to commit changes and tag specific versions of the project. You will need to implement the functionality for committing changes with a message and tagging versions with annotations. You are ...
```python class VersionControl: def __init__(self): self.commit_history = [] self.tagged_versions = [] def commit_changes(self, src, desc): self.commit_history.append((src, desc)) print(f"Changes committed - Source: {src}, Description: {desc}") def tag_version(self, src, de...
magicoder
python
You are tasked with implementing a custom sorting algorithm for a specific data structure. The data structure is defined in the header file "tsortm.hpp", and the custom exception class is defined in "thexception.hpp". Your task is to create a sorting algorithm that can handle this custom data structure and to handle an...
```cpp #include "thexception.hpp" #include "tsortm.hpp" #include <vector> #include <algorithm> // Custom sorting algorithm for CustomData objects void customSort(std::vector<CustomData>& data) { try { std::sort(data.begin(), data.end(), [](const CustomData& a, const CustomData& b) { return a.ke...
magicoder
cpp
You are working on a software tool for managing geological data related to mineral phases. The code snippet provided is a part of a script that is responsible for defining default phases and generating expandable phase configurations. Each phase consists of a name, code, and additional parameters. Your task is to impl...
```python def generate_phase_summary(default_phases): phase_summary = {} for phase_template, configurations in default_phases: phase_name = phase_template[0] % 'S' # Extract phase name from the template for parameters, code, inheritance in configurations: phase_summary[parameters['n...
magicoder
python
You are tasked with creating a Flutter plugin that retrieves the size of the device's window. The plugin should be implemented in such a way that it can be registered with the FlutterPluginRegistry and accessed from the Flutter application. Your task is to create a Flutter plugin called "WindowSizePlugin" that provide...
```dart // window_size_plugin.dart import 'package:flutter/services.dart'; class WindowSizePlugin { static const MethodChannel _channel = const MethodChannel('window_size_plugin'); static Future<Size> getWindowSize() async { final Map<dynamic, dynamic> windowSize = await _channel.invokeMethod('getWindowSize')...
magicoder
dart
You are tasked with implementing a macro for creating a specialized data structure called `Sqrid`. The `Sqrid` structure is parameterized by width, height, and the number of diagonals, and it contains various derived values based on these parameters. Your task is to complete the macro implementation to generate the `Sq...
```rust #[macro_export] macro_rules! sqrid_create { // Pattern for width, height, and number of diagonals ($width: expr, $height: expr, $diags: expr) => { $crate::Sqrid::< { $width }, { $height }, $diags, { ((($width as usize) * ($height as usize)) / 32 + ...
magicoder
rust
You are tasked with implementing a function to calculate the SvQ kernel for a given set of axes and a function. The SvQ kernel is used in the context of neutron scattering experiments to describe the scattering from a sample. The function should take the axes and a function as input and return the calculated SvQ kernel...
```python import numpy as np def SvQkernel(qxaxis, qyaxis, qzaxis, fromfunction): qx, qy, qz = np.meshgrid(qxaxis, qyaxis, qzaxis, indexing='ij') q = np.array([qx, qy, qz]) volume_element = np.prod(np.abs(np.diff(qxaxis)[0]) * np.abs(np.diff(qyaxis)[0]) * np.abs(np.diff(qzaxis)[0])) svq = np.sum(from...
magicoder
python
You are tasked with creating a Python class to manage course bookings for a training institute. The class should have a method to prioritize and book courses based on certain criteria. You need to implement the `booking_courses_by_priorities` method that takes a `browser` object as input and prioritizes and books the c...
```python class BookingCourse: def booking_courses_by_priorities(self, browser): # Get the list of available courses and their priorities from the browser courses = browser.get_available_courses() # Sort the courses based on their priorities in descending order sorted_course...
magicoder
python
You are tasked with creating a multi-threaded server application in Rust. Your goal is to implement a server that can handle multiple client connections concurrently using threads. The provided code snippet is a part of the server implementation, where a new thread is spawned to handle each incoming client connection. ...
```rust use std::net::{TcpListener, TcpStream}; use std::io::{Read, Write}; use std::thread; fn handler(mut stream: TcpStream) -> Result<(), std::io::Error> { // Read data from the client let mut buffer = [0; 1024]; let bytes_read = stream.read(&mut buffer)?; // Process the received data (example: ech...
magicoder
rust
You are working on a project that involves processing and manipulating matrices and vectors using the Rcpp library in C++. As part of this project, you need to implement a function that handles different types of numeric data and ensures conformance with specified criteria. The function also constructs missing matrices...
```cpp #include <Rcpp.h> // Define the ppjsdm namespace and its functions namespace ppjsdm { // Function to get number types and check conformance int get_number_types_and_check_conformance(int default_number_types, /* other parameters */) { // Implementation of the function // ... return number_types;...
magicoder
cpp
You are tasked with implementing a function to shift and extract specific bytes from two given 8-bit values based on certain bit patterns. The function should take two 8-bit values as input and return a tuple of two 8-bit values as output. You are given the following code snippet as a reference: ```rust assert_eq!((0...
```rust fn palette_shift_bytes(coarse_xy: u8, fine_xy: u8) -> (u8, u8) { // Extracting the palette indices based on the coarse and fine XY bits let palette_index1 = (fine_xy & 0b11) | ((coarse_xy & 0b1) << 2); let palette_index2 = ((fine_xy >> 2) & 0b11) | ((coarse_xy & 0b10) << 1); // Shifting the pal...
magicoder
rust
You are tasked with creating a program to split a given dataset into training and testing sets based on the configuration provided. The configuration includes parameters such as the test size and random state for the split. The program should read the configuration and split the dataset accordingly. Additionally, the p...
```python from sklearn.model_selection import train_test_split import pandas as pd def split_dataset(dataset_path, config): # Load the dataset from the provided path dataset = pd.read_csv(dataset_path) # Split the dataset into training and testing sets X_train, X_test = train_test_split(dataset, test_...
magicoder
python
You are tasked with implementing a function to analyze a reference table and create a replacement table based on certain criteria. The reference table contains field names and data types, and the replacement table will exclude key fields and modify certain data types. The data types are represented using an enum called...
```python def _analyze_reference_table(table_obj): """ Analyzes the reference table and creates a replacement table based on certain criteria. """ _data_type_details = {"iter": "iterator"} # Sample data for _data_type_details replace_table = {} for field_name, data_type in zip(table_obj.field_...
magicoder
python
You are tasked with implementing a function that checks if a given string is a palindrome. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward, ignoring spaces, punctuation, and capitalization. For example, "A man, a plan, a canal, Panama" is a palindrome whe...
```python def is_palindrome(s): # Remove spaces and punctuation, and convert to lowercase s = ''.join(e for e in s if e.isalnum()).lower() # Check if the string is equal to its reverse return s == s[::-1] ``` The `is_palindrome` function first removes spaces and punctuation from the input string `...
magicoder
python
You are tasked with implementing a JSON-like data validation system in Rust. The system should support multiple validators and provide a way to declare standard validation rules using macros. Your task is to create a module that allows users to define custom validation rules and apply them to JSON-like data structures...
```rust // Define a module for JSON-like data validation mod json_validator { use std::collections::HashMap; // Define the Error and Result types for validation failures pub type Error = String; pub type Result<T> = std::result::Result<T, Error>; // Define a macro for declaring standard validation...
magicoder
rust
You are working on a music processing application that involves audio rendering and testing. The application uses a custom audio engine with various operations and filters. Your task is to implement a function that applies a three-pole low-pass filter to the input audio signal. You are given the following information:...
```swift func threePoleLowPassFilter(distortion: Double, cutoffFrequency: Double, resonance: Double) -> AudioSignal { // Implement the three-pole low-pass filter using the provided parameters // Return the filtered audio signal // Example implementation using a placeholder AudioSignal type let filteredA...
magicoder
swift
You are tasked with implementing a blog management system that retrieves and displays the latest blog posts along with their associated content modules. The system should retrieve the latest 5 blog posts ordered by date and then by title. Additionally, it should fetch the content modules that have no parent content mod...
```csharp public void RetrieveLatestBlogsAndModules() { using (var Context = new YourDbContext()) { if (user == null) { return; } Blogs = Context.Blogs.OrderByDescending(x => x.Date).ThenBy(x => x.Title).Take(5).ToList(); Modules = Context.ContentModules.Wher...
magicoder
csharp
You are tasked with implementing a function that takes a list of integers as input and returns a dictionary containing the frequency of each integer in the list. The function should be named `count_frequency` and should take a single parameter `nums`, which is a list of integers. The dictionary returned should have the...
```python def count_frequency(nums): frequency_dict = {} for num in nums: if num in frequency_dict: frequency_dict[num] += 1 else: frequency_dict[num] = 1 return frequency_dict if __name__ == '__main__': input_list = [1, 2, 2, 3, 3, 3] print(count_frequency(...
magicoder
python
You are tasked with implementing a simple parser for a custom language. The parser should be able to identify and report errors in the input code. The given code snippet is a part of the error-handling mechanism for the parser. It defines a custom error type `ParsingError` and throws an instance of this error when a pa...
```swift func parseCode(_ code: String) throws -> [String] { var tokens: [String] = [] var stack: [Int] = [] for (index, char) in code.enumerated() { if char == "(" { stack.append(index) } else if char == ")" { if let last = stack.popLast() { tokens.a...
magicoder
swift
You are tasked with implementing a custom routing system for a PHP web application. The system should map incoming HTTP requests to specific controller methods based on the request URL. The URL structure follows the pattern `/controller/method/parameter1/parameter2/...`. For example, a request to `/test/testFunction/12...
```php class Router { public function route($url) { $urlParts = explode('/', trim($url, '/')); $controllerName = ucfirst(array_shift($urlParts)) . 'Controller'; $methodName = array_shift($urlParts); $parameters = $urlParts; if (class_exists($controllerName)) { ...
magicoder
php
You are tasked with creating a progress tracking system for a web application using Django and Celery. The provided code snippet is a Django view function that is responsible for initiating a background task using Celery and rendering a progress bar UI to track the task's progress. Your task is to implement the backen...
```python # Import necessary modules from celery import shared_task from time import sleep # Define a Celery task to simulate a long-running process and update progress status @shared_task def progress_test_task(): # Simulate a long-running process total_iterations = 100 for i in range(total_iterations): ...
magicoder
python
You are tasked with implementing a C++ class that performs method lookup based on the type of callable object passed to its constructor. The class should have a method that returns the name of the callable type. You are given the following code snippet as a starting point: ```cpp //- CtorLookupC.node/kind callable ``...
```cpp #include <iostream> #include <type_traits> #include <functional> class CtorLookupC { public: template <typename T> CtorLookupC(T&& callable) { if constexpr (std::is_function<std::remove_pointer_t<std::decay_t<T>>>::value) { callableType = "function pointer"; } else if constex...
magicoder
cpp
You are tasked with creating a Python function to compare the performance of two different neural network models, a Convolutional Neural Network (CNN) and a Long Short-Term Memory (LSTM) network, on a given dataset. The function should take the paths to the pre-trained models and the test dataset as input and return th...
```python import numpy as np import tensorflow as tf from tensorflow.keras.models import load_model from sklearn.metrics import mean_squared_error, mean_absolute_error def test_lstm(model_path, test_data_path): # Load the pre-trained LSTM model lstm_model = load_model(model_path) # Load and preprocess the...
magicoder
python
You are tasked with implementing a custom smart pointer type, `MyBox`, which is similar to the standard library's `Box` type. Additionally, you need to implement a function, `load0`, that takes a reference to a `MyBox` containing a trait object and returns a new `MyBox` containing the same trait object. The `MyBox` ty...
```rust use std::ops::Deref; struct MyBox<T>(T); impl<T> Deref for MyBox<T> { type Target = T; fn deref(&self) -> &T { &self.0 } } fn load0(ss: &MyBox<dyn SomeTrait>) -> MyBox<dyn SomeTrait> { MyBox(*ss.0) } ``` In the solution, the `Deref` trait is implemented for the `MyBox` type, specify...
magicoder
rust
You are tasked with implementing a simple camera class in a 2D game engine. The camera class should have the ability to store its position and dimensions, and it should also provide a method to check if a given rectangle is within its view. You are given the following code snippet as a starting point: ```rust let x =...
```rust struct Camera { x: f64, y: f64, width: f64, height: f64, } impl Camera { fn new(x: f64, y: f64, width: f64, height: f64) -> Camera { Camera { x, y, width, height } } fn is_rect_within_view(&self, rect_x: f64, rect_y: f64, rect_width: f64, rect_height: f64) -> bool { ...
magicoder
rust
You are tasked with creating a Java program that utilizes Apache CXF to implement a simple web service. Your program should define a web service interface and its implementation, and then expose the service using Apache CXF. The web service should have a method that takes in a string parameter and returns a modified ve...
```java import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.ws.RequestWrapper; import javax.xml.ws.ResponseWrapper; @WebService @XmlSeeAlso({ObjectFactory.class}) public interface StringManipulatio...
magicoder
java
You are working on a software project that involves managing different aspects of a packaging system. The system has a set of constraints defined by the following constants: ``` MAX_PACKSPEC_SLOTS = 16 MAX_CONSTRUCTORS = 16 MAX_PARAM_LISTS = 16 ``` These constants represent the maximum number of slots in a packaging sp...
```python class PackagingSystem: def __init__(self): self.packaging_specs = [] self.constructors = [] self.param_lists = [] def add_packaging_spec(self, spec): if len(self.packaging_specs) < MAX_PACKSPEC_SLOTS: self.packaging_specs.append(spec) else: ...
magicoder
python
You are tasked with creating a Python program that simulates a simple game of Hangman. In this game, the player must guess letters to uncover a hidden word. The player has a limited number of attempts to guess the correct letters before the game ends. Your task is to implement the game logic and provide a user-friendly...
```python from string import ascii_letters from random import choice def select_word(): word_list = ["hangman", "python", "programming", "challenge", "solution"] return choice(word_list) def display_word(word, guessed_letters): return ''.join([letter if letter in guessed_letters else '_' for letter in wor...
magicoder
python
You are tasked with implementing a Python function that simulates a simplified version of command-line argument completion. The function will take a string representing the completion arguments and a cursor position, and it should return a list of potential completion options based on the cursor position. The function...
```python def get_completion_args(completion_args, cursor): # Truncate completion_args based on the cursor position completion_args = completion_args[:int(cursor)] # Split the completion_args into individual words cwords = completion_args.split() # Determine if the input is incomplete based on the...
magicoder
python
You are tasked with implementing a translation service that takes a string and translates it from one language to another. The translation service should also provide the option to exclude certain words from being translated. You are given a TypeScript type definition for the translation options: ```typescript type Tr...
```typescript function translate(input: string, options: TranslationOptions): string { // Default source language is English if not provided const sourceLanguage = options.from || 'en'; const targetLanguage = options.to; // Split the input string into words const words = input.split(' '); // Translate eac...
magicoder
typescript
You are tasked with implementing a class that manages the compatibility of software modules with different target platforms. The provided code snippet defines an enum `TargetPlatform` within the `TargetPlatforms` namespace, representing the possible target platforms for the software modules. The enum includes two platf...
```csharp using System; using System.Collections.Generic; using System.Collections.Concurrent; using System.Threading; namespace TargetPlatforms { public enum TargetPlatform { CLR, RRotor, } public class ModuleCompatibilityManager { private readonly ConcurrentDictionary<string, Lis...
magicoder
csharp
You are tasked with implementing a custom data structure in Swift for managing a list of TV shows. The data structure should support the ability to organize the TV shows into sections and provide a way to access and manipulate the items within each section. Your task is to create a Swift struct called `TVShowList` tha...
```swift // Define the TV show cell view model struct TVShowCellViewModel { // Properties and methods for the TV show cell view model } // Define the SectionModelType protocol protocol SectionModelType { associatedtype Item init(original: Self, items: [Item]) } // Implement the TVShowList struct struct TV...
magicoder
swift
You are tasked with implementing a command-line parser for a simple text-based game. The game has various sub-commands that the player can execute, each with its own set of parameters. Your task is to create a function that parses the input string and executes the appropriate sub-command. The input string will be in t...
```java public String executeCommand(String input) { String[] parts = input.split(" "); String command = parts[0]; if (command.equals("move")) { if (parts.length < 2) { return "Invalid command"; } String direction = parts[1]; return "Player moved " + direction; ...
magicoder
java
You are tasked with implementing a function to create a complication set for a smartwatch app. The complication set consists of various assets, each with a specific idiom, filename, and role. Your task is to write a function that takes no parameters and returns a `ComplicationSet` object containing the specified assets...
```swift func makeComplicationSet() -> ComplicationSet { let assets = [Asset(idiom: .watch, filename: "Circular.imageset", role: .circular), Asset(idiom: .watch, filename: "Extra Large.imageset", role: .extraLarge), Asset(idiom: .watch, filename: "Graphic Bezel.imageset", role: ....
magicoder
swift
You are tasked with designing a transaction processing system for a blockchain network that consists of multiple shards. Each shard is responsible for processing transactions involving specific sets of addresses. The code snippet provided is a part of the transaction processing logic and contains a function to handle t...
```python def process_out_of_shard_transaction(transaction, shard_id): print("Processing tx in shard:", shard_id) if transaction.sender in config.SHARDS_CONFIG[shard_id]['ADDRESSES'] or transaction.sender == config.MAGIC_ADDRESS: if transaction.to in config.SHARDS_CONFIG[shard_id]['ADDRESSES']: ...
magicoder
python
You are tasked with implementing a function that checks for duplicate file names in a package manifest. The package manifest is represented as a dictionary called `packageManifest`, where the "Loose" key contains a dictionary of file names. The function should take two parameters: `packageManifest` (the package manifes...
```python def check_for_duplicate_file(packageManifest, relativeSourceFilePath): sourceFileDuplicate = False # Initialize the flag for duplicate file for entryFileName in packageManifest["Loose"].keys(): # Iterate through the file names in the "Loose" section if entryFileName.lower() == relativeSourc...
magicoder
python
You are tasked with implementing a Python function that performs a specific transformation on a given multi-dimensional array. The transformation involves reshaping the array and inserting a new axis at a specified position. The function should handle various error cases and raise appropriate exceptions when necessary....
```python import numpy as np def perform_transformation(array, axis): if not isinstance(array, list) or not all(isinstance(sublist, list) for sublist in array): raise ValueError("Input array must be multi-dimensional") array_np = np.array(array, dtype=np.int32) array_shape = array_np.shape if...
magicoder
python
You are tasked with creating a custom Eloquent model in a Laravel application. The model should represent a messaging system and be capable of interacting with a corresponding database table. Your goal is to define the model class with the necessary attributes and relationships to ensure seamless integration with the d...
```php use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Ujumbe extends Model { use HasFactory; protected $fillable = ['sender_id', 'recipient_id', 'content']; public function sender() { return $this->belongsTo(User::class, 'sender_id'); ...
magicoder
php
You are tasked with implementing a simple interactive graph visualization tool. The tool should allow users to show/hide nodes by pressing UP/DOWN keys and restore an edge by pressing ENTER after selecting two nodes. You are given a graph data structure represented as a list of nodes and a list of edges. Each node is ...
```python import networkx as nx import matplotlib.pyplot as plt import keyboard def interactive_graph_visualization(nodes, edges): G = nx.Graph() G.add_nodes_from(nodes) G.add_edges_from(edges) pos = nx.spring_layout(G) nx.draw(G, pos, with_labels=True, node_color='lightblue', node_size=1500, fon...
magicoder
python
You are tasked with creating a program that reads a configuration file and replaces placeholders with corresponding environment variable values. The placeholders are represented as `${ENV_VAR_NAME}` in the configuration file, where `ENV_VAR_NAME` is the name of the environment variable. Your task is to implement a func...
```rust use regex::Regex; use std::env; fn replace_placeholders(config_content: &str) -> Result<String, ConfigError> { let re = Regex::new(r"\$\{([^}]+)\}").map_err(|e| ConfigError::RegexError(e.to_string()))?; let replaced_content = re.replace_all(config_content, |caps: &regex::Captures| { let env_var...
magicoder
rust
You are given a Python module named `tests` which contains a function `run_test` that takes two arguments: a list of integers `nums` and an integer `target`. The function is designed to find two numbers in the list `nums` that add up to the `target` and return their indices as a tuple. If no such pair exists, it return...
```python from typing import List, Optional, Tuple import tests def find_pair_indices(nums: List[int], target: int) -> Optional[Tuple[int, int]]: for i in range(len(nums)): complement = target - nums[i] complement_index = tests.run_test(nums[i+1:], complement) if complement_index is not Non...
magicoder
python
You are tasked with developing a command-line interface (CLI) for a testing framework using Python's `argparse` module. The CLI should support various options for configuring the testing environment. Your task is to implement the CLI with the following requirements: 1. The CLI should accept the following command-line ...
```python import argparse def main(): parser = argparse.ArgumentParser(description='CLI for testing framework configuration') parser.add_argument('--docker-base-name', default='TFS_DOCKER_BASE_NAME', help='Base name for Docker images') parser.add_argument('--framework-version', required=True, help='Version...
magicoder
python
You are tasked with implementing a graph-based algorithm to identify the most influential nodes in a given dataset. The dataset consists of three graphs named 'cora', 'citeseer', and 'pubmed', stored in pickle files. Each graph contains information about the original graph, edge-to-index mapping, and a matrix H. Your g...
```python import networkx as nx def find_top_influential_nodes(dataset, k): test_graph = dataset['original_graph'] G = nx.from_scipy_sparse_matrix(test_graph) # Convert the sparse matrix to a NetworkX graph centrality_scores = nx.eigenvector_centrality_numpy(G) # Calculate eigenvector centrality scores ...
magicoder
python
You are working on a file storage system that involves creating and saving space properties to a JSON file. Your task is to implement a Python class method that handles the creation and saving of space properties to a file. The code snippet provided gives a glimpse of the existing implementation. You are given a Pytho...
```python import os import json import time class SpaceManager: def __init__(self, space_id, client): self.space_id = space_id self.client = client self.mtime = int(time.time()) def get_all_properties(self): # Implementation of get_all_properties method pass def sa...
magicoder
python
You are tasked with creating a Python function that validates the metadata attributes of a given package. The function should take the package name as input and check for the presence and type of specific metadata attributes. The metadata attributes to be validated are "author", "contact", "license", and "version". The...
```python import importlib def validate_metadata(package_name: str) -> bool: try: package = importlib.import_module(package_name) metadata_attributes = ["author", "contact", "license", "version"] for attr in metadata_attributes: real_attr = f"__{attr}__" if not hasat...
magicoder
python
You are given a list of airline tickets represented as pairs of departure and arrival airports. Your task is to write a function to reconstruct the itinerary in order, starting from the departure airport "JFK". It is guaranteed that the input list of tickets forms a valid itinerary. The function signature is as follow...
```python from collections import defaultdict def findItinerary(tickets): ticket = defaultdict(list) for fr, to in tickets: ticket[fr].append(to) for k in ticket.keys(): ticket[k].sort(reverse=True) ans = [] def dfs(f, ans): while len(ticket[f]) != 0: dfs(ticke...
magicoder
python
You are tasked with implementing a service for managing stock information in an e-commerce application. The application uses Angular for the front-end and relies on Ionic for mobile app development. The given code snippet is a part of the Angular module configuration for the stock management feature. Your task is to c...
```typescript import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import { StockItem } from './stock-item.model'; @Injectable({ providedIn: 'root' }) export class StockMySuffixService { private apiUrl = 'https://example.com/api/stock'; /...
magicoder
typescript
You are given a code snippet that appears to be incomplete. Your task is to identify the missing part of the code and complete it to form a valid HTTP request. The given code snippet is as follows: ``` POST } ``` Complete the code snippet to form a valid HTTP request. Your completed code should include the necess...
The completed code snippet for a valid HTTP POST request, including the request URL, headers, and request body, is as follows: ```python import requests import json url = "https://api.example.com/endpoint" # Replace with the actual API endpoint URL headers = { "Content-Type": "application/json", "Authorizat...
magicoder
python
You are tasked with creating a script to automate the process of SSH-ing into an AWS Cloud Desktop. The script should handle the necessary authentication steps and initiate the SSH connection to the Cloud Desktop. Your task is to write a Bash script that accomplishes this automation. Your script should perform the fol...
```bash #!/bin/bash # Function to handle errors and exit handle_error() { echo "Error: $1" >&2 exit 1 } # Obtain Kerberos credentials kinit || handle_error "Failed to obtain Kerberos credentials" # Initialize Multi-Factor Authentication mwinit --aea || handle_error "Failed to initialize Multi-Factor Authenticati...
magicoder
shell
You are tasked with implementing a neural network model using PyTorch to perform a binary classification task. The given code snippet is a part of the neural network model, and your task is to complete the implementation by defining the missing components. You are provided with a partial implementation of a PyTorch ne...
```python import torch import torch.nn as nn import torch.nn.functional as F class BinaryClassificationModel(nn.Module): def __init__(self, input_dim, hidden_dim, out_dim): super(BinaryClassificationModel, self).__init__() self.linear_h = nn.Linear(input_dim, hidden_dim) self.linear_out = n...
magicoder
python
You are tasked with implementing a function to process and analyze relaxation magnetic field data obtained from an Inversion Laplace Transform (ILT) experiment. The function takes in several input parameters, including an array of explored relaxation magnetic fields, R1 values for which the ILT was performed, a regular...
```python import numpy as np def process_relaxation_data(R1, ILT_results, regularization_param, mask=None, best_fit=None): # Apply regularization parameter to ILT results processed_data = ILT_results * regularization_param # Apply mask if provided if mask is not None: processed_data = proc...
magicoder
python
You are tasked with implementing a function that performs graph queries using different types of graph structures. The function takes in entity and predicate embeddings, a set of queries, a scoring function, and other parameters based on the graph type. The graph types include "3p", "2i", and "1p". The function then us...
```python def perform_graph_query(graph_type, entity_embeddings, predicate_embeddings, queries, scoring_function, k, t_norm): if graph_type == "3p": scores = query_3p(entity_embeddings, predicate_embeddings, queries, scoring_function, k, t_norm) elif graph_type == "2i": scores = query_2i(entity_...
magicoder
python
You are tasked with implementing a class for representing a flat surface in 3D space. The class should calculate the normal vector and the distance from the origin to the flat surface based on three input points in 3D space. You are given the following code snippet as a starting point: ```csharp public class Flat { ...
```csharp public class Float3 { public float X { get; } public float Y { get; } public float Z { get; } public Float3(float x, float y, float z) { X = x; Y = y; Z = z; } public static Float3 Cross(Float3 u, Float3 v) { return new Float3(u.Y * v.Z - u.Z *...
magicoder
csharp
You are tasked with implementing a custom FunctorWithIndex type in TypeScript. A FunctorWithIndex is a type that extends the Functor type by adding an index to the map function. The mapWithIndex function takes a mapping function that also receives the index of the element being mapped. Your goal is to create a type tha...
```typescript type Functor<F> = { map: <A, B>(f: (a: A) => B) => (fa: F) => F; }; type FunctorWithIndex<F> = Functor<F> & { mapWithIndex: <A, B>(f: (i: number, a: A) => B) => (fa: F) => F; }; // Implementation of FunctorWithIndex type and mapWithIndex function type ArrayWithIndex = FunctorWithIndex<Array<any>>; ...
magicoder
typescript
You are tasked with creating a program that performs part-of-speech tagging and named entity recognition on a given text file using the LTP (Language Technology Platform) library. The LTP library provides tools for natural language processing tasks such as word segmentation, part-of-speech tagging, named entity recogni...
```python # Import necessary libraries import os from pyltp import Postagger, NamedEntityRecognizer # Initialize LTP data directory LTP_DATA_DIR = 'path_to_ltp_data_directory' # Initialize LTP models for part-of-speech tagging and named entity recognition postagger = Postagger() # Initialize part-of-speech tagger po...
magicoder
python
You are tasked with creating a Python class that simulates an embedded server and a client for a database system. The server runs a Lua script and the client interacts with the server to perform database operations. Your task is to implement the necessary classes and methods to achieve this functionality. Your Python ...
```python import os class EmbeddedServer: def __init__(self, database, server_args, quiet): self.database = database self.server_args = server_args self.quiet = quiet self.client = DatabaseClient(self) def run(self): # Start the server with the specified database and se...
magicoder
python
You are tasked with creating a Python function that processes expense data from a database and calculates the total expenses for each year. The given code snippet is part of a larger program that interacts with a database using SQLAlchemy. The `Expenses` table has columns `date` and `value`, where `date` is in the form...
```python from sqlalchemy import func def calculate_yearly_expenses(session): yearly_expenses = {} # Query to calculate total expenses for each year year_query = session.query(func.substr(Expenses.date, 1, 4).label('year'), func.sum(Expenses.value).label('value_sum')) \ ...
magicoder
python
You are tasked with implementing a macro in Rust that generates a component set for a game engine. The macro `impl_component_set!` takes a variable number of tuples as input, where each tuple consists of a component name and its corresponding index. The macro should generate a set of components with their respective in...
```rust macro_rules! impl_component_set { () => { // Base case for no components }; (($comp:ident, $index:expr), $($rest:tt)*) => { pub struct $comp; impl Component for $comp { type Storage = VecStorage<Self>; } impl_component_set!($($rest)*); }; } //...
magicoder
rust
You are tasked with creating a Python class that will handle filtering and processing of data based on specific criteria. The class should be able to store and manage filters for different data sets. Each filter will consist of a set of words and an active flag indicating whether the filter is currently active or not. ...
```python from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker engine = create_engine('sqlite:///:memory:') Session = sessionmaker(bind=engine) session = Session() Base.metadata.create_all(engine) class FilterManager: def __init__(self): self.filters = [] def add_filter(self,...
magicoder
python
You are tasked with creating a Python function that scrapes and filters chess games from an online database based on certain criteria. The function should take in the type of chess game (e.g., bullet, rapid, blitz), the game rating (rated or unrated), and the chess variant (standard chess or other rules such as chess96...
```python from datetime import datetime import json import urllib.request def scrape_chess_games(game_type: str, rating: str, variant: str) -> list: supported_game_types = ['bullet', 'rapid', 'blitz'] supported_ratings = ['rated', 'unrated'] supported_variants = ['standard', 'chess960', 'oddchess'] # Add ...
magicoder
python
You are given a list of integers representing the scores of a game. The game has a special rule for scoring: if the current score is the same as the previous score, the player's total score is doubled; otherwise, the current score is added to the total score. Your task is to write a function that takes in the list of s...
```python from typing import List def calculate_total_score(scores: List[int]) -> int: total_score = 0 prev_score = None for score in scores: if score == prev_score: total_score += score * 2 else: total_score += score prev_score = score return total_score...
magicoder
python
You are tasked with implementing a depth shader for a point light in a 3D rendering engine. The provided code snippet initializes the `m_depth_shader` variable with a shader program obtained from the `core::ResourceManager` using the file "point_light_depth.glsl". Additionally, a framebuffer is mentioned, which is like...
```glsl // Vertex Shader (point_light_depth.vert) #version 330 core layout (location = 0) in vec3 aPos; uniform mat4 lightSpaceMatrix; void main() { gl_Position = lightSpaceMatrix * vec4(aPos, 1.0); } // Fragment Shader (point_light_depth.frag) #version 330 core void main() { // Depth calculation from th...
magicoder
glsl
You are tasked with creating a Python program that processes files within a specified folder and generates a report based on the file contents. The program should read all the files in the specified folder, extract relevant data, and produce a summary report. Your program should perform the following steps: 1. Read al...
```python import os if __name__ == '__main__': folder = './data/pie/' # Step 1: Read all the files in the specified folder file_contents = {} for filename in os.listdir(folder): if filename.endswith('.txt'): with open(os.path.join(folder, filename), 'r') as file: fi...
magicoder
python
You are tasked with creating a Python program that generates a custom Pygments style for syntax highlighting using the `colored_traceback` library. The `colored_traceback` library allows for customizing the appearance of Python tracebacks, making it easier to identify and debug errors. Your program should utilize the `...
```python import colored_traceback from pygments.styles import get_all_styles from pygments.styles import get_style_by_name # Create a custom Pygments style using an existing style custom_style = get_style_by_name('solarized-dark') # Apply the custom Pygments style to the traceback colored_traceback.add_hook(always=T...
magicoder
python
You are tasked with creating a Python program that utilizes the `pythran` and `beniget` libraries to perform static code analysis. Your program should read a Python source file and generate a report containing the number of defined and used variables in the code. Your program should perform the following steps: 1. Imp...
```python # Import necessary modules from pythran.passmanager import ModuleAnalysis from beniget import DefUseChains # Create a class SilentDefUseChains that inherits from DefUseChains class SilentDefUseChains(DefUseChains): # Implement necessary functionality to analyze defined and used variables def analyze_...
magicoder
python
You are tasked with creating a script to automate the management of Docker containers using a bash script. Your script should handle the scenario where a user wants to stop and remove all containers managed by a specific `docker-compose` configuration file. Write a bash script that takes a single argument representing...
```bash #!/bin/bash # Check if the correct number of arguments is provided if [ "$#" -ne 1 ]; then echo "Usage: $0 <docker-compose-file>" exit 1 fi compose_file=$1 # Check if the specified docker-compose file exists if [ ! -f "$compose_file" ]; then echo "Error: $compose_file does not exist" exit 1 f...
magicoder
shell
You are tasked with creating a Python function that generates DNS records for a given domain. The function should take in the domain name as a parameter and return a formatted DNS record string. The DNS record should include the domain name, an IP address, and a random sorting value. Your task is to implement the `gen...
```python from faker import Faker import random fake = Faker() def random_sort(): return random.randint(0, 10) def generate_dns_record(domain_name: str) -> str: ip_address = fake.ipv4() sorting_value = random_sort() return f"{domain_name}. IN A {ip_address}. ; Sorting: {sorting_value}" ```
magicoder
python
You are tasked with creating a Python function that generates a thumbnail image from a given input image. The function should take the input image file and return a thumbnail image in PNG format. You should use the Python Imaging Library (PIL) to achieve this. Write a function `generate_thumbnail` that takes the follo...
```python from PIL import Image from fastapi.responses import StreamingResponse import io def generate_thumbnail(input_image_path): # Open the input image using PIL with Image.open(input_image_path) as img: # Create a thumbnail of the input image thumbnail = img.copy() thumbnail.thumbna...
magicoder
python
You are tasked with implementing a function to calculate the propagation delay of a signal in a medium, given certain parameters. The propagation delay is determined by integrating a function over a range of values and storing the results in a list. The code snippet provided gives a partial implementation of this task,...
```python import math import scipy.integrate as integrate def drange(start, stop, step): r = start while r < stop: yield r r += step def E_z(z, M1, L1, K1): # Define the integrand function E_z based on the parameters M1, L1, and K1 # Example: return M1 * z + L1 * z + K1 def calcul...
magicoder
python
You are tasked with implementing a class that processes query strings for a web application. The class should be able to parse and extract key-value pairs from a given query string. You are given the following code snippet as a starting point: ```csharp namespace ImageProcessor.Web.Helpers { using System; pu...
```csharp using System; using System.Collections.Generic; using System.Web; namespace ImageProcessor.Web.Helpers { public class QueryStringProcessor { public Dictionary<string, string> ParseQueryString(string queryString) { var parsedQuery = new Dictionary<string, string>(); ...
magicoder
csharp
You are working on a computer vision project that involves implementing a custom loss function for training a neural network to perform object detection. The loss function involves calculating the triplet loss, which compares the similarity between an anchor, a positive sample, and a negative sample. In this scenario, ...
```python import tensorflow as tf def triplet_loss(anchor, positive, negative, margin): """ Calculates the triplet loss for training a neural network for object detection. Args: anchor: Tensor representing the anchor samples. positive: Tensor representing the positive samples. negative: Tensor...
magicoder
python
You are tasked with implementing a thread-safe atomic update function using C++11 atomic operations. The function should update a shared variable `barrier_ts_` with the value of `base_ts` if `base_ts` is not less than 0. If `base_ts` is less than 0, the function should return `OB_INVALID_ARGUMENT` and log a warning mes...
```cpp #include <atomic> int atomic_update(std::atomic<int>& barrier_ts_, int base_ts) { int ret = 0; if (base_ts < 0) { ret = OB_INVALID_ARGUMENT; TRANS_LOG(WARN, "invalid argument", KR(ret), K(base_ts)); } else { int expected = barrier_ts_.load(); while (!barrier_ts_.compa...
magicoder
cpp
You are tasked with implementing a function that converts a UUID (Universally Unique Identifier) to an XPC (Cross-Platform Communication) object. The given code snippet provides a starting point for this task. The `CFUUIDGetUUIDBytes` function is used to obtain the bytes of the UUID, which are then mapped to an array c...
```swift public func toXPCObject() -> xpc_object_t? { let bytes = CFUUIDGetUUIDBytes(self) let uuid = [ bytes.byte0, bytes.byte1, bytes.byte2, bytes.byte3, bytes.byte4, bytes.byte5, bytes.byte6, bytes.byte7, bytes.byte8, bytes.byte9, bytes.byte10, bytes.byte11, bytes.byte12, bytes.byte1...
magicoder
swift
You are tasked with creating a Python class that interacts with the Intel compiler executable and extracts its version information. Your task is to implement the `IntelCompiler` class with a method `version` that returns the version of the Intel compiler executable. The `IntelCompiler` class has the following attribut...
```python import re class IntelCompiler: def __init__(self, ctx, exe): self.ctx = ctx self.exe = exe def version(self, *args, **kwargs): """Return the version of the Intel compiler executable.""" # Simulating the execution of the Intel compiler executable # Rep...
magicoder
python
You are tasked with implementing a Python function that can dynamically create rule objects based on different factory functions. The factory functions take in keyword arguments and return rule objects with specific properties. Your goal is to create a generic function that can call these factory functions with the giv...
```python # Solution for call_with function def call_with(factory, kwargs): return factory(**kwargs) # Solution for span_rule_factory def span_rule_factory(period): class SpanRule: def __init__(self, period): self.period = period return SpanRule(period) # Solution for periodic_rule_fac...
magicoder
python
You are tasked with implementing a function to process a series of user records and perform database operations based on certain conditions. The function should take a list of user records as input and execute the following logic: 1. For each user record, attempt to insert it into the database table named "users". 2. ...
```rust use diesel::prelude::*; use diesel::dsl::insert_into; use diesel::pg::upsert::excluded; fn process_user_records(records: Vec<User>, conn: &PgConnection) { for record in records { let existing_user = users::table.filter(users::id.eq(record.id)).first::<User>(conn).optional(); match existing...
magicoder
rust
You are tasked with implementing a custom SQL query analyzer library in C#. The library should be able to parse and analyze SQL queries to extract various components such as the select clause, from clause, where clause, and order by clause. Your task is to implement the `SqlQueryAnalyzer` class with the following meth...
```csharp using System; using System.Collections.Generic; using System.Text.RegularExpressions; namespace SqlAnalyseLibrary { public class SqlQueryAnalyzer { public List<string> ParseSelectClause(string query) { string selectPattern = @"SELECT\s(.*?)\sFROM"; Match match ...
magicoder
csharp
You are tasked with creating a function that processes a list of social media feeds and generates a formatted HTML output. Each feed is represented as an associative array with the following structure: ```php $feed = [ 'id' => 123, // unique identifier for the feed 'template' => '<div class="feed-item"><h3>{tit...
```php function generateFeedHTML(array $feeds, array $pages): string { $html = '<ul>'; foreach ($feeds as $feed) { $feedHTML = strtr($feed['template'], $feed['feed_data']); $relativeTime = Yii::$app->formatter->asRelativeTime($feed['created_at']); $html .= "<li>{$feedHTML}<div class=\"cl...
magicoder
php
You are tasked with creating a Python decorator that measures the execution time of a function and logs the result. Your decorator should use the `time` module to measure the elapsed time and the `logging` module to log the result. The decorator should be registered as a plugin using the `xappt` library. Your task is ...
```python import time import logging import xappt # Define the timed_logger decorator def timed_logger(func): def wrapper(*args, **kwargs): start_time = time.time() result = func(*args, **kwargs) end_time = time.time() elapsed_time_ms = (end_time - start_time) * 1000 logging...
magicoder
python
You are tasked with creating a program that reads the contents of a file, converts the data to a hexadecimal string, and then writes this string to a new file in a specific format. Your program should perform the following steps: 1. Read the contents of a file specified by the `inputFile` path using the `FileManager` ...
```swift func convertFileToHexAndWrite(inputFile: String, outputFile: String, variableName: String) { let fileManager = FileManager.default // Step 1: Read the contents of the input file let inputData = fileManager.contents(atPath: inputFile) ?? Data() // Step 2: Convert the data to a hexadeci...
magicoder
swift
You are tasked with creating a Python program that utilizes the argparse library to parse command-line arguments for a neural network training script. The script is intended to train a neural network model using TensorFlow. The provided code snippet sets up the argument parser with various command-line arguments for co...
```python import argparse import tensorflow as tf # Define the argument parser parser = argparse.ArgumentParser(description='Neural Network Training Script') parser.add_argument('--layer2', dest='layer2', default=128, help='nodes of layer2', type=int) parser.add_argument('--noise_size', dest='noise_size', default=256,...
magicoder
python
You are tasked with implementing a cryptocurrency exchange rate retrieval system using Python's asyncio library. The provided code snippet is part of a class that handles the retrieval of exchange rates for different cryptocurrencies. Your task is to complete the implementation of the `_get_rates` method, which should ...
```python import httpx from typing import List, Tuple class CryptocurrencyExchange: def __init__(self, base_coin: str, **conf): self.base_coin = base_coin self.httpx_conf = conf if 'http2' not in self.httpx_conf: self.httpx_conf['http2'] = True if 'timeout' not in self.h...
magicoder
python
You are given a matrix represented by a 2D list of integers. Your task is to write a function that modifies the matrix in place, setting the entire row and column to 0 if any element in that row or column is 0. You need to implement the following function: ```python def setZeroes(matrix: List[List[int]]) -> None: ...
```python from typing import List def setZeroes(matrix: List[List[int]]) -> None: m, n = len(matrix), len(matrix[0]) rows, cols = set(), set() # Identify the rows and columns that need to be zeroed for i in range(m): for j in range(n): if matrix[i][j] == 0: rows.add...
magicoder
python
You are tasked with creating a Rust function that processes the response from an HTTP request and extracts specific information from it. The function should take a base URL as input and return a vector of strings containing the headers of the HTTP response. You are provided with the following code snippet as a startin...
```rust use reqwest::Url; async fn extract_headers(base_url: &Url) -> Result<Vec<String>, Box<dyn std::error::Error>> { let resp = reqwest::get(base_url.as_ref()).await?; // Perform the HTTP request let headers = resp.headers(); // Get the headers from the response // Convert the headers into a vector of ...
magicoder
rust
You are tasked with creating a Python function that processes version information for software distributions. Your function should take in a distribution name and a version modifier, and then return the modified version of the distribution. The version information is stored in a string format and follows the pattern o...
```python import re from pkg_resources import get_distribution, DistributionNotFound def modify_version(distribution_name, version_modifier): try: __version_modifier__ = r'(\g<1>)' + version_modifier + r'(\g<2>)' version = re.sub(__version_modifier__, r'\g<1>-' + version_modifier + r'-\g<2>', get_d...
magicoder
python
You are tasked with creating a performance benchmark for a custom runtime execution in a blockchain environment. The given code snippet is a part of a Rust program using the `criterion` crate for benchmarking. The `c.bench_function` is used to define a benchmark function named "execute(2, 1, 256)" which takes a closure...
```rust extern crate criterion; use criterion::{criterion_group, criterion_main, Criterion}; // Define the Runtime struct struct Runtime { binary: String, blob: Vec<u8>, pre_state: u64, } impl Runtime { // Implement a new method for creating a new Runtime instance fn new(binary: &str, blob: &[u8]...
magicoder
rust
You are tasked with implementing a data processing class that reads data from source, target, and label buffers and performs some operations on them. The class has three attributes: `source_buffer`, `target_buffer`, and `label_buffer`, which store the source data, target data, and label data, respectively. The class al...
```python class DataProcessor: def __init__(self, _sbuf, _tbuf, _lbuf): self.source_buffer = _sbuf self.target_buffer = _tbuf self.label_buffer = _lbuf self.end_of_data = True def reset(self): # Reset the state of the data processing class self.end_of_data = True...
magicoder
python
You are given a system of first-order ordinary differential equations (ODEs) represented by the following code snippet: ```python x, y = sp.Symbol('x'), sp.Symbol('y') dx = 0.707107*x + 0.707107*y dy = -0.707107*x + 0.707107*y dyns = [dx, dy] vars = [x, y] ``` Your task is to write a Python function that can numeri...
```python import sympy as sp def runge_kutta_solver(x0, y0, h, n): x, y = sp.symbols('x y') dx = 0.707107*x + 0.707107*y dy = -0.707107*x + 0.707107*y def f(x_val, y_val): return [dx.subs({x: x_val, y: y_val}), dy.subs({x: x_val, y: y_val})] x_values = [x0] y_values = [y0] for _ ...
magicoder
python
You are tasked with implementing a parameter management system for a testing framework. The system should allow users to set, retrieve, and display various parameters for test cases. You are provided with a partial code snippet that demonstrates the usage of the parameter management system. Your task is to complete the...
```cpp #include <iostream> #include <map> #include <sstream> class TestParameters { private: std::map<std::string, std::string> parameters; public: void set(const std::string& key, const std::string& value) { parameters[key] = value; } std::string getWithDefaultVal(const std::string& key, con...
magicoder
cpp
You are tasked with implementing a simplified version of a non-blocking heterogeneous queue data structure. The queue is capable of storing elements of different types and supports non-blocking operations for adding elements. Your goal is to implement the `try_start_dyn_push_move` method, which attempts to add an eleme...
```cpp #include <iostream> #include <typeinfo> #include <memory> // Define the Progress enum for non-blocking progress guarantees enum class Progress { WaitFree, LockFree, Blocking }; // Define the MyRunTimeType class to represent runtime type information class MyRunTimeType { public: template <typena...
magicoder
cpp