query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with implementing a password management system that filters and prints out specific passwords based on certain conditions. The system has a `names` field containing a list of names, a `ctx` field representing a context, and a `tree` field indicating whether to print the passwords. The `ctx` object has a ... | ```rust
use std::error::Error;
struct Context;
impl Context {
fn find_exact(&self, name: &str) -> Result<String, Box<dyn Error>> {
// Implementation of finding the password based on the name
// For example, returning a hardcoded password for demonstration purposes
match name {
... | magicoder | rust |
You are tasked with implementing a message handling system for a messaging application. The system should support adding various types of additions to messages, such as emojis, images, or files. Each addition has specific methods that can be applied to it. Your task is to design and implement a class structure in Swift... | ```swift
// Define the base Message class
class Message {
// Common properties and methods for all message types
}
// Define a protocol for addition-specific methods
protocol Addition {
func send()
func save()
func delete()
}
// Implement specific addition classes conforming to the Addition protocol
c... | magicoder | swift |
You are tasked with implementing a protocol-oriented design pattern in Swift. The goal is to create a protocol and its conforming extensions to facilitate the creation of presenter and API service instances for a characters list feature in an iOS application.
The given code snippet is a part of a test class `Character... | ```swift
// Define the CharactersListFactorable protocol
protocol CharactersListFactorable {
func makePresenter(viewController: CharactersListDisplayLogic?) -> CharactersListPresentationLogic
func makeApiService() -> APIClientProtocol
}
// Implement the protocol in the CharactersListInteractorTests class
extension... | magicoder | swift |
You are tasked with implementing a custom max reduction function for an observable stream in Python using the RxPY library. The max reduction function should operate on a stream of numeric values and emit the maximum value encountered so far. You need to create a function that takes a list of numbers as input, uses the... | ```python
import rx
import rx.operators as rs
def custom_max_reduction(source):
actual_result = []
# Create an observable stream from the input list
rx.from_(source).pipe(
# Apply the custom max reduction function
rs.math.max(reduce=True)
).subscribe(on_next=actual_result.append)
... | magicoder | python |
You are tasked with creating a Python program that takes a four-digit integer as input and then separates and prints the individual digits in the thousands, hundreds, tens, and units places.
Write a function called `print_digits` that takes an integer `number` as input and prints the digits in the following format:
``... | ```python
def print_digits(number):
if not isinstance(number, int) or number < 1000 or number > 9999:
print("Invalid input")
return
units = number % 10
dozens = number // 10 % 10
hundreds = number // 100 % 10
thousands = number // 1000 % 10
print('Unidades:', units)
print('... | magicoder | python |
You are tasked with implementing a delivery tracking system for a courier service. The system should be able to track the courier's location at specific time points and calculate the estimated arrival time at a given destination.
You are provided with a Swift code snippet that defines a `Courier` class and a variable ... | ```swift
struct Location {
let latitude: Double
let longitude: Double
}
class Courier {
var currentLocation: Location?
let destination: Location
private var locationHistory: [(timePoint: TimeIntervalMilliseconds, location: Location)] = []
init(destination: Location) {
self.destination ... | magicoder | swift |
You are tasked with implementing a function to load cards and investigators from a JSON file into a database, and then fetching a specific card from the database. The database operations are performed using the provided `AHDatabase` class and the `DatabaseTestsHelper` class. Your task is to write a function that accomp... | ```swift
func loadAndFetchCard() -> Card {
let db = AHDatabase()
do {
try db.deleteAllSavedFileChecksums()
let botaURL = Bundle(for: AHDatabase.self).url(forResource: "bota", withExtension: "json")!
try db.loadCardsAndInvestigatorsFromJSON(at: botaURL)
retu... | magicoder | swift |
You are tasked with implementing a simple event listener in Python. The `listener` function should continuously listen for user input and perform specific actions based on the input received. The program should terminate when a specific exit command is entered.
Your task is to complete the `listener` function, which s... | ```python
def listener():
while True:
user_input = input("Enter a command: ")
if user_input == "start":
print("Starting the process...")
elif user_input == "stop":
print("Stopping the process...")
elif user_input == "exit":
print("Exiting the progr... | magicoder | python |
You are tasked with implementing a watermark positioning system for an image processing application. The application has a class with the following attributes and methods:
Attributes:
- `stamp_location`: A dictionary containing the stamp positions for each image.
- `stamps`: A dictionary to store the watermark stamps.... | ```python
class ImageProcessor:
# ... (other methods and attributes)
def _position_watermark(self, image, watermark_position):
if watermark_position in self.stamp_pos_functions:
position_function = self.stamp_pos_functions[watermark_position]
position_function(image)
els... | magicoder | python |
You are tasked with implementing a custom TensorFlow layer for a neural network model. The layer, named `CustomLayer`, has a specific structure and functionality. The provided code snippet is a part of the `CustomLayer` class, and your task is to complete the implementation of this class based on the given requirements... | ```python
class CustomLayer(tf.keras.layers.Layer):
def __init__(self, act_halting_bias_init, **kwargs):
super(CustomLayer, self).__init__(**kwargs)
self.bias_initializer = tf.constant_initializer(act_halting_bias_init)
def call(self, features, initial_state, training=False, mask=None):
... | magicoder | python |
You are tasked with simulating the movement of a robotic arm in a controlled environment. The environment is represented by an `env` object, which provides methods for setting the arm's position, retrieving the positions of its tips, and executing steps. The arm's movement is controlled by the `action` variable, which ... | ```python
from typing import List, Tuple
def simulate_arm(initial_positions: List[Tuple[int, int]], actions: List[Tuple[int, int]], num_steps: int) -> List[Tuple[int, int]]:
env = Environment() # Assuming the existence of an Environment class with the required methods
# Set initial positions
for i, pos i... | magicoder | python |
You are tasked with creating a program that analyzes the frequency of words in a given text file. Your program should read a text file and output the top N most frequently occurring words along with their frequencies. The program should ignore common stop words (e.g., "the", "and", "is") and should be case-insensitive ... | ```python
import re
from collections import Counter
def topNWords(filename, N):
with open(filename, 'r') as file:
text = file.read().lower()
words = re.findall(r'\b\w+\b', text)
stop_words = {'the', 'and', 'is', 'a', 'this', 'of', 'in', 'to', 'for', 'with', 'on', 'at', 'an'}
filtere... | magicoder | python |
You are tasked with implementing a function that can parse a given date string in the format "dd/mm/yy" and return the corresponding day, month, and year as separate integers. The function should handle both single and double-digit day and month values, and should also account for the two-digit year format. If the inpu... | ```swift
func parseDate(_ dateString: String) -> (Int, Int, Int, String) {
let components = dateString.components(separatedBy: "/")
guard components.count == 3 else {
return (0, 0, 0, "Invalid date format")
}
if let day = Int(components[0]), let month = Int(components[1]), let year = I... | magicoder | swift |
You are tasked with implementing a custom web component called `context-array` that will manage an array of data and display it in a specific format. The component should support dynamic data binding and manipulation through attributes and properties.
The `context-array` component should have the following features:
-... | ```javascript
// Define the custom web component
class ContextArray extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.data = [];
this.key = '';
this.render();
}
static get observedAttributes() {
return ['data.key'];
}
attributeChangedCallback(na... | magicoder | javascript |
You are tasked with implementing a Python class that manages role data in an LDAP structure. The class should handle the retrieval and manipulation of role information using the provided code snippet as a reference.
Your task is to complete the implementation of the `RoleApi` class by incorporating the necessary data ... | ```python
class RoleDataObject:
def __init__(self, id):
self.id = id
# Add other attributes as needed
class RoleApi(RoleLdapStructureMixin, common_ldap.BaseLdap):
def __init__(self, model):
super().__init__(model)
# Additional initialization if needed
def get_role_by_id(se... | magicoder | python |
You are tasked with creating a Python script to automate the process of managing Docker containers. Your script should interact with the Docker daemon to execute commands within a specified container. Specifically, you need to implement a function that takes the container name and a command as input and then executes t... | ```python
import subprocess
def execute_command_in_container(container_name: str, command: str) -> str:
try:
# Execute the command within the specified container using the docker exec command
process = subprocess.Popen(['docker', 'exec', container_name, command], stdout=subprocess.PIPE, stderr=subp... | magicoder | python |
You are tasked with implementing a simple tree traversal algorithm using the Tree-sitter library in Swift. The given code snippet demonstrates the usage of the Tree-sitter library to navigate a tree structure. The `withUnsafeMutablePointer` function is used to safely access and manipulate the underlying memory of the `... | ```swift
import TreeSitter // Assuming the Tree-sitter library is imported
class TreeTraversal {
private var tsTreeCursor: TSTreeCursor // Assuming TSTreeCursor is the type of tsTreeCursor
init(rootNode: TSNode) {
tsTreeCursor = TSTreeCursor() // Initialize the tree cursor
ts_tree_cursor_reset... | magicoder | swift |
You are working on a project to develop a software tool for analyzing flow data from microfluidic chips. The code snippet provided is a part of the software module responsible for flow correction. The `FlowCorr` class is used to perform flow correction on the data obtained from different types of microfluidic chips.
T... | ```python
class FlowCorr:
def __init__(self, chiptype, xblock=None, yblock=None, rootdir='.', method=''):
self.chiptype = chiptype
self.xblock = xblock
self.yblock = yblock
self.rootdir = rootdir
self.method = method
def perform_correction(self, flow_data):
if se... | magicoder | python |
You are tasked with implementing a Python class that simulates a simple event input/output (I/O) system for handling event data in a particle physics experiment. The provided code snippet gives a glimpse of the operations involved in this system. Your task is to create a class `EventIO` that manages event data and prov... | ```python
class EventIO:
def __init__(self):
self.run_id_val = 0
self.subrun_id_val = 0
self.event_id_val = 0
self.current_event_data = None
self.event_sequence = [] # Assuming this is a list of event data
def construct(self, pgraph, pixel2d, hit_in):
# Logic to... | magicoder | python |
You are given a sorted array of distinct integers and a target value. Your task is to implement a function `search` to determine if the target is in the array and return its index. If the target is not found, the function should return -1. You need to implement the `search` function using a binary search algorithm.
Th... | ```python
from typing import List
def search(nums: List[int], target: int) -> int:
left, right = 0, len(nums) - 1
while left <= right:
mid = left + (right - left) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid + 1
else:
... | magicoder | python |
You are tasked with implementing a service discovery mechanism for a distributed system. Service discovery is the process of automatically detecting and locating services within a network. In this scenario, you are required to create a function that performs a GET request to a service discovery endpoint and handles pot... | ```python
import requests
import time
def service_discovery_get(service_discovery_uri, service_discovery_user, service_discovery_password, **kwargs):
max_retries = 300
retry_delay = 1 # Initial retry delay in seconds
retry_count = 0
while retry_count < max_retries:
try:
response =... | magicoder | python |
You are tasked with creating a program that processes a user's input to determine the frequency of each character in the input string. Your program should ignore case sensitivity, consider only alphabetic characters, and output the frequency of each letter in alphabetical order. For example, if the user inputs "Hello, ... | ```python
def count_character_frequency(user_input):
frequency = {}
for char in user_input:
if char.isalpha():
char = char.lower()
if char in frequency:
frequency[char] += 1
else:
frequency[char] = 1
sorted_frequency = dict(sorted(... | magicoder | python |
You are tasked with implementing a function that creates a neural machine translation (NMT) model using TensorFlow. The function `create_nmt_model` takes several parameters, including a TensorFlow session, a boolean flag `forward_only`, an optional model path, a boolean flag `use_best`, a `FLAGS` object, a list of `buc... | ```python
import tensorflow as tf
def create_nmt_model(session, forward_only, model_path=None, use_best=False, FLAGS=None, buckets=None, translate=False):
# Define the NMT model creation logic based on the provided parameters
if model_path is None:
# Create a new model with fresh parameters
pri... | magicoder | python |
You are tasked with implementing a dependency resolution algorithm for a software package management system. The system maintains a list of dependencies between different software packages, where each dependency is represented as a tuple containing the name of the dependent package and the version of the dependency. Th... | ```python
def resolve_dependencies(dependencies):
graph = {}
indegree = {}
for package, version in dependencies:
if package not in graph:
graph[package] = []
indegree[package] = 0
for i in range(1, len(dependencies)):
prev_package, prev_version = dependencies[i-1]... | magicoder | python |
You are tasked with implementing a caching mechanism for a web application using Python and SQLAlchemy. The cache should improve the performance of the application by storing frequently accessed data in memory. Your goal is to create a cache decorator that can be applied to SQLAlchemy query methods to cache their resul... | ```python
from functools import lru_cache
from collections import OrderedDict
def sqlalchemy_cache(max_size):
cache = OrderedDict()
def decorator(func):
def wrapper(*args, **kwargs):
key = (func.__name__, args, frozenset(kwargs.items()))
if key in cache:
# Move ... | magicoder | python |
You are tasked with creating a custom exception class in C# that extends the `System.Exception` class. This custom exception will be used to handle errors related to a specific database operation. Your task is to implement the custom exception class and demonstrate its usage in a sample program.
Your custom exception ... | ```csharp
using System;
namespace CustomExceptions
{
public class DatabaseOperationException : Exception
{
public DatabaseOperationException(string message) : base(message)
{
}
public DatabaseOperationException(string message, Exception innerException) : base(message, innerExce... | magicoder | csharp |
You are tasked with creating a program to calculate the break-even point and potential profit or loss from selling options in a financial trading scenario. In options trading, the break-even point is the price at which an option buyer neither makes a profit nor incurs a loss. The potential profit or loss is determined ... | ```python
def calculate_pnl(put: bool, strike: float, sell_factor: float, premium: float, price_at_expiry: float) -> (float, float):
if put:
break_even = strike - sell_factor * premium
pnl = strike - premium - price_at_expiry
else:
break_even = strike + sell_factor * premium
pnl ... | magicoder | python |
You are tasked with creating a simple logging utility for a multi-threaded application. The utility should allow different log levels to be set for different modules, and it should format log messages with timestamps. Your task is to implement the `Logger` struct and associated functions to achieve this functionality.
... | ```rust
use std::sync::{Arc, Mutex};
use std::time::{SystemTime, UNIX_EPOCH};
struct Logger {
module_levels: Arc<Mutex<Vec<(String, log::LevelFilter)>>>,
}
impl Logger {
fn new() -> Self {
Logger {
module_levels: Arc::new(Mutex::new(Vec::new())),
}
}
fn set_module_level(&s... | magicoder | rust |
You are working on a software system that deals with components and subcomponents. The code snippet provided is part of a function that manipulates these components and subcomponents. Your task is to implement a function that performs a specific operation on the components based on the given code snippet.
You are give... | ```javascript
function manipulateComponents(newComponent, activeComponent) {
newComponent.baseSubcomponent.isTemporaryAddPreview = true;
Object.assign(activeComponent.subcomponents, newComponent.subcomponents);
const { higherComponentContainer } = ActiveComponentUtils.getHigherLevelComponents(activeComponent);
... | magicoder | javascript |
You are tasked with creating a program that extracts the license information from a given source code file. The license information is typically found within comments at the beginning of the file. The license text may span multiple lines and can be preceded by any number of comment characters (e.g., #, //, /*, etc.).
... | ```python
import re
def extract_license(filename: str) -> str:
with open(filename, 'r', encoding='utf-8') as file:
content = file.read()
match = re.search(r'(?s)(?://|/\*|\#)(.*?)(?://|/\*|\#)', content)
if match:
return match.group(1).strip()
else:
return ""
```
The `extract_l... | magicoder | python |
You are tasked with implementing a Python class for calculating the covariance matrix. The class should have the following features:
- It should be initialized with a data matrix `X`, a boolean parameter `unbiased` (defaulting to `True`), and a scalar multiple `scalar_multiple` (defaulting to `1.0`).
- The class should... | The `CovarianceMatrix` class is implemented with an `__init__` method to initialize the class with the input data matrix `X`, the `unbiased` parameter, and the `scalar_multiple` parameter. The `calculate_covariance_matrix` method is added to calculate the covariance matrix based on the input data matrix `X`, considerin... | magicoder | python |
You are tasked with creating a function to handle the validation and database operation for adding a new warehouse shelf. The function should take input parameters for the maximum number of layers on the shelf and any remarks about the shelf. The function should perform the following tasks:
1. Validate the input parame... | ```php
function addWarehouseShelf($maxLayer, $remark) {
// Validate input parameters
if (empty($maxLayer)) {
errorMsg(400, '货架层数不能为空');
}
try {
// Database operation - start transaction
Db::startTrans();
// Perform database operations to add the new warehouse shelf
... | magicoder | php |
You are tasked with implementing a custom extension trait for the Rust programming language. The trait, named `TryStreamExt2`, is intended to extend the functionality of Rust's `TryStream` type. The `TryStream` type represents a stream of values that may contain errors, and the goal of the extension trait is to add a m... | ```rust
use futures::stream::{TryStream, Stream, StreamExt};
use std::pin::Pin;
pub trait TryStreamExt2: TryStream {
fn try_then<T, F>(self, f: F) -> TryThen<Self, F>
where
Self: Sized,
F: FnMut(Self::Ok) -> Result<T, Self::Error>,
{
TryThen {
stream: self,
f... | magicoder | rust |
You are tasked with implementing a multi-threaded image processing system. The system is designed to capture RGB frames from a camera and process them concurrently. The provided code snippet is a method within the system's camera class, responsible for obtaining an RGB frame. The method acquires a lock before accessing... | To address this problem, you can create a frame processing pipeline using Python's `threading` module to handle concurrent execution of multiple stages. Below is a sample solution demonstrating the implementation of the frame processing pipeline:
```python
import threading
class FrameProcessingPipeline:
def __ini... | magicoder | python |
You are tasked with implementing a Python function that processes a form containing checkboxes and text fields. The function should take in three parameters: `col2`, `checkbox_dict`, and `checked`. The `col2` parameter is a list of text strings to be placed in the second column of the form. The `checkbox_dict` paramete... | ```python
from typing import List, Union, Dict, Tuple
from collections import OrderedDict
def process_form(col2: List[str], checkbox_dict: Union[OrderedDict, Dict], checked: List[str]) -> Tuple[Dict[str, bool], Dict[str, str], Tuple[str, Dict[str, bool]]]:
checkbox_values = {key: True for key in checked}
text_... | magicoder | python |
You are given a JavaScript function that is intended to reverse a string. However, the code snippet provided is incomplete and contains some errors. Your task is to complete the function and fix any issues to ensure that it correctly reverses the input string.
The given code snippet is as follows:
```javascript
funct... | ```javascript
function reverseString(str) {
if (typeof str !== 'string') {
return "Invalid input. Please provide a valid string.";
}
if (str === "") {
return "Empty string provided.";
}
let reversed = "";
for (let i = str.length - 1; i >= 0; i--) {
reversed += str[i];
}
return reversed;
}
``... | magicoder | javascript |
You are tasked with implementing a Python class that interacts with a SQL database. The class, named `SQLQuery`, is initialized with the following parameters:
- `table_name`: a string representing the name of the SQL table to query
- `condition_str`: a string representing the SQL condition to be applied to the query
- ... | ```python
import sqlite3
class SQLQuery:
def __init__(self, table_name, condition_str, unique=False, columns=None, group=1):
self.table_name = table_name
self.condition_str = condition_str
self.unique = unique
self.columns = columns
self.group = group
def execute_query(... | magicoder | python |
You are tasked with creating a function that retrieves the user group name based on the user's group ID and the route key associated with the current action. The user's group ID is obtained from the request, and the route key is extracted from the given code snippet. You need to implement a function that uses this info... | ```php
function getUserGroupName($routeKey, $userGroupId) {
// Fetch the user group name based on the user group ID
$userGroup = UserGroup::find($userGroupId);
// Return the user group name associated with the given user group ID
return $userGroup->name;
}
``` | magicoder | php |
You are tasked with implementing a thread-safe counter class in Java. The class should provide methods for incrementing the counter value, getting the current value, and resetting the counter to zero. Additionally, the class should be designed to be used in a multi-threaded environment, ensuring that concurrent access ... | ```java
import java.util.concurrent.atomic.AtomicLong;
public class ThreadSafeCounter {
private AtomicLong counter = new AtomicLong(0);
public void increment() {
counter.incrementAndGet();
}
public long getValue() {
return counter.get();
}
public void reset() {
counte... | magicoder | java |
You are tasked with creating a dependency resolution algorithm for a package manager. The package manager uses a configuration file to define targets and their dependencies. Each target can depend on other targets within the same package or on products in packages which this package depends on.
Your task is to impleme... | ```swift
func resolveDependencies(configuration: [(name: String, dependencies: [String], isTestTarget: Bool)]) -> [String: [String]] {
var dependencyMap: [String: [String]] = [:]
for target in configuration {
dependencyMap[target.name] = target.dependencies
}
var resolvedDependencies: [String:... | magicoder | swift |
You are working on a project involving the manipulation of biological network data represented as a graph using the PyBEL library. Your task is to implement a function that adds nodes and edges to the graph based on certain conditions.
You are given a Python function snippet that partially implements the required func... | ```python
def add_nodes_and_edges_to_graph(graph, node, universe):
"""
:param pybel.BELGraph graph: The graph to add stuff to
:param node: A BEL node
"""
skip_predecessors = set()
for predecessor in universe.predecessors(node):
if predecessor in graph:
skip_predecessors.add(p... | magicoder | python |
You are given a 2D array representing a logo, where each element in the array represents a color (N for navy, G for green, and R for red). The logo is represented as a 8x8 grid. Your task is to write a function that takes this 2D array as input and returns the number of pixels that are part of the logo, i.e., the count... | ```python
from typing import List
def count_logo_pixels(logo: List[List[str]]) -> int:
count = 0
for row in logo:
for pixel in row:
if pixel != 'N':
count += 1
return count
```
The `count_logo_pixels` function iterates through each pixel in the logo and increments the c... | magicoder | python |
You are tasked with creating a Python program that generates LaTeX code for documenting modules and their contents. The program should take module names and their contents as input and produce the corresponding LaTeX code for documentation.
Your task is to implement a function `generate_latex_documentation` that takes... | ```python
import sys
class ExampleModule:
def __init__(self, name):
self.name = name
def get_input_specs(self):
return InputSpecs
class InputSpecs:
@staticmethod
def generateLatex():
return "% LaTeX code for documenting function1"
def generate_latex_documentation(module, cont... | magicoder | python |
You are tasked with implementing a frequency synthesizer for a communication system. The frequency synthesizer uses a set of configuration registers to control its operation. One of the key components of the frequency synthesizer is the RF configuration, which includes settings for the VCO (Voltage Controlled Oscillato... | To calculate the output frequency, we need to understand the impact of the RF configuration settings on the VCO frequency. The VCO frequency can be calculated using the following formula:
VCO Frequency = (Input Frequency / rfDivideBy) * (2^vcoBias) * (2^vcoInductor)
Where:
- Input Frequency: The reference frequency p... | magicoder | python |
You are given the definition for a singly-linked list node in C++:
```cpp
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
};
```
Your task is to implement a function `reverseList` that takes the head of a singly-linked list as input and returns the head of the reverse... | ```cpp
ListNode* reverseList(ListNode* head) {
ListNode* prev = nullptr;
ListNode* curr = head;
ListNode* next = nullptr;
while (curr != nullptr) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
```
The `reverseList` function i... | magicoder | cpp |
You are tasked with implementing a reinforcement learning algorithm using an actor-critic architecture. The actor-critic algorithm involves two neural networks: the actor, which learns a policy for selecting actions, and the critic, which evaluates the actions taken by the actor. Your goal is to implement the actor net... | ```python
import torch
import torch.nn as nn
import torch.nn.functional as F
class Actor(nn.Module):
def __init__(self, action_size, seed, fc1_units, fc2_units):
super(Actor, self).__init__()
self.seed = torch.manual_seed(seed)
self.fc1 = nn.Linear(action_size, fc1_units)
self.fc2 =... | magicoder | python |
You are tasked with creating a Python class that represents a platform for a specific hardware device. The platform class should inherit from the `XilinxPlatform` class and have specific attributes and methods to configure the platform for a Xilinx FPGA device. Your task is to complete the implementation of the `Platfo... | ```python
from my_xilinx_platform_module import XilinxPlatform # Assuming the XilinxPlatform class is defined in a separate module
class Platform(XilinxPlatform):
name = "sp3_kit"
default_clk_name = "clk50"
default_clk_period = 20.0
def __init__(self, toolchain="ise", programmer="openocd"):
_... | magicoder | python |
You are given a code snippet that calculates the number of unique binary search trees that can be formed with `n` nodes. The code uses dynamic programming to solve this problem. Your task is to complete the implementation of the `numTrees` function and write a program to find the number of unique binary search trees th... | ```cpp
#include <iostream>
#include <vector>
int numTrees(int n) {
std::vector<int> dp(n + 1, 0);
dp[0] = 1;
dp[1] = 1;
for (int i = 2; i <= n; i++) {
for (int j = 1; j <= i; j++) {
dp[i] += dp[j - 1] * dp[i - j];
}
}
return dp[n];
}
int main() {
int n;
std:... | magicoder | cpp |
You are tasked with implementing a logging system for monitoring the parameters of a machine learning model. The provided code snippet demonstrates a function `store_model_indicators` that iterates through the named parameters of a PyTorch model and stores the parameters that require gradient computation using a logger... | ```python
import torch
class ModelLogger:
def __init__(self):
self.stored_params = {}
def add_indicator(self, name: str, data: torch.Tensor):
# Add an indicator as a histogram with the given name and data
# Implementation not shown
def store(self, name: str, param: torch.Tensor):
... | magicoder | python |
You are tasked with implementing a custom data structure in C# to represent a binary search tree (BST) and performing various operations on it. A binary search tree is a binary tree where for each node, all elements in its left subtree are less than the node, and all elements in its right subtree are greater than the n... | ```csharp
public class BSTNode
{
public int Value { get; set; }
public BSTNode Left { get; set; }
public BSTNode Right { get; set; }
public BSTNode(int value)
{
Value = value;
Left = null;
Right = null;
}
}
public class BinarySearchTree
{
private BSTNode root;
... | magicoder | csharp |
You are given a code snippet representing a class with various properties. Each property is decorated with attributes such as `Ordinal` and `RED`. The properties have different data types and are related to inkCanvasWidgetReference, CUInt32, CFloat, and inkTextWidgetReference. Your task is to create a program that proc... | ```python
def processProperties(instance):
red_properties = [(prop, type(getattr(instance, prop)).__name__) for prop in dir(instance) if hasattr(getattr(instance, prop), 'RED')]
ordinal_properties = [(prop, getattr(getattr(instance, prop), 'Ordinal')) for prop in dir(instance) if hasattr(getattr(instance, prop)... | magicoder | python |
You are tasked with creating a password validation system. Your task is to implement a class `PasswordValidator` with the following requirements:
1. The class should have a property `Password` of type string, which represents the password to be validated.
2. The password must satisfy the following criteria:
- At le... | ```csharp
public class PasswordValidator
{
public string Password { get; set; }
public bool IsValidPassword()
{
if (Password.Length < 8)
return false;
if (!Password.Any(char.IsUpper))
return false;
if (!Password.Any(char.IsLower))
return false;
... | magicoder | csharp |
You are tasked with creating a program that extracts the copyright information from a given source code file. The copyright information is typically found in comments at the beginning of the file and may contain multiple lines. The program should be able to identify and extract the copyright notice from the comments an... | ```python
import re
def extract_copyright_notice(source_code):
# Use regular expression to find the copyright notice in the source code
match = re.search(r'Copyright\s+\d{4}-\w+\s+.*', source_code)
if match:
return match.group().lstrip('#').strip()
else:
return "Copyright notice not fou... | magicoder | python |
You are tasked with implementing a Python module that provides a custom import behavior for a package. The package contains a file named `__init__.py` and a module named `trellab.py`. The `__init__.py` file is empty, and the `trellab.py` module contains a class named `TrellabOrganizationClient`.
Your goal is to modify... | To achieve the desired custom import behavior, you can modify the `__init__.py` file within the package. By explicitly defining the `__all__` variable in the `__init__.py` file and including the `TrellabOrganizationClient` class, you can control which symbols are imported when using the `from package_name import *` syn... | magicoder | python |
You are tasked with creating a memory monitoring system for a microcontroller running MicroPython. The system should periodically report the amount of free memory and perform other tasks concurrently. You are provided with a code snippet that uses MicroPython's `uasyncio` module for asynchronous task management and the... | ```python
import uasyncio
import gc
# mem_report task
async def mem_report():
while True:
print('free mem = %s' % gc.mem_free())
await uasyncio.sleep_ms(5_000)
# main task
async def main():
# create tasks
uasyncio.create_task(led_blink())
uasyncio.create_task(say_hello())
uasyncio.... | magicoder | python |
You are tasked with implementing a circular buffer data structure in C++. A circular buffer, also known as a ring buffer, is a fixed-size buffer that overwrites old data with new data when the buffer is full. Your task is to create a class template for a circular buffer that supports the following operations:
1. `push_... | ```cpp
#include <cstddef>
#include <stdexcept>
#include <memory>
template <typename T, size_t N>
class RingBuf {
public:
RingBuf() : buffer(new T[N]), head(0), tail(0), size(0) {}
void push_back(const T& value) {
if (size == N) {
head = (head + 1) % N; // Overwrite the oldest element
... | magicoder | cpp |
You are given a vector of integers `nums`. Your task is to find the length of the longest increasing subsequence (LIS) within `nums`. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. An increasing subsequence is a... | ```cpp
#include <vector>
#include <algorithm>
int longestIncreasingSubsequence(const std::vector<int>& nums) {
int n = nums.size();
if (n == 0) return 0;
std::vector<int> dp(n, 1);
int maxLength = 1;
for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
if (nums[i] > num... | magicoder | cpp |
You are tasked with implementing a file decryption function in Swift. The function takes in a file URL, a decryption key, and a callback function. The goal is to decrypt the contents of the file using the provided key and then invoke the callback function with the decrypted file URL. If any errors occur during the decr... | ```swift
public func decrypt(file: URL, key: Data, callback: @escaping ((URL) throws -> Void)) throws -> Void {
print("Initializing")
let fileURL = file
guard let fileData = try? Data(contentsOf: fileURL) else {
throw NSError(domain: "Unable to read file data", code: 0, userInfo: nil)
}
... | magicoder | swift |
You are tasked with implementing a custom assertion method for testing exceptions in Java. Your goal is to create a method that can be used in JUnit tests to assert whether a specific exception is thrown or not thrown when a certain piece of code is executed.
Your task is to implement the `assertThrows` and `assertDoe... | ```java
import org.junit.jupiter.api.function.Executable;
import static org.junit.jupiter.api.Assertions.fail;
public class ExceptionAssertions {
public static void assertThrows(Class<? extends Throwable> expectedException, Executable executable) {
try {
executable.execute();
fail... | magicoder | java |
You are tasked with simulating a chat server using Python's Pyro library. The provided code snippet is a part of a multi-threaded chat client that interacts with the chat server. Your goal is to implement a chat client class that can send and receive messages to and from the chat server using Pyro.
Your task is to com... | ```python
import Pyro.core
CHAT_SERVER_NAME = "chat_server_name"
class ChatClient:
def __init__(self):
self.abort = False
self.chatbox = Pyro.core.getProxyForURI('PYRONAME://'+CHAT_SERVER_NAME)
def send_message(self, message):
self.chatbox.send_message(message)
def receive_messag... | magicoder | python |
You are tasked with implementing a function that checks if a given file descriptor is ready for reading within a specified timeout period. You are provided with a code snippet that includes the necessary header files for the function implementation. Your task is to complete the function and ensure that it correctly uti... | ```c
#include <sys/types.h>
#include <sys/select.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
int isReadyForReading(int fileDescriptor, int timeoutSeconds, int timeoutMicroseconds) {
fd_set readfds;
struct timeval timeout;
FD_ZERO(&readfds);
FD_SET(fileDescriptor, &readfds);
timeo... | magicoder | c |
You are tasked with creating a program that parses a SQL CREATE TABLE statement and extracts the table name, column names, data types, default values, and column constraints. Your program should be able to handle both regular and temporary tables, and it should support multiple columns and constraints.
Write a functio... | ```python
import re
def parseCreateTable(sql_statement):
result = {}
columns = []
# Extract table name
table_name_match = re.search(r'CREATE\s+(?:LOCAL\s+)?(?:TEMPORARY|TEMP)?\s+TABLE\s+(\w+)', sql_statement)
if table_name_match:
result["table_name"] = table_name_match.group(1)
# Extr... | magicoder | python |
You are tasked with creating a user interface for a 3D visualization application using the ImGui library in C++. The snippet provided shows a part of the code responsible for handling user input and displaying options related to raw pose, automatic camera control, and calibration settings. Your task is to extend this c... | To achieve this, you can extend the existing ImGui interface with controls for manipulating the position and orientation of the 3D object. Here's a possible solution:
```cpp
// Add ImGui controls for 3D object manipulation
if (ImGui::TreeNode("Object Manipulation")) {
ImGui::SliderFloat3("Position", &objectPositio... | magicoder | cpp |
You are tasked with creating a program that simulates a simple messaging system between a server and a client. The server and client are connected, and the server is continuously receiving messages from the client. The server uses a fixed-size header to determine the length of the incoming message and decodes it using ... | ```python
import socket
HEADER = 64
FORMAT = 'utf-8'
PORT = 5050
SERVER = socket.gethostbyname(socket.gethostname())
ADDR = (SERVER, PORT)
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
server.listen()
conn, addr = server.accept()
connected = True
count = 0
while connected:
msg_le... | magicoder | python |
You are given a directed weighted graph with N nodes and M edges. The graph is represented by an adjacency matrix dp, where dp[i][j] represents the weight of the edge from node i to node j. If there is no edge from node i to node j, dp[i][j] is set to infinity. Additionally, the diagonal elements dp[i][i] are all initi... | ```python
from typing import List
def update_adjacency_matrix(dp: List[List[int]], N: int) -> List[List[int]]:
for k in range(N):
for i in range(N):
for j in range(N):
if dp[i][k] != float('inf') and dp[k][j] != float('inf'):
dp[i][j] = min(dp[i][j], dp[i][k]... | magicoder | python |
You are tasked with implementing a transpose operation for a given 2D array using OpenCL. The provided code snippet is a part of the `opencl` namespace and contains a template function `transpose_inplace` that performs an in-place transpose operation on the input array. The function takes an `Array` reference `in` and ... | ```cpp
namespace opencl
{
template<typename T>
void transpose_inplace(Array<T> &in, const bool conjugate)
{
dim4 iDims = in.dims();
if(conjugate) {
if(iDims[0] % kernel::TILE_DIM == 0 && iDims[1] % kernel::TILE_DIM == 0)
kernel::transpose_inplace<T, true, true>(i... | magicoder | cpp |
You are tasked with simulating the process of obtaining login credentials for a Tesla API. The process involves generating parameters, making HTTP requests, and handling responses. Your goal is to implement a function that performs the necessary steps to obtain the login page and extract the required parameters for aut... | ```python
import requests
from urllib.parse import urlparse, parse_qs
def gen_params():
# Implementation of the gen_params function is not provided as it is specific to the problem domain.
def obtain_login_params(headers, MAX_ATTEMPTS, UA, X_TESLA_USER_AGENT):
for attempt in range(MAX_ATTEMPTS):
code_... | magicoder | python |
You are tasked with implementing a simple class hierarchy for managing different types of employees in a company. The company has three types of employees: full-time employees, part-time employees, and contractors. Each type of employee has different attributes and behaviors.
Create a class hierarchy with the followin... | ```java
// Employee class
public abstract class Employee {
private String name;
private int employeeId;
public Employee(String name, int employeeId) {
this.name = name;
this.employeeId = employeeId;
}
public String getName() {
return name;
}
public int getEmployeeI... | magicoder | java |
You are tasked with implementing a custom reference-counted cow (clone-on-write) data structure in Rust. The cow data structure should support both owned and borrowed data, and it should be able to efficiently clone the data when it is mutated. Your task is to complete the implementation of the `RCow` struct and its as... | ```rust
impl<'a, T: ?Sized> RCow<'a, T> {
pub fn to_mut(&mut self) -> &mut T {
match &mut self.data {
CowData::Borrowed(_) => {
let new_data = self.data.clone();
self.data = new_data;
self.to_mut()
}
CowData::Owned(o) => Rc:... | magicoder | rust |
You are tasked with implementing a function that takes a person's full name as input and returns their initials. The initials should be a string consisting of the first letter of each word in the name, capitalized and without any spaces. If the input name contains any non-alphabetic characters, they should be ignored.
... | ```python
def initials(name):
parts = name.split(' ')
letters = ''
for part in parts:
if part.isalpha(): # Check if the part contains only alphabetic characters
letters += part[0].upper() # Append the first letter of the part, capitalized
return letters
```
The `initials` function... | magicoder | python |
You are tasked with implementing a music library management system. The system should be able to store information about various artists and their latest albums. You are provided with a `MockService` class that contains a static method `getArtistInfos()` which returns an array of `Artist` objects. Each `Artist` object ... | ```swift
class Artist {
let name: String
let latestAlbum: String
let latestAlbumDate: Date
init(name: String, latestAlbum: String, latestAlbumDate: Date) {
self.name = name
self.latestAlbum = latestAlbum
self.latestAlbumDate = latestAlbumDate
}
}
class MockService {
... | magicoder | swift |
You are tasked with implementing a Singleton class that maintains a history of values and provides methods to update the value, set the maximum history length, and retrieve statistics about the history.
Your task is to implement the Singleton class with the following requirements:
- The class should have a method `upd... | ```python
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super(Singleton, cls).__new__(cls)
cls._instance.history = []
cls._instance.max_history_length = float('inf')
return cls._instance
def updateValue(sel... | magicoder | python |
You are tasked with implementing a function that formats a numerical value with an appropriate unit based on its magnitude. The function should take a numerical value and an optional decimal precision as input and return a tuple containing the formatted value as a string and its corresponding unit.
The function signat... | ```swift
func valueFormatAutoUnit(_ value: Double, decimal: Int?) -> (value: String, unit: String) {
var result = (value: value, unit: "")
if value >= 10000 {
result = (value: value / 10000, unit: "万")
}
if let decimal = decimal {
return (String(format: "%.\(decimal)f", result.... | magicoder | swift |
You are tasked with implementing a function to calculate the total number of lines between two given positions in a document. The document is represented as a collection of blocks, and each block contains a certain number of lines. The given positions are represented by block numbers within the document.
You are provi... | ```cpp
int calculateTotalLines(Document* document, Cursor* elem_cursor, int startBlockNum, int endBlockNum) {
int totalLines = 0;
for (int j = startBlockNum; j <= endBlockNum; j++) {
totalLines += document->findBlock(j).lineCount();
}
return totalLines;
}
```
The `calculateTotalLines` function i... | magicoder | cpp |
You are tasked with creating a program to parse and extract information from a series of HTML elements representing posts on a web page. Each post is contained within a `div` element with the class `kns-konten`, and contains the following structure:
```html
<div class="container mb-5 pb-4">
<div class="row mb-2">
... | ```python
from bs4 import BeautifulSoup
def parsePosts(html_content):
posts = []
soup = BeautifulSoup(html_content, 'html.parser')
post_divs = soup.find_all('div', class_='kns-konten')
for div in post_divs:
post = {}
post['teacher_name'] = div.find('p').text.split(' : ')[1].split('... | magicoder | python |
You are tasked with implementing a Lua binding for a C++ class representing an item stack in a game. The provided code snippet is a part of the implementation for binding the C++ class `LuaItemStack` to Lua. The code snippet uses the Lua C API to create a metatable, fill a method table, and register the class in Lua. Y... | ```cpp
#include <lua.hpp>
class LuaItemStack {
public:
static const char className[];
// Constructor for LuaItemStack
static int create_object(lua_State* L) {
// Retrieve the argument type and create the item stack accordingly
// Example: LuaItemStack* item = new LuaItemStack(...);
... | magicoder | cpp |
You are tasked with creating a script to automate the setup of a MySQL server on a Linux system. The script should perform the following tasks:
1. Create the necessary directories for MySQL data, runtime, and log files: `/var/lib/mysql`, `/var/run/mysqld`, and `/var/log/mysql`.
2. Add specific configuration entries to... | ```bash
#!/bin/bash
# Create necessary directories
mkdir -p /var/lib/mysql
mkdir -p /var/run/mysqld
mkdir -p /var/log/mysql
# Add configuration entries to my.cnf
cat <<EOT >> /etc/mysql/my.cnf
[client]
[mysql]
[mysqld]
EOT
```
The script begins by creating the required directories using the `mkdir -p` command to e... | magicoder | shell |
You are tasked with implementing a function to evaluate comparison expressions in a custom scripting language. The language supports comparison operators such as "eq" (equal), "gt" (greater than), and "lt" (less than). The function takes in three parameters: `$evalStringResult`, `$valueLeft`, and `$valueRight`. The `$e... | The `evaluateComparison` function takes in the array `$evalStringResult` containing the comparison operator, and the values `$valueLeft` and `$valueRight` to be compared. It uses a `switch` statement to handle different comparison operators and returns the result of the comparison. If the comparison operator is "gt" (g... | magicoder | python |
You are tasked with implementing a time-based key-value store. The store should support the following operations:
1. `set(key: String, value: V, timestamp: u64)`: Set the key to the given value at the given timestamp.
2. `get(key: String, timestamp: u64) -> Option<&V>`: Get the value at the given key and timestamp. If... | ```rust
pub struct Entry<V> {
pub timestamp: u64,
pub value: V,
}
pub struct TimeMap<V> {
map: std::collections::HashMap<String, Vec<Entry<V>>>,
}
impl<V> TimeMap<V> {
pub fn new() -> Self {
TimeMap {
map: std::collections::HashMap::new(),
}
}
pub fn set(&mut self,... | magicoder | rust |
You are given a binary tree where each node has a value and may have a left and/or right child. The depth of a node is defined as the number of edges from the node to the tree's root node. The diameter of a tree is the number of nodes on the longest path between any two nodes in the tree.
Write a function `diameterOf... | ```python
class TreeNode:
def __init__(self, value=0, left=None, right=None):
self.value = value
self.left = left
self.right = right
class Solution:
def diameterOfBinaryTree(self, root: TreeNode) -> int:
self.ans = 1
def dfs(node: TreeNode) -> int:
if not no... | magicoder | python |
You are tasked with creating a program to process and store network data into a database. The given code snippet is a part of this program and is responsible for inserting network information into a database table. The `datum.metadata.networks` collection contains network data that needs to be inserted into the `networ... | ```csharp
public void InsertNetworks(List<string> networkData, MySqlConnection dbConnection)
{
int i = 1; // Initialize the unique ID counter
foreach (var network in networkData)
{
string query = "INSERT INTO networks(id, network) VALUES (@id, @network)";
MySqlCommand cmd = new MySqlComman... | magicoder | csharp |
You are given an array of integers and an integer target. Your task is to find two distinct numbers in the array that sum up to the target. If such a pair exists, return their indices. If there are multiple pairs, return the indices of the first pair encountered. If no such pair exists, return an empty array.
You need... | ```cpp
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> numMap;
vector<int> result;
for (int i = 0; i < nums.size(); i++) {
int complement = target - nums[i];
if (numMap.find(complement) != numMap.end()) {
result.push_back(numMap[complement]);
... | magicoder | cpp |
You are working on a project that involves processing and analyzing motion capture data. The provided code snippet is part of a Python class that loads motion capture data from a specified path and performs some operations on it. The data is stored in a NumPy array with dimensions representing the number of samples, ch... | ```python
import numpy as np
class MotionCaptureDataProcessor:
def __init__(self, data_path):
self.data_path = data_path
# Load data from the specified path
print(self.data_path)
self.data = np.load(self.data_path, mmap_mode='r')
def calculate_average_joint_position(self, joint... | magicoder | python |
You are tasked with implementing a user authentication and subscription management system for a chat application. The system involves several components, including a `UserManager`, `SubscriptionManager`, and `PushManager`. The provided code snippet is a part of the authentication and subscription management process.
... | ```swift
// Define the UserManager class responsible for user authentication
class UserManager {
static func changes() {
// Implementation for user authentication changes
}
}
// Define the SubscriptionManager class responsible for subscription management
class SubscriptionManager {
static func chan... | magicoder | swift |
You are tasked with implementing a class for validating and processing command-line parameters for a graphics application. The class, `validation_parameters`, is responsible for extracting and validating specific parameters from the command line using the `twisted_works::cli_parser` library. The class has a constructor... | ```cpp
#include <iostream>
#include <string>
#include <cassert>
#include "twisted_works/cli_parser.h"
#include <GL/gl.h>
class validation_parameters {
public:
validation_parameters(const twisted_works::cli_parser& CommandLine);
std::string file_path;
GLenum profile;
};
validation_parameters::validation_pa... | magicoder | cpp |
You are tasked with creating a function that analyzes a given Swift source code file and counts the number of test cases defined within it. Test cases are defined within classes that inherit from XCTestCase and are marked with the prefix "test" in their function names.
Write a function `countTestCases` that takes a st... | ```swift
func countTestCases(_ sourceCode: String) -> Int {
var testCasesCount = 0
// Split the source code by lines
let lines = sourceCode.components(separatedBy: .newlines)
var isInsideXCTestCaseClass = false
for line in lines {
if line.contains(": XCTestCase") {
... | magicoder | swift |
You are tasked with creating a Python script that monitors the status of a given process and alerts the user if the process is not running. The script should take the process name as input and continuously check if the process is running. If the process is not running, the script should send an email notification to th... | ```python
import subprocess
import smtplib
from email.message import EmailMessage
import time
def send_email_notification(process_name: str):
sender_email = "your_email@example.com"
receiver_email = "recipient_email@example.com"
password = "your_email_password"
message = EmailMessage()
message["Fr... | magicoder | python |
You are tasked with implementing a filter for a web application that handles user authentication and session management. The provided code snippet is a part of the filter logic and contains a segment that deals with user logout functionality. Your task is to understand the code and design a method to handle user logout... | ```java
public class UserLogoutHandler {
public void handleLogout(HttpServletRequest request, HttpServletResponse response) {
if (FiltersHelper.isAuthenticated(request)) {
String headerValue = request.getHeader(FiltersHelper.Constants.HEADER_AUTHORIZATION);
if ((headerValue == null |... | magicoder | java |
You are tasked with creating a Python program that simulates a simple banking system. The program should be able to handle basic banking operations such as account creation, balance inquiry, deposits, and withdrawals. The program should also incorporate user authentication to ensure the security of the accounts.
Your ... | ```python
import random
class BankAccount:
def __init__(self, name, initial_deposit):
self.account_number = random.randint(10000, 99999)
self.name = name
self.balance = initial_deposit
self.password = None
def set_password(self, password):
self.password = password
... | magicoder | python |
You are tasked with implementing a C++ class that simulates a simple linked list. Your class should support basic operations such as insertion, deletion, and traversal of the linked list. Additionally, you need to implement a method to reverse the linked list.
Your task is to complete the implementation of the `Linked... | ```cpp
#include <iostream>
class Node {
public:
int data;
Node* next;
Node(int value) : data(value), next(nullptr) {}
};
class LinkedList {
private:
Node* head;
public:
LinkedList() : head(nullptr) {}
void insertAtBeginning(int value) {
Node* newNode = new Node(value);
newNod... | magicoder | cpp |
You are given a list of integers representing the start and end points of several intervals. Your task is to write a function that merges overlapping intervals and returns a new list of non-overlapping intervals.
For example, given the list of intervals:
```
intervals = [[1, 3], [2, 6], [8, 10], [15, 18]]
```
The func... | ```python
from typing import List
def merge_intervals(intervals: List[List[int]]) -> List[List[int]]:
if not intervals:
return []
intervals.sort(key=lambda x: x[0]) # Sort intervals based on the start value
merged = [intervals[0]] # Initialize the merged list with the first interval
for in... | magicoder | python |
You are given a 4x4 matrix of integers. Your task is to find the maximum sum of a hourglass shape in the matrix. An hourglass shape is defined as a subset of values in the matrix arranged in the following pattern:
```
a b c
d
e f g
```
Where a, b, c, d, e, f, and g are distinct values in the matrix.
Write a functi... | ```python
def max_hourglass_sum(matrix):
max_sum = None
for i in range(4):
for j in range(4):
s = sum(matrix[i][j:j+3]) + matrix[i+1][j+1] + sum(matrix[i+2][j:j+3])
if max_sum is None or s > max_sum:
max_sum = s
return max_sum
```
The `max_hourglass_sum` funct... | magicoder | python |
You are tasked with creating a test case for an e-commerce website's payment process using Protractor, a popular end-to-end testing framework for Angular and AngularJS applications. The provided code snippet is a TypeScript class that represents a page object for the payment page. The class contains an ElementFinder fo... | ```typescript
import { browser, element, by, ElementFinder } from 'protractor';
describe('Payment Page', () => {
let payByBankWireButton: ElementFinder;
beforeAll(async () => {
await browser.get('http://your-ecommerce-website.com/payment'); // Replace with the actual URL
payByBankWireButton = element(by.c... | magicoder | typescript |
You are tasked with creating a program to manage and execute parallel jobs based on a given input file. The program should read the input file, which contains a list of jobs, and execute them in parallel using a specified number of threads. Your task is to implement a function or method that accomplishes this job execu... | ```python
import subprocess
def execute_parallel_jobs(input_file: str, num_threads: int) -> None:
parallel_command = f"parallel --jobs {num_threads} < {input_file}"
subprocess.run(parallel_command, shell=True)
```
The `execute_parallel_jobs` function uses the `subprocess` module to run the parallel command wi... | magicoder | python |
You are working on a document management system that utilizes the Incode framework. In this system, there is a class `VetoDocFragmentDeleteSubscriber` which subscribes to events related to the deletion of document fragments. The class contains a method `on` that is triggered when a `DocFragment.DeleteDomainEvent` occur... | ```java
import com.google.common.eventbus.Subscribe;
import org.axonframework.eventhandling.EventHandler;
public class DocumentEventHandler {
@Subscribe
@EventHandler
public void handleDocumentEvent(DocumentEvent event) {
switch (event.getEventPhase()) {
case ARCHIVE:
S... | magicoder | java |
You are tasked with creating a Django model for a user management system. The model should include fields for user ID, phone number, creation time, and update time. Your task is to define the model class and its meta information according to the given requirements.
Define a Django model class called `UserModel` that i... | ```python
from django.db import models
from django.contrib.auth.models import AbstractUser
class UserModel(AbstractUser):
user_id = models.AutoField(verbose_name='用户ID', primary_key=True)
phone_num = models.CharField(max_length=20, verbose_name='联系电话')
crt_time = models.DateTimeField(verbose_name='创建时间', a... | magicoder | python |
You are working for a data science team that is building a machine learning model using the XGBoost library. Your task is to create a Python function that loads a pre-trained XGBoost model from a file and makes predictions on a new dataset. The model files are stored with a specific naming convention, and you need to i... | ```python
import os
import xgboost as xgb
import pickle
def load_and_predict_model(name, data):
model_file_path = os.path.join(util.features_prefix + name + '_XXXYYY.pkl')
if os.path.exists(model_file_path):
with open(model_file_path, 'rb') as model_file:
xgboost_model = pickle.load(model_f... | magicoder | python |
You are working on a Python project that involves interfacing with a C++ library using SWIG (Simplified Wrapper and Interface Generator). As part of this project, you need to understand and modify the provided code snippet, which is a part of the SWIG-generated Python wrapper for a C++ class.
The code snippet includes... | The provided code snippet is part of a SWIG-generated Python wrapper for a C++ class. Let's analyze the functions in the code snippet:
1. `__repr__` Function:
The `__repr__` function is used to create a string representation of an object. In this case, it is used to create a string representation of the `self.this`... | magicoder | python |
You are tasked with creating a Python function that takes in a dataset and performs a specific data preprocessing task. The function should be able to handle both numerical and categorical features, and it should return the preprocessed dataset ready for machine learning modeling.
You are given the following code snip... | ```python
import pandas as pd
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.compose import ColumnTransformer
from sklearn.model_selection import train_test_split
def preprocess_data(dataset, target_column):
# Separate features and target variable
X = dataset.drop(columns=[target_... | magicoder | python |
You are tasked with implementing a parser for a simple expression language. The language consists of binary operations, such as addition, subtraction, multiplication, and division, as well as parentheses for grouping. The expressions are represented using a custom abstract syntax tree (AST) format.
The AST nodes have ... | ```python
class Token:
def __init__(self, start, stop, type, value):
self.start = start
self.stop = stop
self.type = type
self.value = value
class Expr:
def __init__(self, start, stop, type, children):
self.start = start
self.stop = stop
self.type = type
... | magicoder | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.