query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with implementing a function to calculate the sum of all prime numbers within a given range. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. The function should take two integer parameters, `start` and `end`, representing the inclusive range within... | ```cpp
#include <iostream>
#include <cmath>
bool isPrime(int n) {
if (n <= 1) {
return false;
}
for (int i = 2; i <= sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
long long sumOfPrimes(int start, int end) {
long long sum = 0;
for (in... | magicoder | cpp |
You are tasked with implementing a function that processes work orders in a manufacturing system. The function should take a dictionary of values as input and update the production schedule with the planned finish date for the work order.
You are given the following code snippet as a reference:
```python
if values['d... | ```python
def update_production_schedule(values, workorder):
if 'date_planned_finished' in values:
planned_finish_date = values['date_planned_finished']
workorder.production_id.with_context(force_date=True).write({
'date_planned_finished': fields.Datetime.to_datetime(planned_finish_date)... | magicoder | python |
You are tasked with implementing a Python class for representing 3D vectors and edges in a geometric context. The class `Vector3` represents a 3D vector with x, y, and z components, and the class `Edge` represents an edge connecting two 3D points. Your task is to implement the missing methods for the `Vector3` and `Edg... | ```python
class Vector3:
def __init__(self, x: float, y: float, z: float):
self.x = x
self.y = y
self.z = z
def __eq__(self, other: 'Vector3') -> bool:
return self.x == other.x and self.y == other.y and self.z == other.z
class Edge:
def __init__(self, start: Vector3, end: ... | magicoder | python |
You are given a code snippet that is part of a script used to process data from a quantum mechanics simulation. The script is designed to extract specific data from a file called EIGENVAL and manipulate it to create new files. Your task is to write a program that simulates the data processing steps described in the cod... | ```python
# Read the contents of the file EIGENVAL
with open('EIGENVAL', 'r') as eigenval_file:
eigenval_data = eigenval_file.readlines()
# Define the value of $nband (assuming it's a known variable)
nband = 10 # Replace with the actual value of $nband
# Iterate over the range of values for variable i
for i in r... | magicoder | python |
You are tasked with implementing a custom data structure in C# to manage a collection of items with the following requirements:
1. The data structure should be able to store items of any data type.
2. It should support adding items to the collection, removing items from the collection, and checking if a specific item i... | ```csharp
using System;
using System.Collections.Generic;
namespace PhoenixPoint.Common.Core
{
public class UniqueCollection<T>
{
private HashSet<T> items;
public UniqueCollection()
{
items = new HashSet<T>();
}
public void AddItem(T item)
{
... | magicoder | csharp |
You are tasked with optimizing a query for retrieving transportation service information based on geographical proximity. The given code snippet is a part of a Python function that performs a database query to find transportation services and stops within a certain radius of a given location. The function takes into ac... | To optimize the given query for retrieving transportation service information based on geographical proximity, we can utilize the PostgreSQL extension `cube` and `earthdistance` to efficiently calculate distances and improve query performance.
The optimized query can be rewritten as follows:
```sql
SELECT sfs.id, sfs... | magicoder | sql |
You are tasked with implementing a Python function that calculates the total cost of a customer's purchase, factoring in both the base price of the items and any additional costs. The function should accept a variable number of keyword arguments, where each keyword represents an item and its associated price. Additiona... | ```python
def calculate_total_cost(**kwargs) -> float:
total_cost = sum(kwargs.values())
return total_cost
```
The `calculate_total_cost` function first calculates the sum of all the values in the `kwargs` dictionary, representing the prices of the items and additional costs. It then returns this total cost as... | magicoder | python |
You are tasked with implementing a function that processes a sequence of integers and returns the longest increasing subsequence (LIS) present in the sequence. 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 i... | ```python
from typing import List
def longest_increasing_subsequence(seqs: List[int]) -> List[int]:
if not seqs:
return []
n = len(seqs)
lis = [1] * n
for i in range(1, n):
for j in range(0, i):
if seqs[i] > seqs[j] and lis[i] < lis[j] + 1:
lis[i] = lis[j] ... | magicoder | python |
You are tasked with implementing a multi-threaded program that simulates a simple semaphore mechanism. A semaphore is a synchronization construct that can be used to control access to a shared resource. In this problem, you are required to implement a class `CustomSemaphore` that provides the functionality of a semapho... | ```csharp
using System;
using System.Threading;
public class CustomSemaphore
{
private int count;
public CustomSemaphore(int initialCount)
{
count = initialCount;
}
public void Wait()
{
lock (this)
{
while (count == 0)
{
Monitor.... | magicoder | csharp |
You are tasked with implementing a function that simulates the movement of data between different types of registers in a low-level assembly language. The assembly language in question is used for a specific architecture and supports operations for moving data between floating-point registers, general registers, and re... | ```java
void moveData(Register from, Register to) {
if (from.getType() == RegisterType.FLOAT_REG && to.getType() == RegisterType.FLOAT_REG) {
masm.moveDouble(from.getFloatReg(), to.getFloatReg());
} else if (from.getType() == RegisterType.FLOAT_REG && to.getType() == RegisterType.GENERAL_REG_PAIR) {
... | magicoder | java |
You are working on a performance analysis tool for a machine learning model. The code snippet provided is a part of the tool that measures the average inference time and average summary time for the model. The `info` dictionary contains information about each inference, including the `invoke_time` for each inference. T... | ```python
import time
def calculate_average_times(info: dict) -> tuple:
times = []
for data in info.values():
times.append(data['invoke_time'])
start = time.time()
end = time.time()
time_avg = sum(times) / len(times)
time_all = (end - start) / len(times)
return (time_avg * 1000, tim... | magicoder | python |
You are tasked with implementing a function to parse and extract information from a given Python code snippet. The code snippet contains a series of backtick-delimited strings and a conditional block. Your task is to extract the backtick-delimited strings and the conditional block, and then process the information to g... | ```python
def parse_code_snippet(code: str) -> str:
sequences = {}
num_sequences = 0
conditional_block = ""
# Extract backtick-delimited strings and conditional block
code_lines = code.split("\n")
for line in code_lines:
if line.startswith("`"):
seq_info = line.strip().lstri... | magicoder | python |
You are tasked with implementing a function to calculate the first and second derivatives of the joints in a two-joint arm system. The function `animatearm` is responsible for animating the movement of the two-joint arm using matplotlib. Your task is to create a Python function that computes the derivatives and then us... | ```python
import numpy as np
import matplotlib.pyplot as plt
def calculate_derivatives(ACC):
a1d, a2d = ACC[:, 0]
a1dd, a2dd = ACC[:, 1]
return [a1d, a2d, a1dd, a2dd]
def animatearm(state, t, aparams):
"""
animate the twojointarm
"""
# Assuming the implementation of the animatearm function... | magicoder | python |
You are tasked with creating a custom React component that renders a horizontal list of items using styled-components. The component should accept an array of items as a prop and render each item as a list element in a horizontal layout.
Your task is to complete the `HorizontalList` component by using the `styled-comp... | ```jsx
import React from 'react';
import styled from 'styled-components';
const HorizontalList = styled.ul`
list-style: none;
padding: 0;
display: flex;
flex-direction: row;
align-items: center;
`;
const ListItem = styled.li`
margin: 0 10px;
`;
const HorizontalListItem = ({ item }) => {
return <ListIte... | magicoder | jsx |
You are tasked with creating a Rust function that processes a given source code and generates a byte vector based on certain options and a header flag. The function should handle potential errors and return the result as a `Result<Vec<u8>, Error>`.
The function signature is as follows:
```rust
fn generate(source: &str... | ```rust
use std::io;
use syn;
use proc_macro2;
use thiserror::Error;
#[derive(Error, Debug)]
enum Error {
#[error("Failed to parse source code")]
ParseError(#[from] syn::Error),
#[error("Failed to find bridge module")]
BridgeError,
#[error("Type checking failed")]
TypeCheckError,
#[error("F... | magicoder | rust |
You are tasked with implementing a thread-safe data structure called `ConcurrentSet` in Swift. The `ConcurrentSet` should support adding and removing elements concurrently using Grand Central Dispatch (GCD) to ensure thread safety. The `ConcurrentSet` should have the following methods:
1. `add(_:)`: This method should... | ```swift
import Foundation
class ConcurrentSet<T: Hashable> {
private var entries = [T]()
private let queue = DispatchQueue(label: "com.example.ConcurrentSetQueue")
func add(_ element: T) {
queue.async(flags: .barrier) {
self.entries.append(element)
}
}
func remove(_ e... | magicoder | swift |
You are tasked with implementing a function that corrects the angles of a scope based on a given period. The function takes in three parameters: `angles0`, `angles1`, and `scope_id`. The `angles0` and `angles1` parameters are NumPy arrays representing the initial and final angles of the scope, and `scope_id` is an inte... | ```python
import numpy as np
def correct_angles(angles0: np.ndarray, angles1: np.ndarray, scope_id: int) -> np.ndarray:
period = np.pi
dif = angles1 - angles0
mask = np.abs(dif) > period * 0.5
angles1 += -period * mask * np.sign(dif)
ave = (angles0 + angles1) / 2.0
if scope_id == 0:
# A... | magicoder | python |
You are tasked with implementing a decoding proxy for reading data from a source. The proxy should be able to decode the data as it is read and provide the decoded content to the consumer. Your task is to design and implement the `DecodingReadProxy` struct in Rust, which will act as a proxy for reading and decoding dat... | ```rust
use std::io::{Read, Result};
pub struct DecodingReadProxy<'a, R> {
source: &'a mut R,
}
impl<'a, R: Read> DecodingReadProxy<'a, R> {
pub fn new(source: &'a mut R) -> DecodingReadProxy<'a, R> {
DecodingReadProxy { source }
}
pub fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
... | magicoder | rust |
You are tasked with debugging a section of code that sets up routes for an API using the Dingo API package in a Laravel application. The code snippet provided contains a portion of the route setup, but it seems to have a potential issue. Your task is to identify the problem and propose a solution to fix it.
Given the ... | The potential issue in the provided code snippet is the commented-out middleware `'auth:api'` in the route setup. This middleware is typically used for authenticating API requests using Laravel Passport. However, it seems to have been commented out, which might lead to unauthorized access to the 'users' route.
To fix ... | magicoder | php |
You are tasked with implementing a Python class that simulates a simple multi-agent environment for a scenario. The scenario is defined in a separate Python file and is loaded dynamically. Your goal is to create the environment using the provided code snippet as a guide.
Your task is to implement the `MultiAgentEnv` c... | ```python
class MultiAgentEnv:
def __init__(self, world, reset_world, reward, observation):
self.world = world
self.reset_world = reset_world
self.reward = reward
self.observation = observation
self.current_state = None
def reset(self):
self.current_state = self.... | magicoder | python |
You are tasked with implementing a Swift data structure for managing images and their associated metadata. The structure, `ImageContainer`, is designed to hold an image along with optional metadata such as type, preview status, additional data, and user information. Additionally, the structure provides a method to modi... | ```swift
import Foundation
// Define the PlatformImage type
typealias PlatformImage = UIImage
typealias ImageType = String
typealias UserInfoKey = String
struct ImageContainer {
let image: PlatformImage
let type: ImageType?
let isPreview: Bool
let data: Data?
let userInfo: [UserInfoKey: Any]
... | magicoder | swift |
You are tasked with creating a Python package version checker. Your program should take in the name of a Python package and return its version and license information. You can assume that the package is installed in the current Python environment.
Write a function `package_info` that takes a string `package_name` as i... | ```python
import importlib.metadata
def package_info(package_name):
try:
package_version = importlib.metadata.version(package_name)
package_license = importlib.metadata.license(package_name)
return {'version': package_version, 'license': package_license}
except importlib.metadata.Packag... | magicoder | python |
You are tasked with creating a program that simulates a simple fluid dynamics system. The fluid simulation will be represented by a grid of cells, and the fluid will flow between adjacent cells based on certain rules.
Your task is to implement a function `simulateFluid` that takes the following parameters:
- `grid`: a... | ```java
public class FluidSimulation {
public static int[][] simulateFluid(int[][] grid, int iterations) {
int rows = grid.length;
int cols = grid[0].length;
int[][] result = new int[rows][cols];
while (iterations > 0) {
for (int i = 0; i < rows; i++) {
f... | magicoder | java |
You are tasked with creating a program that simulates a simple package manager for a fictional operating system called "MyOS." The package manager should be able to handle the installation of new packages and display a list of installed packages. Each package can have dependencies on other packages, and the package man... | ```python
class PackageManager:
def __init__(self):
self.packages = {}
def install_package(self, package_name):
if package_name in self.packages:
print(f"{package_name} is already installed.")
else:
dependencies = self.get_dependencies(package_name)
f... | magicoder | python |
You are tasked with implementing a module manager class in Python. The module manager should support adding, retrieving, and removing modules by name. Each module has a name and a version. You need to implement the `ModuleManager` class with the following methods:
- `add_module(module_name, module_version)`: Adds a mod... | ```python
class Module:
def __init__(self, name, version):
self.name = name
self.version = version
class ModuleManager:
def __init__(self):
self.modules = []
def add_module(self, module_name, module_version):
self.modules.append(Module(module_name, module_version))
def... | magicoder | python |
You are tasked with creating a Python function that simulates a network device interaction using the `scrapli` library. The function will take in a list of interaction events and a list of strings that represent failed commands/interactions. The function will then use the `scrapli` library to send the interaction event... | ```python
from scrapli.driver.core import IOSXEDriver
from nornir.core.task import Result
def send_interactive(interact_events, failed_when_contains):
# Assume task.host.get_connection and task.nornir.config are properly defined
scrapli_conn = task.host.get_connection("scrapli", task.nornir.config)
scrapli... | magicoder | python |
You are tasked with implementing a simplified version of a party invitation system. The system should handle the process of inviting guests to different parties and handle any errors that may occur during the invitation process.
You are given a code snippet that represents a part of the invitation system. The snippet ... | ```rust
// Define the Guest struct
struct Guest {
name: String,
}
// Define the Party struct
struct Party {
name: String,
guests: Vec<Guest>,
}
impl Party {
fn new(name: &str) -> Party {
Party {
name: String::from(name),
guests: Vec::new(),
}
}
}
// Impleme... | magicoder | rust |
You are tasked with implementing a simple Object-Relational Mapping (ORM) system in Swift. The provided code snippet is part of a database access layer that interacts with the underlying database using SQL queries. Your task is to extend this ORM system by implementing the `getOrm` function and the `deleteBuilder` and ... | ```swift
// Implementation of the getOrm function
func getOrm(cls: AnyClass) -> ORM {
// Your implementation of retrieving the ORM instance for the given class
// This could involve a mapping between Swift classes and their corresponding database tables
// Return the ORM instance for the given class
}
// I... | magicoder | swift |
You are tasked with implementing a TypeScript interface and a function that utilizes this interface. The interface represents a message definition, and the function is responsible for constructing a message based on the provided parameters.
Interface:
```typescript
interface MessageDefinition {
value: string | Objec... | ```typescript
function constructMessage(definition: MessageDefinition): string {
if (typeof definition.value === 'string') {
return definition.value;
} else if (typeof definition.value === 'object' && definition.protoPath && definition.packageName && definition.name) {
return `Constructed message using prot... | magicoder | typescript |
You are tasked with implementing a custom context lookup mechanism for a web application framework. The `MockContext` class provides a method `lookup` that takes in a key and a variable number of lookup types (e.g., PATH, HEADER, COOKIE, FLASH, SESSION, QUERY, FORM, MULTIPART) and returns a corresponding `Value` object... | ```java
import java.util.HashMap;
import java.util.Map;
// Custom exception for missing values
class MissingValueException extends RuntimeException {
// Custom exception implementation
}
// Enum for lookup types
enum LookupType {
PATH, HEADER, COOKIE, FLASH, SESSION, QUERY, FORM, MULTIPART
}
// Value class t... | magicoder | java |
You are tasked with implementing a simple registration system for classes in a C++ namespace using the given code snippet as a reference. The code snippet demonstrates the registration of a class `VertexGlyphFilter` within the `quick::Vtk` namespace using the `Qml::Register::Class` function. Your task is to create a si... | ```cpp
#include <iostream>
#include <string>
#include <map>
// Define the namespace MyNamespace
namespace MyNamespace {
// Define the class MyClass
class MyClass {
public:
MyClass() {
// Constructor logic for MyClass
}
};
// Define a registration mechanism for classes ... | magicoder | cpp |
You are tasked with implementing a program that processes C++ header files to extract specific information. In this problem, you are required to write a function that takes a string representing the content of a C++ header file and extracts the name of the header file from the `#endif` directive.
You need to implement... | ```cpp
#include <string>
std::string extractHeaderFileName(const std::string& fileContent) {
std::string endIfDirective = "#endif";
size_t pos = fileContent.rfind(endIfDirective);
if (pos != std::string::npos) {
size_t start = fileContent.rfind('/', pos);
size_t end = fileContent.rfind("hpp... | magicoder | cpp |
You are tasked with implementing a function that checks whether the given dictionary of boundary pairs is valid. A boundary pair consists of two boundary names separated by an equals sign. The function should return True if the dictionary is valid, and False otherwise.
The function should take a single argument:
- `pB... | ```python
def validate_boundary_pairs(pBd):
if not isinstance(pBd, dict):
return False
bnPOOL = set()
for pair in pBd:
if '=' not in pair or pair.count('=') > 1:
return False
bn1, bn2 = pair.split('=')
if (bn1, bn2) in bnPOOL or (bn2, bn1) in bnPOOL:
... | magicoder | python |
You are tasked with implementing a method to calculate the real item count in a hierarchical data structure. The structure consists of nodes, each potentially containing child nodes. The method should take into account the depth of the nodes and return the total count of all items in the hierarchy.
You are given the f... | ```java
/**
* Calculates the real item count in a hierarchical data structure.
* @param childCount The count of child items at the current level.
* @return The total count of all items in the hierarchical structure.
* @throws IOException If an I/O error occurs.
*/
private int _getRealItemCount(int childCount) throws IO... | magicoder | java |
You are tasked with implementing a function to calculate the positions of control points for a Bezier curve based on given parameters. The Bezier curve is defined by four points: two anchor points (to1 and to2) and two control points (control1 and control2). The function should take the following inputs:
- `reverseFrac... | ```swift
func calculateControlPoints(reverseFraction: Double, waxing: Bool) -> (Int, Int, Int, Int) {
var to1y = 0 // to2y = 800 - (to1y)
var controlx = 1000 // control 1 and 2 always the same
var control1y = -200
to1y = Int(((reverseFraction-1)*500)*((1-reverseFraction)*10))
controlx = Int(rev... | magicoder | swift |
You are tasked with creating a Rust macro that generates code for accessing memory-mapped registers in an embedded system. The macro should provide a convenient and safe way to access the MPU Type Register, which indicates the number of regions the Memory Protection Unit (MPU) supports. The MPU Type Register is located... | ```rust
macro_rules! reg {
($(#[$struct_attr:meta])* pub $reg_name:ident => {
address => $address:expr;
size => $size:expr;
reset => $reset:expr;
traits => { $($trait:ident)* };
}) => {
$(#[$struct_attr])*
pub struct $reg_name;
impl $reg_name {
... | magicoder | rust |
You are tasked with creating a function that processes payment updates from a payment service provider and stores the payment details in a database. The function will receive a JSON string representing a payment update and will need to perform the following steps:
1. Deserialize the JSON string into a `PaymentUpdate` o... | ```csharp
public class PaymentUpdate
{
public string LocationId { get; set; }
public string EntityId { get; set; }
}
public class Payment
{
public string Id { get; set; }
public DateTime CreatedAt { get; set; }
// Other payment details
}
public class PaymentProcessor
{
private readonly HttpCli... | magicoder | csharp |
You are tasked with implementing a function that compares two DataFrames and checks if they are equal, with the option to ignore schema metadata such as comments. The function should handle cases where one or both DataFrames are None.
Write a Python function `compare_dataframes` that takes in four parameters:
1. `expe... | ```python
import pandas as pd
def compare_dataframes(expected, actual, ignore_schema_metadata=False, ignore_comments=False):
if expected is None:
assert actual is None, 'The expected DataFrame is None, but the actual DataFrame is not.'
return True # Both DataFrames are None.
if ignore_schema_... | magicoder | python |
You are tasked with implementing a simple notification library in Rust. The library should allow users to subscribe to various events and receive notifications when those events occur. Your task is to create a `NotificationLibrary` struct with the following methods:
1. `new()`: This method should create a new instance ... | ```rust
struct NotificationLibrary {
subscriptions: std::collections::HashMap<String, Vec<Box<dyn Fn() + Send>>>,
}
impl NotificationLibrary {
fn new() -> Self {
NotificationLibrary {
subscriptions: std::collections::HashMap::new(),
}
}
fn subscribe(&mut self, event: String... | magicoder | rust |
You are tasked with implementing a Python function that simulates a simple vending machine. The vending machine will have a set of available items, each with a specific price. The function should take the item name and the amount of money inserted by the user as input and return the appropriate response based on the fo... | ```python
def vending_machine(item: Literal['cola', 'chips', 'candy'], money_inserted: float) -> str:
items = {'cola': 1.5, 'chips': 1.0, 'candy': 1.75}
if item in items:
price = items[item]
if money_inserted >= price:
return f"Item Dispensed: {item}"
else:
r... | magicoder | python |
You are tasked with creating a Rust function that processes data from an API response and returns a specific result. The function `parse_response_body` is responsible for parsing the response body, and the `get_modules` function is intended to retrieve a list of modules from an IoT hub. Your task is to implement the `p... | ```rust
use std::io;
use aziot_identity_common::hub::Module;
// Implement the parse_response_body function to extract relevant data from the API response
async fn parse_response_body<T, U, E>(response: T) -> Result<U, E> {
// Your implementation here to parse the response and return the parsed data
}
// Complete ... | magicoder | rust |
You are tasked with implementing a C++ concept checking utility for argument providers of expandables. An argument provider of expandables is a type that can provide a sequence of arguments, where the number of arguments can vary at runtime. Your goal is to define a concept that checks whether a given type satisfies th... | ```cpp
#include <type_traits>
// Define the concept IsArgumentProviderOfExpandables
template <typename T>
concept IsArgumentProviderOfExpandables = requires(T t) {
// Check if T has a member function expand() that returns a sequence of arguments
{ t.expand() } -> std::convertible_to<std::tuple<>>; // Check if... | magicoder | cpp |
You are tasked with implementing a method to delete a product from a database using PHP and Laravel. The method should handle the deletion of the product and return a success message upon successful deletion.
You are given the following code snippet as a starting point:
```php
public function update(EditProductReques... | ```php
public function delete(Request $request)
{
try {
$productId = $request->input('product_id');
$product = Product::find($productId);
if ($product) {
$product->delete();
return redirect()->route('product.index')
->with('msg', 'Xóa sản phẩm... | magicoder | php |
You are tasked with implementing a squeeze-and-excite block, a component commonly used in convolutional neural networks to enhance feature representation. The block consists of two main steps: squeeze and excitation. The squeeze step involves reducing the spatial dimensions of the input tensor to a single vector, while... | ```python
from keras.layers import GlobalAveragePooling2D, Reshape, Dense, multiply
import tensorflow as tf
def squeeze_excite_block(input, ratio=16):
init = input
filters = init.shape[-1] # Obtain the number of filters in the input tensor
se_shape = (1, 1, filters)
se = GlobalAveragePooling2D()(init)... | magicoder | python |
You are tasked with creating a function that processes a list of file paths and returns the count of files with a specific file extension. The function should be able to handle different operating systems and file path formats.
You are given a code snippet that includes a test function for a Windows-specific feature.... | ```rust
#[cfg(feature = "windows")]
#[test]
fn query_test() {
let file_paths = vec![
"C:\\Users\\user\\documents\\file1.txt",
"C:\\Users\\user\\documents\\file2.jpg",
"/home/user/documents/file3.txt",
"/home/user/documents/file4.png",
];
let count = count_files_with_extension... | magicoder | rust |
You are tasked with implementing a simple dependency injection container in Swift. The container should be able to register and resolve dependencies using a protocol-oriented approach.
Your task is to create a `DependencyContainer` class that allows registering and resolving dependencies. The container should support ... | ```swift
protocol Resolvable {
associatedtype ResolvedType
static var instance: ResolvedType { get }
}
class DependencyContainer {
private var dependencies: [String: Any] = [:]
func register<T>(type: T.Type, instance: T) {
let key = "\(T.self)"
dependencies[key] = instance
}
f... | magicoder | swift |
You are tasked with implementing a function to copy a subset of biases from one array to another. The provided code snippet is a partial implementation of the function `copy_biases_linear`, which takes in two arrays `biases` and `biases_local_1`. The function is intended to copy a subset of biases from the `biases` arr... | ```c
void copy_biases_linear(dType_8u *biases, dType_4u *biases_local_1)
{
// Layer 1
for (int idx = 0; idx < t_LAYER_i_LENGTH; idx++)
{
biases_local_1[idx] = biases[idx + t_LAYER_i_OFFSET];
}
}
```
In the solution, the missing part of the code snippet has been completed. The loop iterates over ... | magicoder | c |
You are tasked with implementing a Python class that publishes messages to an MQTT broker using the Paho MQTT client library. The class should handle the connection to the broker and provide a method for publishing messages. Your task is to complete the implementation of the `PublishAction` class by adding the necessar... | ```python
import paho.mqtt.client as paho
class PublishAction(Action):
def __init__(self, config):
super(PublishAction, self).__init__(config)
self._config = config # Corrected variable assignment
self._client = paho.Client() # Initialize the MQTT client
def connect_to_broker(self):... | magicoder | python |
You are tasked with implementing a function that takes in an array of integers and returns the maximum sum of a contiguous subarray within the input array. The function should efficiently handle both positive and negative numbers.
You need to implement the following function:
```php
/**
* Find the maximum sum of a c... | ```php
function maxSubarraySum($nums) {
$maxSum = $nums[0];
$currentSum = $nums[0];
for ($i = 1; $i < count($nums); $i++) {
$currentSum = max($nums[$i], $currentSum + $nums[$i]);
$maxSum = max($maxSum, $currentSum);
}
return $maxSum;
}
```
The solution uses Kadane's algorithm to e... | magicoder | php |
You are tasked with creating a custom Angular directive that will enhance the functionality of buttons in a web application. The directive should be able to handle different button states and styles based on the provided examples.
You are given a code snippet that demonstrates the expected behavior of the directive. T... | ```typescript
import { Directive, ElementRef, Input, Renderer2, OnInit } from '@angular/core';
@Directive({
selector: '[smeButton]'
})
export class SmeButtonDirective implements OnInit {
@Input() disabled: boolean;
constructor(private elementRef: ElementRef, private renderer: Renderer2) {}
ngOnInit() {
t... | magicoder | typescript |
You are working on a project to model the growth and mortality of a specific plant species in a given environment. The project involves analyzing various parameters that influence the plant's survival and growth. One such parameter is the flow velocity of water, which has a significant impact on the plant's mortality r... | ```python
import math
def calculate_mortality_rate(flow_velocity, vel_thres, vel_slope):
if len(vel_thres) != len(vel_slope):
raise ValueError("Length of vel_thres and vel_slope should be the same")
mortality_rate = 1 / (1 + math.exp(-vel_slope[0] * (flow_velocity - vel_thres[0])))
return mortalit... | magicoder | python |
You are tasked with implementing a simple 2D game where a player can move in different directions based on user input. The game uses a camera to control the player's view and movement. The given code snippet is a part of the game's movement logic. The `inputFlags` variable is a bit field representing the user's input, ... | ```python
from typing import Tuple
class Vector2:
def __init__(self, x: float, y: float):
self.x = x
self.y = y
def updatePlayerPosition(inputFlags: int, position: Vector2, cameraLookDirection: Vector2, playerSpeed: float, modifier: float) -> Vector2:
if inputFlags & InputForward:
posi... | magicoder | python |
You are working on a data processing pipeline for a system that collects and analyzes sensor data. The pipeline consists of several scripts that process and store the data. You need to write a script to automate the processing of the collected data.
The provided code snippet is part of a shell script that processes th... | Shell script completion:
```bash
# Process the data
./src/collect.py dat/temp.dat arg1 arg2 # Replace arg1 and arg2 with appropriate arguments
db=$(ls -t json/ | head -2 | tail -1)
echo "Using db $db"
./src/fingerprint.py "json/"$db json/online.json
```
Python function to identify the second most recent JSON file:
``... | magicoder | shell |
You are working on a bioinformatics project and need to implement a method for extracting the 5' to 3' sequence of a transcript. The provided code snippet is part of a larger Python program that defines a model for transcript data and includes a method `get_seq` within the model class. Your task is to implement the `ge... | ```python
from Bio.Seq import Seq
class TranscriptModel:
exons = obj_model.ManyToManyAttribute(ExonLocus, related_name='transcripts')
class Meta(obj_model.Model.Meta):
attribute_order = ('id', 'name', 'rna', 'exons', 'half_life',
'comments', 'references', 'database_referenc... | magicoder | python |
You are tasked with implementing a function that converts a JSON value to an unsigned 64-bit integer. The function should handle different cases and return an error code if the conversion is not possible.
You are given the following code snippet as a starting point:
```rust
Some(obj) => Ok(obj),
None ... | ```rust
use serde_json::Value;
#[derive(Debug)]
enum ErrorCode {
CommonInvalidStructure,
}
pub fn val_to_u64<'a>(val: &'a Value) -> Result<u64, ErrorCode> {
match val {
Value::Number(num) => {
if let Some(uint_val) = num.as_u64() {
Ok(uint_val)
} else {
... | magicoder | rust |
You are tasked with implementing a permission-based filtering system for a file management application. The application has two relevant models: `Folder` and `AccessEntry`. The `Folder` model represents folders in the file system, and the `AccessEntry` model represents access permissions for users on folders. Each `Acc... | ```python
from django.core.exceptions import PermissionDenied
from django.db.models import Q
def filter_objects_by_access(permission, user, queryset):
try:
# Check if the user has the required permission
Permission.objects.check_permissions(user, [permission])
# User has the permission, ret... | magicoder | python |
You are tasked with creating a Python class that acts as an adapter plugin for a data processing framework. The adapter plugin will be responsible for connecting to a specific data source and retrieving data using the provided credentials. Your task is to implement the `AdapterPlugin` class and its associated component... | ```python
class AdapterPlugin:
def __init__(self, adapter, credentials, include_path):
self.adapter = adapter
self.credentials = credentials
self.include_path = include_path
def retrieve_data(self, query):
adapter_instance = self.adapter(self.credentials)
adapter_instanc... | magicoder | python |
You are tasked with creating a Python function to generate a GIF from a series of images. The function should take in a file name prefix and the output file name as parameters. Each image file should be named with the prefix followed by a sequential number (e.g., "image1.png", "image2.png", etc.). The function should t... | ```python
import imageio
import os
def make_gif(fn_prefix, filename):
# Get a list of all files starting with the given prefix
image_files = [f for f in os.listdir() if f.startswith(fn_prefix) and f.endswith('.png')]
# Sort the image files based on the sequential number in the file name
image_file... | magicoder | python |
You are tasked with implementing a Python function that calculates the numerical derivative of a given objective function using the central difference method and then visualizing the results using a logarithmic plot.
Write a function `numerical_derivative_and_plot(obj_func, baseline_objective, epss)` that takes in thr... | ```python
import numpy as np
import matplotlib.pyplot as plt
def numerical_derivative_and_plot(obj_func, baseline_objective, epss):
# Calculate numerical derivative using central difference method
derivs = (obj_func(epss + epss) - obj_func(epss - epss)) / (2 * epss)
# Normalize the derivative values
... | magicoder | python |
You are tasked with creating a Python class that tracks function calls within specified modules. Your class should be able to record the modules and functions called, and provide a summary of the calls made.
Create a Python class `CallTrackerEngine` with the following specifications:
- The class should have an `__init... | ```python
from importlib import import_module
class CallTrackerEngine:
def __init__(self, import_module):
self.imported_module = import_module
def calltrack_module(self, module_name):
module = import_module(module_name)
functions_called = [func for func in dir(module) if callable(getat... | magicoder | python |
You are tasked with implementing a data processing algorithm that involves dividing a large dataset into smaller blocks and performing calculations on each block. The given code snippet is a part of the algorithm and contains some variables and print statements. Your task is to complete the implementation of the algori... | ```python
def calculate_data_range(N_st, N_cut, Nt_block, N_div, Nt_inc):
data_ranges = []
for i in range(N_div):
start_index = N_st + (i * Nt_block)
end_index = min(start_index + Nt_block, N_cut)
data_ranges.append('from %d to %d' % (start_index, end_index))
return data_ranges
# Te... | magicoder | python |
You are working on a Python application that manages event data for a gaming guild. The provided code snippet is part of a class used to create and manipulate event objects. The class has a method to create an event object from a database row, as well as methods to set the actor and count attributes, and to insert the ... | ```python
import datetime
class GuildEvent:
# ... (previous class definition remains the same)
def calculate_duration(self, other_event):
if self.event_type != other_event.event_type:
raise ValueError("Events must be of the same type to calculate duration")
return abs((self.timesta... | magicoder | python |
You are tasked with implementing a custom iterator for a fusion sequence in C++. Fusion is a library for working with heterogeneous sequences, providing a way to manipulate collections of different types in a uniform manner. Your goal is to create a custom iterator that can traverse a fusion sequence in a random-access... | ```cpp
#include <iostream>
#include <boost/fusion/include/vector.hpp>
#include <boost/fusion/iterator/distance.hpp>
#include <boost/fusion/iterator/next.hpp>
#include <boost/fusion/iterator/prior.hpp>
#include <boost/fusion/iterator/value_of.hpp>
#include <boost/fusion/iterator/deref.hpp>
struct custom_iterator : boos... | magicoder | cpp |
You are tasked with implementing a Python class that provides the functionality to fetch the contents of columns of several rows of a ContentResultSet with a single function call. The class should adhere to a specified interface and handle type checking.
Your task is to complete the implementation of the `XFetchProvid... | ```python
from abc import abstractmethod
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .fetch_result import FetchResult as FetchResult_98510aab
from ..uno.x_interface import XInterface as XInterface_8f010a43
class XFetchProvider(XInterface_8f010a43):
"""
provides the possibility to get the conte... | magicoder | python |
You are tasked with creating a C++ class to monitor the CPU utilization of a Linux system. The class should utilize the provided `LinuxParser` class to retrieve the necessary system information. Your task is to implement the `Processor` class with a method `Utilization()` that calculates and returns the aggregate CPU u... | ```cpp
#include "processor.h"
#include "linux_parser.h"
// Return the aggregate CPU utilization
float Processor::Utilization() {
long activeJiffies = LinuxParser::ActiveJiffies();
long totJiffies = LinuxParser::Jiffies();
return float(activeJiffies) / float(totJiffies);
}
```
The `Utilization()` method in the ... | magicoder | cpp |
You are tasked with creating a Python function that processes a list of student scores and returns the top N students based on their average scores. The function should also calculate the overall class average and identify any students who have scored below the class average.
You are given the following code snippet a... | ```python
def top_students(scores, N):
averages = [sum(student) / len(student) for student in scores]
class_average = sum(averages) / len(averages)
below_average = [i for i, avg in enumerate(averages) if avg < class_average]
top_n_students = sorted(enumerate(averages), key=lambda x: x[1], reverse=True)[... | magicoder | python |
You are tasked with implementing a trading algorithm for a cryptocurrency exchange. The algorithm is designed to execute buy orders based on a specified price limit. Your task is to write a function that calculates the volume of the cryptocurrency to be bought based on the given price limit.
You are provided with a co... | ```rust
use rust_decimal::Decimal;
struct Fill {
base_value: Decimal,
quote_value: Decimal,
exhausted: bool,
}
impl Fill {
pub fn ask_volume(&self, price_limit: &Decimal, current_price: &Decimal) -> Fill {
let mut base_value = Decimal::zero();
let mut quote_value = Decimal::zero();
... | magicoder | rust |
You are tasked with creating a Python function that processes a configuration dictionary and performs various operations based on the data provided. The configuration dictionary contains information about machines, runners, features, and users. Your task is to implement a function that takes this configuration dictiona... | ```python
def process_configuration(config, machine):
M = config['Machines']
runner_name = M.get(machine, {}).get('runner')
features = list(map(str.strip, M.get(machine, {}).get('features', '').split(',')))
runner = find_runner(name=runner_name, features=features)
settings = dict(M.get(machine, {}))... | magicoder | python |
You are tasked with creating a Java program that processes a list of imported classes and extracts specific information from them. The program should identify and extract the names of the imported classes from the given code snippet and then display the unique imported class names in alphabetical order.
The given code... | ```java
import java.util.Arrays;
import java.util.TreeSet;
public class ImportedClassExtractor {
public static void main(String[] args) {
String codeSnippet = "import android.view.KeyEvent;\n" +
"import android.Manifest;\n" +
"import com.common.cklibrary.common.BaseActivity;... | magicoder | java |
You are tasked with creating a program that calculates the average of a list of numbers. Your program should take a list of numbers as input and output the calculated average. You should ensure that the average is rounded to two decimal places and displayed with an appropriate message.
Write a Python function `calcula... | ```python
def calculate_average(numbers):
average = sum(numbers) / len(numbers)
average_formatted = "{:.2f}".format(average)
return "Your average is " + average_formatted
```
The `calculate_average` function takes a list of numbers as input and calculates the average by summing all the numbers and dividing ... | magicoder | python |
You are tasked with creating a Python module that simulates a simple banking system. The module should include a class `BankAccount` with the following functionalities:
- Initialize a bank account with a given account number and initial balance.
- Deposit funds into the account.
- Withdraw funds from the account.
- Che... | ```python
# realUser.py
class RealUser:
def authenticate_user(self, username, password):
# Implementation to authenticate a real user
pass
# bank_account.py
from .realUser import RealUser
class BankAccount:
def __init__(self, account_number, initial_balance):
self.account_number = acco... | magicoder | python |
You are tasked with creating a program that generates test data for a fictional online shopping platform. The test data should include information about products, such as their names, prices, and categories. Additionally, the program should be able to generate data for multiple users, including their names, email addre... | ```python
import random
import json
import argparse
# Predefined lists for generating random data
adjectives = ['Sleek', 'Elegant', 'Stylish', 'Modern', 'Charming', 'Luxurious']
nouns = ['Chair', 'Table', 'Lamp', 'Sofa', 'Bed', 'Desk']
categories = ['Furniture', 'Electronics', 'Clothing', 'Appliances', 'Books']
first... | magicoder | python |
You are tasked with creating a test case for a mobile application using XCTest, Apple's testing framework for iOS applications. The application has a feature that allows users to log in with their credentials. Your goal is to write a test case that verifies the login functionality of the application.
The code snippet ... | ```swift
func testLogin() {
let app = XCUIApplication()
app.launch()
// Enter valid login credentials
let usernameTextField = app.textFields["usernameTextField"]
let passwordTextField = app.secureTextFields["passwordTextField"]
usernameTextField.tap()
usernameTextField.typeText("exampleUser... | magicoder | swift |
You are tasked with writing a script to automate the creation of a cluster and partition in a distributed computing environment. The script should use the provided list of agents and execute specific commands to set up the cluster and partition.
Given the following code snippet as inspiration:
```bash
AGENTS2="ag.14.... | ```bash
#!/bin/bash
# Concatenate the provided list of agents with an existing list of agents
AGENTS2="ag.14.01,ag.14.02,ag.14.03,ag.14.04,ag.14.05,ag.14.06,ag.14.07,ag.14.08,ag.14.09,ag.14.14,ag.14.11,ag.14.12,ag.14.13,ag.14.14,ag.14.15,ag.14.16"
AGENTS1="ag.13.01,ag.13.02,ag.13.03" # Example existing list of agents... | magicoder | shell |
You are given a snippet of code that is part of a larger program. The variable `cleared` is being incremented by 1 within a loop. Your task is to write a function that takes an integer `n` as input and returns the value of `cleared` after `n` iterations of the loop.
Write a function `calculateClearedValue(n: int) -> i... | ```python
def calculateClearedValue(n: int) -> int:
cleared = 0
for _ in range(n):
cleared += 1
return cleared
```
The function `calculateClearedValue` initializes the variable `cleared` to 0 and then iterates `n` times, incrementing `cleared` by 1 in each iteration. Finally, it returns the value o... | magicoder | python |
You are given a snippet of code that reads from an input file to create a collection of particles. Each particle has a position (x, y) and a velocity (vx, vy). Your task is to write a program that processes the input file and calculates the final positions of the particles after a given number of steps.
The input file... | ```cpp
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
struct Particle {
int x, y, vx, vy;
void step() {
x += vx;
y += vy;
}
};
int main(int argc, char** argv) {
if (argc < 3) {
std::cout << "usage: " << argv[0] << " <input_file> <... | magicoder | cpp |
You are tasked with implementing a function to parse and process file paths related to Python package distributions. The function should extract specific information from the file path and handle exceptions as specified.
You are given a code snippet that includes a function `substitute(target_relpath)` and a set `EXCE... | ```python
import os.path
from pkg_resources import safe_name
EXCEPTIONS = {'datadog_checks_base', 'datadog_checks_dev', 'datadog_checks_downloader'}
def substitute(target_relpath):
filename = os.path.basename(target_relpath)
name, ext = os.path.splitext(filename)
wheel_distribution_name, package_version... | magicoder | python |
You are working on a computer vision project and need to implement data augmentation using the Albumentations library in Python. Your task is to create a function that applies a series of image transformations to a given dataset using Albumentations and then converts the augmented images to PyTorch tensors.
You are pr... | ```python
import albumentations as A
from albumentations.pytorch import ToTensorV2
import torch
from torch.utils.data import DataLoader, Dataset
from typing import List, Union
def apply_augmentation(dataset: List[Union[str, bytes]], image_size: int, batch_size: int) -> DataLoader:
# Define image augmentation trans... | magicoder | python |
You are tasked with implementing a validation system for a key-value pair data structure. The system should enforce specific rules for the key and value fields. The rules are defined in an associative array where the key represents the field name and the value represents the validation rule.
Your task is to write a fu... | ```php
protected $rules = [
'key' => 'required',
'value' => 'required',
// Additional validation rules may be present
];
function validateKeyValuePair($pair) {
foreach ($this->rules as $field => $rule) {
if ($rule === 'required' && !array_key_exists($field, $pair)) {
return false;... | magicoder | php |
You are tasked with implementing a change detection algorithm for a data stream. The Adaptive Windowing (ADWIN) algorithm is a popular method for detecting changes in data streams. The ADWIN algorithm dynamically adjusts the window size to adapt to changes in the data distribution. Your task is to implement the ADWIN a... | ```python
import numpy as np
class ADWIN:
def __init__(self, delta=0.002):
self.delta = delta
self.width = 0
self.bucket1 = []
self.bucket2 = []
self.total = 0
self.variance = 0
def add_element(self, element):
self.total += 1
if self.width == 0:
... | magicoder | python |
You are tasked with implementing a simple factory pattern in C++ to create instances of different Lua objects. The Lua objects are defined by a base class `LuaObject` and two derived classes `LuaNumber` and `LuaString`. Your goal is to create a `LuaFactory` class that can produce instances of these Lua objects based on... | ```cpp
#include <iostream>
#include <memory>
#include <string>
class LuaObject {
public:
virtual void printType() = 0;
};
class LuaNumber : public LuaObject {
public:
void printType() override {
std::cout << "LuaNumber" << std::endl;
}
};
class LuaString : public LuaObject {
public:
void prin... | magicoder | cpp |
You are tasked with implementing a WebSocket server that authenticates incoming connections using an authentication token and manages session tokens for each connected client. The server should use the `aioredis` library to interact with a Redis database for token validation and session management. Additionally, the se... | ```python
import logging
import urllib.parse
import aioredis
import websockets
from joust import redis
logger: logging.Logger = logging.getLogger(__name__)
class ServerProtocol(websockets.WebSocketServerProtocol):
auth_token: str
session_token: str
async def process_request(self, path, request_headers):... | magicoder | python |
You are tasked with simulating the behavior of a user interface (UI) event handler in a hypothetical application. The application has a set of UI events, each associated with a specific action to be performed when triggered. Your goal is to implement a program that can execute the corresponding action for a given UI ev... | ```python
class UIEventHandler:
def on_copyAddress_clicked(self):
# Implement action for on_copyAddress_clicked event
print("Copy address action executed")
def on_signMessage_clicked(self):
# Implement action for on_signMessage_clicked event
print("Sign message action executed")... | magicoder | python |
You are tasked with creating a Python function that reads a YAML configuration file, updates the logging configuration based on the contents of the file, and then starts a server. Your task is to complete the implementation of the `load_cfg` function, which should read the YAML configuration file and return its content... | ```python
import logging
import logging.config
import yaml
import shutil
logging_cfg_path = 'path_to_logging_config.yaml'
def load_cfg():
with open(logging_cfg_path, 'r') as f:
return yaml.safe_load(f)
def serve_zveronics(ip, port):
# Implementation of serve_zveronics function is not provided
pas... | magicoder | python |
You are tasked with creating a script to automate the login process for a web application using the `curl` command-line tool. The script should extract the CSRF token and session ID from the HTTP response headers and store them in environment variables for subsequent requests. The script should also securely handle the... | The script can be completed by using the `read` command to securely prompt the user for the password and then passing it to the web application. Additionally, error handling and cleanup operations should be included. Below is the completed script:
```bash
#!/bin/bash
# Prompt user for password securely
read -s -p "En... | magicoder | shell |
You are tasked with implementing a custom `to_string` function in C++ that converts various types of integers to their string representations. The provided code snippet shows the initial implementation of the `to_string` function for `int`, `unsigned int`, and `long` types. Your task is to extend this implementation to... | ```cpp
#include <string>
#include <cstdio>
template <typename T>
std::string to_string(T Val) {
char buf[32]; // Assuming a maximum of 32 characters for the string representation
if constexpr (std::is_same_v<T, int>) {
sprintf_s(buf, sizeof(buf), "%i", Val);
} else if constexpr (std::is_same_v<T, u... | magicoder | cpp |
You are tasked with implementing a custom UITableViewCell subclass to display the status of a task. The status is represented by an enum called `StatusColor`, which contains cases for different task statuses: `inProgress`, `success`, `aborted`, `error`, and `onHold`. Each status has a corresponding color associated wit... | ```swift
import UIKit
final class BuildCell: UITableViewCell {
enum StatusColor: String {
case inProgress = "in-progress"
case success = "success"
case aborted = "aborted"
case error = "error"
case onHold = "on-hold"
}
func colorForStatus(_ status: StatusColor) -> ... | magicoder | swift |
You are tasked with implementing a custom hook in a React application that fetches network data based on a specified chain. The hook should utilize the `useMemo` hook to efficiently retrieve the network data and return the result for further processing.
Your task is to create a custom hook called `useNetworkData` that... | ```javascript
import { useMemo } from 'react';
import BridgeDictionary from 'your-bridge-dictionary-path'; // Replace with the actual path
const useNetworkData = (chain) => {
const networkData = useMemo(
() =>
BridgeDictionary.listNetworks().find(
(item) => item.chain === chain
) as NetworkMo... | magicoder | javascript |
You are tasked with implementing a program to perform K-means clustering on a given dataset using the `sklearn` library in Python. K-means clustering is a popular unsupervised machine learning algorithm used for partitioning a dataset into a set of clusters. The algorithm aims to minimize the sum of squared distances b... | ```python
from sklearn.cluster import KMeans
import numpy as np
from pandas import DataFrame
def perform_kmeans_clustering(dataset: DataFrame, num_clusters: int) -> np.ndarray:
kmeans = KMeans(n_clusters=num_clusters, random_state=0)
cluster_labels = kmeans.fit_predict(dataset)
return cluster_labels
```
T... | magicoder | python |
You are tasked with creating a program that processes data from a JSON file and uses the Picasso library to load and display images in a user interface. The program should read a JSON file containing information about different images, including their URLs and titles. It should then use the Gson library to parse the JS... | ```java
import com.google.gson.Gson;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import javax.swing.*;
import java.awt.*;
import java.io.FileReader;
import java.io.IOException;
public class ImageDisplayApp {
public static void main(String[] args) {
try {
// Read t... | magicoder | java |
You are tasked with implementing a method to traverse a tree structure and collect all the "use boxes" associated with a given base box. Each box in the tree structure has a value and may have child boxes. The goal is to create a method that returns a list of all the use boxes related to the given base box.
You are gi... | ```java
public List<Box> getUseBoxes() {
List<Box> useBoxes = new ArrayList<>();
Set<Box> visited = new HashSet<>();
collectUseBoxes(this, useBoxes, visited);
return useBoxes;
}
private void collectUseBoxes(Box currentBox, List<Box> useBoxes, Set<Box> visited) {
if (currentBox == null || visited.contains(cur... | magicoder | java |
You are given a Swift code snippet that involves the creation and comparison of `Line` objects. The `Line` class represents a line segment in a 2D coordinate system and is defined by two `CGPoint` objects. The snippet also includes the testing of equality and inequality of these `Line` objects using the `XCTAssert` fun... | ```swift
// Line class definition
class Line: Equatable {
let startPoint: CGPoint
let endPoint: CGPoint
init(_ startPoint: CGPoint, _ endPoint: CGPoint) {
self.startPoint = startPoint
self.endPoint = endPoint
}
static func == (lhs: Line, rhs: Line) -> Bool {
return ... | magicoder | swift |
You are tasked with creating a program that parses and extracts information from HTML code. Specifically, you need to extract the labels and their corresponding attributes from the given HTML snippet.
Write a function `extractLabels` that takes a string representing the HTML code as input and returns a dictionary wher... | ```python
import re
def extractLabels(html_code):
label_pattern = r'<label\s+([^>]+)>([^<]+)</label>'
labels = re.findall(label_pattern, html_code)
label_attributes = {}
for attributes, label in labels:
attribute_str = ' '.join(attributes.split())
label_attributes[label.strip()] = attri... | magicoder | python |
You are tasked with implementing a custom error handling mechanism for a Rust program. The program uses the `DecodePartial` trait to decode data structures, and the `DecodeError` type represents errors that can occur during decoding. The `DecodePartial` trait provides methods for inserting child nodes and properties in... | ```rust
use std::rc::Rc;
// Define the custom error type for decoding errors
struct DecodeError;
// Define the trait for error spans
trait ErrorSpan {}
// Define the trait for decoding partial data structures
trait DecodePartial<S: ErrorSpan> {
fn insert_child(&mut self, node: &SpannedNode<S>, ctx: &mut Context<... | magicoder | rust |
You are tasked with implementing a pagination algorithm for a web application that displays a list of orders. The provided code snippet is a part of the pagination logic and contains some incomplete parts. Your task is to complete the pagination logic based on the given code and requirements.
The code snippet is part ... | ```csharp
// Complete the pagination logic
if (Page < TotalPages)
NextPage = Page + 1;
if (Page >= TotalPages)
NextPage = null;
// Return the completed pagination information
return new PaginationResult
{
RecordsPerPage = RecordsPerPage,
TotalRecords = TotalRecords,
TotalPages = TotalPages,
Ord... | magicoder | csharp |
You are tasked with implementing a login system that interacts with an API service, a mailer, a tracking server, and Google authentication. The code snippet provided initializes various components required for the login system. Your task is to design and implement the `LoginSystem` class, along with the necessary mock ... | ```javascript
class LoginSystem {
constructor(apiService, mailer, trackingServer, googleAuth) {
this.apiService = apiService;
this.mailer = mailer;
this.trackingServer = trackingServer;
this.googleAuth = googleAuth;
}
authenticateUserWithGoogle(token) {
// Use Google authentication to verify ... | magicoder | javascript |
You are given a code snippet that processes and writes out macro definitions for a set of variables. Your task is to write a Python function that takes the input data and generates the corresponding macro definitions as output.
The input data consists of three lists: `gl`, `wgl`, and `glX`. Each list contains sublists... | ```python
def generate_macros(gl, wgl, glX):
macro_definitions = []
# Write out the end indices for gl, wgl, and glX
macro_definitions.append('define(`gl_end`, `%d`)' % (len(gl) - 1))
macro_definitions.append('define(`wgl_start`, `%d`)' % len(gl))
macro_definitions.append('define(`wgl_end`, `%d`)' ... | magicoder | python |
You are working on a file management system for a code grading platform. The system uses environment variables to store various file paths and directories. The code snippet provided sets up several environment variables related to file management.
Your task is to write a function that takes a file name as input and re... | ```javascript
function getFilePath(fileName) {
const rootDir = process.env.CG_FILES_DIR;
const problemsDir = process.env.CG_FILES_PROBLEMS;
const problemsTmpDir = process.env.CG_FILES_PROBLEMS_TMP;
const testcasesDir = process.env.CG_FILES_TESTCASES;
const testcasesSolDir = process.env.CG_FILES_TESTCASES_SOL;... | magicoder | javascript |
You are tasked with implementing a queue data structure in TypeScript. The queue should have the following functionalities:
1. `enqueue(item: T): void` - Add an item to the end of the queue.
2. `dequeue(): T | undefined` - Remove and return the item at the front of the queue.
3. `peek(): T | undefined` - Return the ite... | ```typescript
export class Queue<T> {
private items: T[];
constructor() {
this.items = [];
}
enqueue(item: T): void {
this.items.push(item);
}
dequeue(): T | undefined {
return this.items.shift();
}
peek(): T | undefined {
return this.items[0];
}
isEmpty(): boolean {
return ... | magicoder | typescript |
You are tasked with implementing a simple mutex using the HIP (Heterogeneous-Compute Interface for Portability) runtime library for GPU programming. The HIP runtime library provides a set of functions for managing memory, launching kernels, and synchronizing between the host and the GPU.
Your task is to implement a de... | ```cpp
#ifndef ROCSHMEM_LIBRARY_SRC_DEVICE_MUTEX_HPP
#define ROCSHMEM_LIBRARY_SRC_DEVICE_MUTEX_HPP
#include <hip/hip_runtime.h>
class DeviceMutex {
public:
__device__ DeviceMutex() : locked(false) {}
__device__ void lock() {
while (atomicCAS(&locked, 0, 1) != 0) {
// Spin until the mutex ... | magicoder | cpp |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.