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 process point cloud data. The function takes in a vector of point cloud data and performs a series of operations on it. The point cloud data is represented as a vector of points, and each point is represented by its coordinates in 3D space. Additionally, the function maint... | ```cpp
#include <iostream>
#include <vector>
#include <Eigen/Dense>
// Define the PointCloud type
typedef std::vector<Eigen::Vector3f> PointCloud;
typedef std::shared_ptr<PointCloud> PointCloudPtr;
// Define the processPointCloud function
PointCloudPtr processPointCloud(const std::vector<Eigen::Vector3f>& data, std::... | magicoder | cpp |
You are tasked with creating a Python function that simulates the behavior of the `pkg_config` function in a build system. The `pkg_config` function is responsible for retrieving and processing configuration information for a specified package using the `pkg-config` tool. The provided code snippet demonstrates a simpli... | ```python
import os
import subprocess
import re
def simulate_pkg_config(package_name):
# Create a copy of the current environment
my_env = os.environ.copy()
# Set the PKG_CONFIG_PATH environment variable for Windows variant
if variant == 'windows':
my_env['PKG_CONFIG_PATH'] = '/tmp/gtk_downloa... | magicoder | python |
You are given a 2D array representing a grid of points. Each point is represented by its x and y coordinates. Your task is to write a function that takes this 2D array as input and returns a new 2D array containing the distances of each point from the origin (0, 0). The distance of a point (x, y) from the origin is giv... | ```python
import math
def calculateDistances(points):
distances = []
for point in points:
x, y = point
distance = math.sqrt(x**2 + y**2)
distances.append([round(distance, 15), round(distance, 15)]) # Rounding to 15 decimal places
return distances
# Test the function with the given... | magicoder | python |
You are tasked with implementing a version control system that tracks changes made to files in a directory. The system should be able to handle adding new files, modifying existing files, and displaying a summary of the changes made.
You are given a code snippet that represents the output of the version control system... | ```python
def process_version_control_output(output: str) -> str:
added_files = []
modified_files = []
renamed_files = []
deleted_files = []
untracked_files = []
operations = output.split(', ')
for operation in operations:
if operation.startswith('added'):
added_files.ap... | magicoder | python |
You are tasked with implementing a Variational Autoencoder (VAE) oversampler to address class imbalance in a dataset. The VAE oversampler will generate synthetic samples for the minority class by learning the underlying data distribution and sampling from it. The code snippet provided initializes the VAE oversampler an... | ```python
from keras.layers import Input, Dense, Lambda
from keras.models import Model
from keras import backend as K
from keras import objectives
from keras import optimizers
class VAEOversampler:
def __init__(self, epochs):
self.epochs = epochs
self.batch_size = 100
self.latent_dim = 2 #... | magicoder | python |
You are tasked with implementing a cryptographic hash function using the SHA-256 algorithm. The SHA-256 algorithm takes an input message and produces a 256-bit (32-byte) hash value. In this problem, you will need to implement the `update` and `finalize_reset` methods for the SHA-256 hash function.
The `update` method ... | ```rust
use sha2::{Digest, Sha256};
use generic_array::GenericArray;
struct MySha256 {
state: Sha256,
}
impl MySha256 {
fn new() -> Self {
MySha256 {
state: Sha256::new(),
}
}
#[inline]
fn update(&mut self, data: impl AsRef<[u8]>) {
self.state.update(data);
... | magicoder | rust |
You are tasked with implementing a resource management system for a graphics application. The system should handle the creation and destruction of image objects and their associated image views. An image view is a resource that provides a way to interpret the data in an image's memory according to a specific format, as... | ```cpp
class Image {
public:
void destroy() {
// Implementation for destroying the image
}
};
class ImageView {
public:
void destroy() {
// Implementation for destroying the image view
}
};
class Sampler {
public:
bool create() {
// Implementation for creating the sampler
... | magicoder | cpp |
You are given an array A of integers. Your task is to find the sum of bitwise XOR operations between all pairs of distinct elements in A, multiplied by the frequency of each element in the array.
Write a function `xor_sum_with_frequency(A)` that takes in an array of integers A and returns the sum as described above.
... | ```python
def xor_sum_with_frequency(A):
o = {}
for a in A:
o.setdefault(a, 0)
o[a] += 1
ans = 0
for i in range(len(A)-1):
for j in range(i+1, len(A)):
ans += (A[i] ^ A[j]) * o[A[i]] * o[A[j]]
return ans
```
The function `xor_sum_with_frequency` first c... | magicoder | python |
You are tasked with implementing a caching mechanism for storing proposals and trial results to facilitate communication between an advisor and train workers. The provided code snippet includes a partial implementation of a `TrainCache` class, which is responsible for managing the caching functionality. Your task is to... | ```python
import logging
from singa_auto.advisor import Proposal, TrialResult
from .redis import RedisSession
logger = logging.getLogger(__name__)
REDIS_NAMESPACE = 'TRAIN'
class TrainCache(object):
def __init__(self):
self._redis_session = RedisSession()
def cache_proposal(self, key, proposal):
... | magicoder | python |
You are tasked with implementing a Python function that simulates a simple text-based game. The game involves navigating through a grid-based world, collecting treasures, and avoiding obstacles. The game world is represented as a 2D grid, where each cell can be either empty, contain a treasure, or be blocked by an obst... | ```python
def play_game(grid, start, moves):
rows, cols = len(grid), len(grid[0])
directions = {'U': (-1, 0), 'D': (1, 0), 'L': (0, -1), 'R': (0, 1)}
treasures_collected = 0
current_position = start
for move in moves:
new_row = current_position[0] + directions[move][0]
new_col = cur... | magicoder | python |
You are tasked with creating a shell script that checks for the existence of certain commands and prints the current shell being used. Your script should perform the following tasks:
1. Print the current shell being used by the script.
2. Check if the command "brew" exists and print "yes" if it does, otherwise print "... | ```bash
#!/bin/bash
# Print the current shell being used
echo "The current shell is: $(ps $$ -ocomm=)"
# Check if the command "brew" exists and print "yes" if it does, otherwise print "no"
if command -v brew &> /dev/null
then
echo "yes"
else
echo "no"
fi
# Use the "which" command to check if the command "exi... | magicoder | shell |
You are tasked with implementing a function that calculates the total area of a series of rectangles in a 2D plane. Each rectangle is represented by its top-left and bottom-right coordinates. The total area is the sum of the individual areas of the rectangles, excluding any overlapping regions.
You are given the follo... | ```swift
func calculateTotalAreaOfRectangles(rectangles: [(topLeft: (x1: Int, y1: Int), bottomRight: (x2: Int, y2: Int))]) -> Int {
var totalArea = 0
for i in 0..<rectangles.count {
let rect1 = rectangles[i]
totalArea += (rect1.bottomRight.x2 - rect1.topLeft.x1) * (rect1.topLeft.y1 - rect1.... | magicoder | swift |
You are working on a computer vision project that involves detecting vanishing points in images. A vanishing point is a point in the image plane where parallel lines appear to converge. Your task is to implement a function that measures the error in the number of detected vanishing points compared to the ground truth v... | ```python
import math
def num_model_detection_error(ground_truth_vps, detected_vps):
seen_gt_vps = set()
seen_dt_vps = set()
total_error = 0
for gt_vp, dt_vp in zip(ground_truth_vps, detected_vps):
distance = math.sqrt((dt_vp[0] - gt_vp[0])**2 + (dt_vp[1] - gt_vp[1])**2)
if gt_vp in se... | magicoder | python |
You are tasked with implementing a function that calculates the median of a given array of integers. The median of a set of numbers is the middle number when the numbers are ordered from least to greatest. If the set contains an odd number of elements, the median is the middle number. If the set contains an even number... | ```cpp
#include <algorithm>
int calculateMedian(int arr[], int size) {
std::sort(arr, arr + size); // Sort the array in ascending order
if (size % 2 == 0) {
// If the size of the array is even, return the average of the two middle elements
return (arr[size / 2 - 1] + arr[size / 2]) / 2;
}... | magicoder | cpp |
You are working on a Discord bot that needs to handle various permissions for different actions. The permissions are represented as powers of 2 in a string format. For example, "536870912" represents the permission to manage webhooks, "1073741824" represents the permission to manage emojis and stickers, and so on.
You... | ```python
def decodePermissions(permissionSum):
permissions = {
"MANAGE_WEBHOOKS": "536870912",
"MANAGE_EMOJIS_AND_STICKERS": "1073741824",
"USE_APPLICATION_COMMANDS": "2147483648",
"REQUEST_TO_SPEAK": "4294967296",
"MANAGE_THREADS": "17179869184",
"CREATE_PUBLIC_THRE... | magicoder | python |
You are tasked with troubleshooting a Python code snippet that utilizes the PyObjCTools library to test the creation of an NSHost object. The code snippet is part of a test case for the NSHost class and attempts to create an NSHost object using the hostWithAddress_ method. However, the code raises an exception on GNUst... | The exception "Foundation.NSRecursiveLockException - unlock: failed to unlock mutex" suggests that there might be a threading issue related to the use of locks or mutexes in the PyObjCTools library. To resolve this issue, it is important to ensure that the NSHost creation operation is thread-safe and does not lead to r... | magicoder | python |
You are tasked with implementing a function that processes a list of integers and returns the count of unique numbers in the list. A unique number is one that appears only once in the list. You need to write a Python function `count_unique_numbers` that takes a list of integers as input and returns the count of unique ... | ```python
from typing import List
def count_unique_numbers(nums: List[int]) -> int:
num_count = {}
for num in nums:
if num in num_count:
num_count[num] += 1
else:
num_count[num] = 1
unique_count = 0
for count in num_count.values():
if count == 1:
... | magicoder | python |
You are tasked with implementing a program to find the extreme points of the convex hull of a set of 2D points. The convex hull of a set of points is the smallest convex polygon that contains all the points. Extreme points are the points on the convex hull that define its shape.
Write a function `findExtremePoints` th... | ```python
def orientation(p, q, r):
val = (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1])
if val == 0:
return 0 # collinear
return 1 if val > 0 else 2 # 1 for clockwise, 2 for counterclockwise
def findExtremePoints(points):
n = len(points)
if n < 3:
return points
... | magicoder | python |
You are tasked with creating a Rust program to manage a simple library system. The library system should allow users to add, remove, and search for books in the library. Each book has a title, author, and unique ISBN (International Standard Book Number). Additionally, the program should be able to display all the books... | ```rust
// Define the Book struct
struct Book {
title: String,
author: String,
isbn: u32,
}
// Define the Library struct
struct Library {
books: Vec<Book>,
}
impl Library {
// Constructor method to create a new library
fn new() -> Library {
Library { books: Vec::new() }
}
// M... | magicoder | rust |
You are tasked with simulating the behavior of a PCA9633 LED driver in a simplified setting. The PCA9633 is a 4-channel constant-current LED driver with an I2C-bus interface. The provided code snippet demonstrates the configuration of the PCA9633 to control LED outputs. Your task is to implement a program that emulates... | ```rust
// Define the LED output modes
enum LedOut {
Pwm,
PwmGroup,
}
// Define the LED channels
enum Channels4 {
_1,
_2,
_3,
_4,
}
struct Pca9633 {
// Simulated LED states
led_states: [u8; 4],
// Simulated PWM values
pwm_values: [u8; 4],
}
impl Pca9633 {
fn new() -> Pca96... | magicoder | rust |
You are tasked with creating a Rust module that interfaces with a CUDA library to perform parallel computations on a GPU. Your goal is to implement a function that calculates the sum of elements in an array using CUDA parallel processing. The provided code snippet includes the module structure and external crate declar... | ```rust
// cuda_impl.rs
use ptx::cuda;
pub fn sum_array_with_cuda(input: &[i32]) -> i32 {
// Allocate device memory for input array
let device_input = cuda::allocate_device_memory(input.len() * std::mem::size_of::<i32>());
// Copy input array to device memory
cuda::copy_to_device(device_input, inp... | magicoder | rust |
You are tasked with implementing a role-based access control system for a user management module in a web application. The system should allow assigning roles to users and enrolling them in specific roles. The code snippet provided demonstrates the usage of a `User` class with methods `assignRole` and `assignEnrolment`... | ```php
class User {
const ROLE_TEACHER = 'teacher';
private $roles = [];
public static function assignRole(User $user, $role) {
$user->addRole($role);
}
public static function assignEnrolment(User $user, $role) {
$user->enroll($role);
}
public function save() {
// ... | magicoder | php |
You are tasked with implementing a custom indicator system for loading images in a SwiftUI-based application. The provided code snippet includes two methods for associating indicators with image loading. Your task is to create a custom IndicatorViewModifier and Indicator structure to support this functionality.
Your c... | ```swift
// Custom Indicator structure
struct Indicator<T: View> {
var content: (_ isAnimating: Binding<Bool>, _ progress: Binding<Double>) -> T
}
// Custom IndicatorViewModifier
struct IndicatorViewModifier<T: View>: ViewModifier {
@Binding var reporter: Bool
var indicator: Indicator<T>
func body... | magicoder | swift |
You are tasked with implementing a DHCP port creation event handler for a networking application. The application uses a testing framework with the following code snippet as a part of its test suite:
```python
self.assertTrue(isinstance(self.mech.dhcp_driver, odl_dhcp_driver.OdlDhcpDriver))
def test_dhcp_port_create_... | ```python
def create_dhcp_port_on_subnet_event(subnet_info):
# Check if the subnet information is valid
if not subnet_info:
raise ValueError("Invalid subnet information provided")
# Extract necessary details from the subnet_info (e.g., subnet ID, network ID, etc.)
subnet_id = subnet_info.get('i... | magicoder | python |
You are tasked with implementing a neural network training framework that supports various types of optimizers. The framework consists of layers, optimizers, and a composite optimizer that can combine multiple individual optimizers. Your goal is to implement a method to test the behavior of the composite optimizer.
Yo... | ```python
import unittest
from your_neural_network_module import layers, optimizer, composite_optimizer
class TestCompositeOptimizer(unittest.TestCase):
def testCompositeOptimizerRaises(self):
# Instantiate a composite optimizer
composite_opt = composite_optimizer.CompositeOptimizer()
# A... | magicoder | python |
You are tasked with implementing a real-time image segmentation feature in an iOS app using the AVFoundation and Vision frameworks. The goal is to create an ImageSegmentationViewController that can segment objects in a live camera feed and display the segmented results on the screen.
Your task is to complete the imple... | ```swift
import UIKit
import AVFoundation
import Vision
class ImageSegmentationViewController: UIViewController, AVCaptureVideoDataOutputSampleBufferDelegate {
private var captureSession: AVCaptureSession!
private var videoOutput: AVCaptureVideoDataOutput!
private var videoPreviewLayer: AVCaptureVideoPrevi... | magicoder | swift |
You are tasked with implementing a Python class that dynamically creates instances of other classes based on a list of module class names and a dictionary of arguments. Your goal is to create an `InstanceFactory` class with an `__init__` method that takes in a list of module class names, a dictionary of arguments, and ... | ```python
class InstanceFactory:
def __init__(self, module_class_list, args_dict, **kwargs):
self.instances = {}
for module_class in module_class_list:
module = __import__(module_class)
class_ = getattr(module, module_class)
instance = class_(**args_dict.get(modul... | magicoder | python |
You are tasked with implementing a simple image annotation tool using Python and Streamlit. The provided code snippet initializes the necessary session state variables and defines a function for annotating images. Your task is to complete the implementation by creating a Streamlit web application that allows users to a... | ```python
import streamlit as st
import random
# Initialize session state variables
if 'annotations' not in st.session_state:
st.session_state.annotations = {}
if 'files' not in st.session_state:
st.session_state.files = ["cat.1.jpg", "dog.1.jpg", "bird.1.jpg"] # Replace with actual image file names
if 'curre... | magicoder | python |
You are tasked with creating a Python class that manages and enforces quotas for various resources in a cloud computing environment. The class should be able to set, retrieve, and update quotas for different resources such as CPU, memory, storage, and network bandwidth.
Your task is to implement the `Quota` class, whi... | ```python
from openstack import resource
from otcextensions.sdk import quotamixin
class Quota(quotamixin.QuotaProxyMixin, resource.Resource):
def __init__(self, *args, **kwargs):
super(Quota, self).__init__(*args, **kwargs)
def set_quota(self, resource_type, limit):
# Set the quota limit for t... | magicoder | python |
You are working on a project that involves building a microservices architecture using Python. As part of this project, you need to implement a service that interacts with a service registry to discover available data services and then make HTTP requests to these services. Your task is to write a Python class that acco... | ```python
import cherrypy
import requests
from CommunicationLayer import ServiceRegistry
class ImageAPI(object):
address = "http://127.0.0.1:8761/"
@cherrypy.popargs('imageName')
@cherrypy.expose()
def index(self, imageName):
# Get data centers
servicesArray = ServiceRegistry.getServi... | magicoder | python |
You are tasked with implementing a function that calculates the total number of unique ways to climb a staircase. You are given a positive integer n, which represents the total number of steps in the staircase. You can climb either 1 or 2 steps at a time. Your function should return the total number of unique ways to r... | ```python
def climbStairs(n: int) -> int:
if n == 1:
return 1
elif n == 2:
return 2
else:
first = 1
second = 2
for i in range(3, n+1):
current = first + second
first = second
second = current
return second
```
The `climbStai... | magicoder | python |
You are tasked with creating a Python script that automates the packaging and deployment process for a Python application called "wavespy." The script should perform the following tasks:
1. Build a Debian package (.deb) for the "wavespy" application using the provided setup.py file and move the resulting .deb file to ... | ```python
import os
NAME = "wavespy"
VERSION = "0.1"
# Task 1: Build Debian package for "wavespy" application using setup.py
os.system("#fpm --python-bin python3 --python-pip pip3 --python-package-name-prefix 'python36' --python-obey-requirements-txt -s python -t deb ./setup.py && mv *.deb /result/")
# Task 2: Creat... | magicoder | python |
You are working on a machine learning project and have been tasked with testing a neural network dataset builder. The code snippet provided is a part of the unit test for the dataset builder. The `trainer` object has a method `build_dataset` that returns a `LanguageDataset` object. The `neural_dataset` is then used to ... | ```python
class Trainer:
def build_dataset(self, override_targets: bool) -> LanguageDataset:
# Implementation of build_dataset method
pass # Placeholder for the implementation
class LanguageDataset:
def build(self, example_set: str) -> List[Tuple[List[List[List[int]]], List[Tuple[int, int]]]]... | magicoder | python |
You are tasked with creating a program that simulates a simplified version of the Git version control system. Your program should implement a subset of Git commands to manage a local repository. Specifically, you need to handle the following commands: `git pull`, `git push`, and `git merge`.
Your program should mainta... | ```python
class GitRepository:
def __init__(self):
self.master_branch = []
self.gh_pages_branch = []
def git_pull(self):
# Simulate pulling changes from the remote repository
# Update the local branches with changes from the remote repository
pass
def git_push(self)... | magicoder | python |
You are tasked with implementing a C++ program that manages a library system. The program should utilize various classes from different libraries to create a cohesive system for managing books and patrons.
You are provided with the following code snippet as a starting point:
```cpp
#include "class_7.h"
#include <lib_... | ```cpp
#include <iostream>
#include <string>
#include <vector>
// Book class
class Book {
public:
std::string title;
std::string author;
std::string ISBN;
bool available;
void checkOut() {
if (available) {
available = false;
std::cout << "Book checked out successful... | magicoder | cpp |
You are given an array `c` of `n` integers. Your task is to create two new arrays `ab` and `bc` of the same size `n`, where `ab[i]` is the product of the first `i` elements of array `c`, and `bc[i]` is the product of the last `n-i` elements of array `c`.
You need to implement a function `calculateProducts` that takes ... | ```cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long ll;
pair<vector<ll>, vector<ll>> calculateProducts(vector<ll> c) {
int n = c.size();
vector<ll> ab(n);
vector<ll> bc(n);
ab[0] = 1;
bc[n-1] = 1;
for (int i = 1; i < n; ++i) {
ab[i... | magicoder | cpp |
You are tasked with implementing a neural network layer in Python using the PyTorch library. The given code snippet is a part of a neural network class that defines a forward pass through the network. The network consists of at least two layers, each followed by an activation function. The first layer is defined by a l... | ```python
import torch
class NeuralNetwork(torch.nn.Module):
def __init__(self, input_dim, hidden_dim):
super(NeuralNetwork, self).__init__()
self.Lin_1 = torch.nn.Linear(input_dim, hidden_dim)
self.actF = torch.nn.ReLU()
self.Lin_out = torch.nn.Linear(hidden_dim, 4)
def forwar... | magicoder | python |
You are tasked with implementing a function that finds the maximum length of a contiguous subarray with an equal number of 0s and 1s in a binary array. The input will be a list of integers containing only 0s and 1s. You need to return the length of the longest contiguous subarray with an equal number of 0s and 1s. If n... | ```python
from typing import List
def findMaxLength(nums: List[int]) -> int:
max_length = 0
count = 0
count_map = {0: -1} # Initialize the count_map with count 0 at index -1
for i in range(len(nums)):
count += 1 if nums[i] == 1 else -1 # Increment count for 1, decrement for 0
if count... | magicoder | python |
You are tasked with creating a program that generates all possible combinations of a given list of elements. Your program should take a list of elements as input and output all the unique combinations of these elements. A combination is a selection of items from the list, where the order of selection does not matter. F... | ```python
from itertools import combinations
def generate_combinations(elements):
all_combinations = []
for r in range(1, len(elements) + 1):
all_combinations.extend(list(combinations(elements, r)))
return [list(comb) for comb in all_combinations]
```
The `generate_combinations` function uses the `... | magicoder | python |
You are tasked with implementing a class that adheres to the given interface `iConverter`. The interface `iConverter` has a single method `convert()` that can throw an exception. Your task is to create a class `TemperatureConverter` that implements the `iConverter` interface and provides a method to convert temperature... | ```java
public class TemperatureConverter implements iConverter {
public void convert() {
try {
double celsius = 25.0; // Example temperature in Celsius
double fahrenheit = convertCelsiusToFahrenheit(celsius);
System.out.println("Temperature in Fahrenheit: " + fahrenheit)... | magicoder | java |
You are tasked with implementing a function that converts a hexadecimal color code to its corresponding RGB representation. The function should take an integer representing the hexadecimal color code and return a tuple of three floating-point numbers representing the red, green, and blue components of the color.
You a... | ```swift
func hexToRGB(_ hex: Int) -> (Double, Double, Double) {
let red = Double((hex & 0xff0000) >> 16) / 255.0
let green = Double((hex & 0x00ff00) >> 8) / 255.0
let blue = Double(hex & 0x0000ff) / 255.0
return (red, green, blue)
}
```
The `hexToRGB(_:)` function takes an integer `hex` representing t... | magicoder | swift |
You are tasked with implementing a custom authorization system for a web application. The system should allow users to have multiple roles, and each role should have specific permissions. To achieve this, you need to create an `AuthorizeEnum` class that utilizes flags to represent the permissions associated with each r... | ```csharp
using System;
namespace SACustomAPI.Utilities
{
[Flags]
public enum Roles
{
None = 0,
Admin = 1 << 0,
Editor = 1 << 1,
Contributor = 1 << 2,
Viewer = 1 << 3
}
[Flags]
public enum Permissions
{
None = 0,
Create = 1 << 0,
... | magicoder | csharp |
You are tasked with implementing a class for measuring and asserting time-related results in a testing framework. The class, `AssertPart`, is responsible for validating that the measured time does not exceed a specified maximum time. The class should throw an exception if the measured time exceeds the provided maximum ... | ```csharp
using System;
public class AssertPart
{
private readonly RunResult _measureResult;
public AssertPart(RunResult measureResult)
{
_measureResult = measureResult;
}
public void NotExceedTotalTime(TimeSpan maxAllowedTime)
{
if (_measureResult.ElapsedTime > maxAllowedTime... | magicoder | csharp |
You are tasked with creating a command-line interface (CLI) application for a file management system. The CLI should support various commands for navigating directories, creating and deleting files, and displaying the contents of a directory. Your task is to implement the `Cli` class and its `Execute` method, which wil... | ```python
import os
class Cli:
def __init__(self, parameters, cwd, logMethod):
self.parameters = parameters
self.cwd = cwd
self.logMethod = logMethod
def Execute(self):
command = self.parameters[0]
if command == "cd":
directory = self.parameters[1]
... | magicoder | python |
You are tasked with creating a Python function that tokenizes a given input string based on a provided token specification. The token specification is a list of tuples, where each tuple contains a token name and a corresponding regular expression pattern. The function should return a list of tokens, where each token is... | ```python
import re
from typing import List, Tuple
def tokenize(input_string: str, token_specification: List[Tuple[str, str]]) -> List[Tuple[str, str]]:
tokens = []
combined_regex = '|'.join('(?P<%s>%s)' % pair for pair in token_specification)
for match in re.finditer(combined_regex, input_string):
... | magicoder | python |
You are tasked with implementing a genetic algorithm to evolve a population of birds to maximize their fitness in a simulated environment. Each bird is represented by a chromosome, which contains a neural network representing the bird's brain. The genetic algorithm will evolve these chromosomes over multiple generation... | ```python
import random
import numpy as np
class NeuralBird:
def __init__(self, input_size, hidden_size, output_size):
self.input_size = input_size
self.hidden_size = hidden_size
self.output_size = output_size
self.weights_input_hidden = np.random.rand(hidden_size, input_size)
... | magicoder | python |
You are given a string `s` consisting of lowercase English letters and spaces. The string contains a hidden message encoded using a simple substitution cipher. In this cipher, each letter is shifted a certain number of places down or up the alphabet. For example, with a shift of 3, 'a' would be replaced by 'd', 'b' wou... | ```python
def decode_cipher(s: str, shift: int) -> str:
decoded_message = ""
for char in s:
if char.isalpha():
shift_amount = 65 if char.isupper() else 97
decoded_char = chr((ord(char) - shift_amount - shift) % 26 + shift_amount)
decoded_message += decoded_char
... | magicoder | python |
You are tasked with creating a Node.js script that processes user inputs to execute a command in a specified working directory. The script should handle different target types and interpreters based on user input. You are given a code snippet from a Node.js script that captures user inputs and sets default values for t... | ```typescript
function executeCommand(): void {
const child_process = require('child_process');
let command = '';
if (input_targetType === 'inline') {
command = `${input_targetInterperter} -c "${input_script} ${input_arguments}"`;
} else if (input_targetType === 'file') {
command = `${i... | magicoder | typescript |
You are tasked with creating a script to automate the process of updating and synchronizing git submodules. Git submodules are repositories embedded within a parent repository. The provided code snippet attempts to synchronize and update the submodules and retries the operation if it fails.
Your task is to write a she... | ```bash
#!/bin/bash
MAX_RETRIES=3
RETRY_COUNT=0
s=0
while [ $RETRY_COUNT -lt $MAX_RETRIES ]; do
git submodule sync && git submodule update --init --recursive && s=0 && break || s=$?
echo "Retrying..."
((RETRY_COUNT++))
done
exit $s
```
In the solution, a shell script is provided that uses a while loop t... | magicoder | shell |
You are tasked with implementing a Python class for fluid properties using the CoolProp library. CoolProp is a C++ library that provides high-quality fluid properties for use in process simulation. Your task is to create a Python class called `Fluid` that interfaces with CoolProp to retrieve and display the properties ... | ```python
import CoolProp.CoolProp as CP
class Fluid:
def __init__(self, fluid_name):
self.fluid_name = fluid_name
def get_property(self, property_name, units):
value = CP.PropsSI(property_name, "Name", self.fluid_name)
if units == "Celsius":
if property_name == "T":
... | magicoder | python |
You are tasked with creating a Python program that manages reformulators for a text processing system. The reformulators are used to modify and enhance the input text in various ways. Each reformulator is a class that inherits from the `BaseReformulator` class and provides specific functionality. The reformulators are ... | ```python
from collections import defaultdict
class BaseReformulator:
pass
class StaticReformulator(BaseReformulator):
pass
class LinearReformulator(BaseReformulator):
pass
class AttentiveReformulator(BaseReformulator):
pass
class MemoryReformulator(BaseReformulator):
pass
class SymbolicReform... | magicoder | python |
You are given a list of strings representing file extensions. Your task is to write a function that groups these file extensions based on their common prefixes. If two file extensions have the same prefix, they should be grouped together. The function should return a dictionary where the keys are the common prefixes an... | ```python
def group_file_extensions(file_extensions):
groups = {}
for ext in file_extensions:
prefix = ''
for i in range(len(ext)):
prefix += ext[i]
if prefix in groups:
groups[prefix].append(ext)
else:
groups[prefix] = [ext]
... | magicoder | python |
You are working on a blockchain application that involves handling unspent transaction outputs (UTXOs). Your task is to implement a function that processes UTXOs and performs attribute updates with fees. The function `_send_attrib_with_fees` is responsible for this operation. It takes several parameters, including the ... | ```rust
use serde::{Serialize, Deserialize};
use serde_json;
#[derive(Serialize, Deserialize)]
struct UTXO {
// Define the structure of UTXO as per the application's requirements
// For example: pub amount: u64, pub address: String, etc.
}
fn process_UTXOs(did: &str, attrib_raw_data: Option<&str>, wallet_hand... | magicoder | rust |
You are working on a natural language processing (NLP) project and need to implement a data batching mechanism for a sequence-to-sequence model. The provided code snippet is part of a Python class method responsible for adding data to the batch. The class maintains several lists to store information about the source an... | ```python
class DataBatch:
def __init__(self):
self.batch_Src_length = []
self.batch_Src_labels = []
self.batch_Src_label_length = []
self.batch_Tgt_labels = []
self.batch_Tgt_label_length = []
self.batch_Src_text = []
def add_data_to_batch(self, mat, Src_tokens,... | magicoder | python |
You are tasked with implementing a Python decorator that adds functionality to a view function in a Django web application. The decorator, named `active_auction`, is intended to check if an auction for a specific item is still active before allowing the view function to proceed. If the auction is still ongoing, the vie... | ```python
from django.utils import timezone
from django.http import HttpResponse
# Decorator definition
def active_auction(function):
def wrap(request, *args, **kwargs):
item = Item.objects.get(slug=kwargs['slug'])
if item.end_of_auction > timezone.now():
return function(request, *args,... | magicoder | python |
You are given a code snippet that is part of a function. Your task is to complete the function by implementing the missing logic. The function takes an array of integers as input and is expected to return the sum of all the positive integers in the array.
```c
#include <stdio.h>
int sumOfPositiveIntegers(int arr[], i... | ```c
#include <stdio.h>
int sumOfPositiveIntegers(int arr[], int size) {
int sum = 0;
for (int i = 0; i < size; i++) {
if (arr[i] > 0) {
sum += arr[i];
}
}
return sum;
}
``` | magicoder | c |
You are tasked with implementing a configuration parser for a Swagger UI application. The configuration is provided as an associative array in PHP, containing various settings for the Swagger UI. Your goal is to write a function that processes this array and returns a formatted string representing the configuration in ... | ```php
function parseSwaggerConfig(array $config): string {
$output = "Swagger UI Configuration:\n";
if (isset($config['default-swagger-version'])) {
$output .= "Default Swagger Version: {$config['default-swagger-version']}\n";
}
if (isset($config['api-doc-template'])) {
$output .= ... | magicoder | php |
You are tasked with implementing a function to validate a signature using the BLS12-381 curve. The function should take in the necessary parameters and verify whether the signature is valid for the given message and public key.
You are provided with the following code snippet as a starting point:
```rust
pub fn noop_... | ```rust
use pairing::bls12_381::{Bls12, Fr, G1, G2, Fq12};
use pairing::{CurveAffine, PrimeField, Field, Engine};
use bls12_381::{Signature, PublicKey, verify};
pub fn noop_operation(tree: &CircuitAccountTree, acc_id: u32) -> Operation<Bn256> {
let signature_data = SignatureData::init_empty();
let first_sig_ms... | magicoder | rust |
You are tasked with creating a Discord bot command that processes messages and issues warnings for the use of forbidden words. The bot should also ignore channels marked as NSFW and those listed in the ignore list. The command should be able to toggle the warning system on and off and provide specific instructions for ... | ```javascript
// Sample implementation in JavaScript using Discord.js library
const Discord = require('discord.js');
const client = new Discord.Client();
const config = require('./config.json'); // Assuming the configuration is stored in a separate file
// Function to process messages and issue warnings
function proce... | magicoder | javascript |
You are tasked with implementing a class that can merge two specifications in a specific way. The specifications are represented as sets of objects, and the merging process involves adding all objects from one specification to another. After the merge, the resulting specification should contain all objects from both or... | ```python
class Specification:
def __init__(self):
self.objs = set()
def add_object(self, obj):
self.objs.add(obj)
def merge(self, other_spec):
self.objs.update(other_spec.objs)
def __eq__(self, other):
return self.objs == other.objs
# Example usage
spec1 = Specificat... | magicoder | python |
You are tasked with implementing a function to deserialize and process transaction data in a simplified blockchain system. The provided code snippet is part of a larger system responsible for handling transactions. The `deserializeOutputs` function deserializes the outputs of a transaction from a given read stream, whi... | ```javascript
// Solution for deserializeOutputs function
function deserializeOutputs(readStream) {
// Implementation of deserialization logic for transaction outputs
// Example: Assuming readStream contains serialized outputs, deserialize and return the outputs
// ...
return deserializedOutputs;
}
// ... | magicoder | javascript |
You are tasked with implementing a system to manage the effects of a magical spell on specific targets within a game environment. The provided code snippet is part of the spell's logic and is written in C++. Your task is to complete the implementation by defining the necessary classes and functions to handle the spell'... | ```cpp
// Define the UOrangeVesselTarget class representing the target component
class UOrangeVesselTarget : public UActorComponent
{
GENERATED_BODY()
public:
// Define necessary functions and members for the target component
};
// Define the UOrangeTargetData class holding additional information about a targ... | magicoder | cpp |
You are tasked with implementing a Python function that processes a given file and returns its unique identifier. The unique identifier is a string that is derived from the file's content and properties. The function should handle various file types and return the identifier based on specific rules for each type.
The ... | ```python
import hashlib
from PIL import Image
def get_file_identifier(file_path: str) -> str:
with open(file_path, 'rb') as file:
content = file.read()
file_extension = file_path.split('.')[-1].lower()
if file_extension in ['txt', 'csv', 'json']:
return hashlib.md5(content).he... | magicoder | python |
You are tasked with creating a PHP script that generates a class file based on the given code snippet. Your script should parse the provided code and extract relevant information to construct a valid PHP class file. The extracted information includes the package, author's name and email, copyright details, license, ver... | ```php
<?php
// Given code snippet
$codeSnippet = "\n\t \$ROOT = (!isset(\$ROOT)) ? \"../../../\":\$ROOT;";
$codeSnippet .= "\n\t /**";
$codeSnippet .= "\n\t * @Package /example";
$codeSnippet .= "\n\t * @Category Object";
$codeSnippet .= "\n\t * @Author John Doe <john@example.com>";
$codeSnippet .= "\n\t * @Copyright ... | magicoder | php |
You are tasked with creating a program that simulates a simple build system. The build system should be able to handle dependencies between different components of a software project and build the project in the correct order.
Your task is to implement a function that takes a list of targets and their dependencies an... | ```python
def build_order(targets):
dependency_map = {target["target_name"]: set(target["dependencies"]) for target in targets}
built = set()
order = []
def build_target(target_name):
if target_name not in built:
for dependency in dependency_map[target_name]:
build_t... | magicoder | python |
You are tasked with implementing a simple command-line calculator that can perform basic arithmetic operations. The calculator should take user input in the form of a mathematical expression and then evaluate and display the result. The supported operations are addition (+), subtraction (-), multiplication (*), and div... | ```python
def calculate(expression):
def evaluate(tokens):
stack = []
for token in tokens:
if token.isdigit() or (token[0] == '-' and token[1:].isdigit()):
stack.append(float(token))
elif token in {'+', '-', '*', '/'}:
b, a = stack.pop(), stack... | magicoder | python |
You are tasked with implementing a function that calculates the size of a CIMPLE class in bytes based on the given code snippet. CIMPLE is a modeling language and framework for creating management information models. The code snippet provided contains metadata and information about a CIMPLE class, including the number ... | ```c
size_t calculateCIMPLEClassSize(
int meta_qualifiers,
int num_meta_qualifiers,
void* class_metadata,
size_t class_size,
void* locals,
int super_class,
int num_keys,
void* meta_repository
) {
// Calculate the size of the CIMPLE class
size_t totalSize = class_size;
// Add... | magicoder | c |
You are tasked with implementing a custom input function that reads integers from the standard input in C++. The function should handle both positive and negative integers and ignore any non-integer input.
Write a function `customInput` that reads the next integer from the standard input and returns it. The function s... | ```cpp
#include <iostream>
using namespace std;
int customInput() {
int n = 0;
bool negative = false;
int c = getchar();
while ((c < '0' || c > '9') && c != '-') {
c = getchar();
}
if (c == '-') {
negative = true;
c = getchar();
}
while (c >= '0' && c <= '9') {
n = n * 10 + (c - '0');
... | magicoder | cpp |
You are tasked with creating a Python function that utilizes the Py4J library to interact with a Java application. The function should retrieve documentation for a specific method of a Java class and perform assertions on the retrieved documentation.
Write a Python function `get_method_documentation` that takes in the... | ```python
def get_method_documentation(gateway, class_name, method_name):
with gateway() as g:
java_class = g.help(class_name, display=False, pattern=f"{method_name}(*")
assert f"Help on class {class_name} in package" in java_class
assert f"{method_name}" not in java_class
assert f"{... | magicoder | python |
You are tasked with creating a Python program that processes audio data to generate complete lists of files. The program takes three command-line arguments: the directory containing MFCC (Mel-frequency cepstral coefficients) files, the directory containing transcription files, and the output directory for the generated... | ```python
import os
import sys
def generate_complete_lists(mfcc_dir, trans_dir, list_dir):
mfcc_files = [f for f in os.listdir(mfcc_dir) if os.path.isfile(os.path.join(mfcc_dir, f))]
trans_files = [f for f in os.listdir(trans_dir) if os.path.isfile(os.path.join(trans_dir, f))]
matched_pairs = []
for m... | magicoder | python |
You are tasked with creating a web service that generates and serves a dynamic favicon based on a given URL. The favicon will be generated by fetching the website's favicon using the provided URL and returning it as a file with the appropriate MIME type. However, the service should also handle errors gracefully by retu... | ```csharp
public class FaviconService
{
public IActionResult GetFavicon(string url)
{
try
{
// Fetch the website's favicon using the provided URL
FaviconModel faviconModel = FetchFavicon(url);
// Serve the fetched favicon as a file with the appropriate MIME t... | magicoder | csharp |
You are tasked with implementing a Python class that processes input data and handles errors using a custom error handling utility. The class, named `DataProcessor`, is responsible for parsing a list of values and storing a specific value at a given index. Additionally, it should handle potential errors related to insu... | ```python
class DataProcessor:
def __init__(self, values):
try:
self.style = int(values[118])
except IndexError as _err:
_msg = "ERROR: Insufficient input values."
_code = Utilities.error_handler(_err.args)
# Call the error handling method with the err... | magicoder | python |
You are tasked with implementing a Rust macro that processes Vulkan API documentation attributes. The macro should extract relevant information from the provided attributes and generate corresponding documentation for the Vulkan API.
Your task is to create a macro that takes in the following input attributes:
- `doc`:... | ```rust
macro_rules! generate_vulkan_doc {
(doc = $doc:expr) => {
format!("Documentation: {}", $doc)
};
(doc = $doc:expr, alias = $alias:expr) => {
format!("Documentation: {}\nAlias: {}", $doc, $alias)
};
}
fn main() {
let doc_only = generate_vulkan_doc!(doc = "<s>Vulkan Manual Page... | magicoder | rust |
You are tasked with creating a function that processes an image and performs a specific transformation on it. The given code snippet initializes a texture from an image file and defines a function to draw the Codeplay logo using this texture. Your task is to implement a function that takes the loaded image as input and... | ```cpp
ci::Surface8uRef grayscaleTransform(const ci::Surface8uRef& inputImage) {
ci::Surface8u outputImage(inputImage->getWidth(), inputImage->getHeight(), false);
for (int y = 0; y < inputImage->getHeight(); y++) {
for (int x = 0; x < inputImage->getWidth(); x++) {
ci::Color8u pixel = input... | magicoder | cpp |
You are tasked with creating a Python function that processes a list of theme icons and their properties. Each theme icon is represented as a dictionary containing the icon details. The function should extract and return the unique combinations of icon variants and their corresponding gradient colors.
The theme icon d... | ```python
def extract_icon_variants(icons):
unique_variants = {}
for icon in icons:
variant = icon["variant"]
gradient = icon["gradient"]
if variant in unique_variants:
if gradient not in unique_variants[variant]:
unique_variants[variant].append(gradient)
... | magicoder | python |
You are tasked with implementing a Python class method that interacts with a microcontroller's raw REPL (Read-Eval-Print Loop) prompt. The method should send a control character, wait for a response, and then wait for the raw REPL prompt to appear.
You are given a partial code snippet that demonstrates the usage of th... | ```python
class Microcontroller:
def __init__(self):
# Initialize the microcontroller
def ctrl_a(self):
# Send CTRL-A to enter raw REPL mode
def wait_repl_response(self):
# Wait for the response from the microcontroller
def wait_prompt(self):
try:
prompt_re... | magicoder | python |
You are working on a statistics library for Python and have been tasked with implementing a module for conducting various types of analysis of variance (ANOVA) tests. The code snippet provided imports three functions from the `anova` module: `bartletts_test`, `oneway_anova`, and `tukeys_range_test`. These functions are... | ```python
# anova.py
import numpy as np
from scipy.stats import bartlett, f_oneway
from statsmodels.stats.multicomp import pairwise_tukeyhsd
def bartletts_test(*args):
"""
Perform Bartlett's test for equal variances.
Args:
*args: Multiple arrays of data.
Returns:
test_statistic: The test sta... | magicoder | python |
You are tasked with creating a Python program to manage a simple form application using the Tkinter library. The form application should be displayed in a window that is centered on the screen. The form should collect information about a person, such as their name, age, and email address. The form should have input fie... | ```python
import tkinter as tk
def centrar_ventana(ventana):
pantalla_ancho = ventana.winfo_screenwidth()
pantalla_largo = ventana.winfo_screenheight()
aplicacion_ancho = 400
aplicacion_largo = 200
x = int((pantalla_ancho/2) - (aplicacion_ancho/2))
y = int((pantalla_largo/2) - (aplicacion_largo... | magicoder | python |
You are tasked with implementing a Python module that provides diagnostic tools for a label propagation algorithm. The module should include a class called `LpaDiagnostics` and should be designed to be imported using the `__all__` list.
Your task is to create the `LpaDiagnostics` class with the following methods:
1. `... | ```python
# lpa_diagnostics.py
class LpaDiagnostics:
def __init__(self, graph):
self.graph = graph
# Initialize any necessary data structures for diagnostics
def run_diagnostics(self):
# Perform diagnostics on the label propagation algorithm
# Analyze the algorithm's performanc... | magicoder | python |
You are tasked with implementing a custom inspector for a game development project. The game includes a feature for defining ragdoll physics behavior, and you need to create a custom GUI for editing the ragdoll definitions. The provided code snippet includes a method for setting the current ragdoll definition and an ov... | ```csharp
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(RagdollDefinition))]
public class RagdollDefinitionEditor : Editor
{
private SerializedProperty limbConstraintsProperty;
private SerializedProperty jointStrengthsProperty;
private SerializedProperty collisionSettingsProperty;
private... | magicoder | csharp |
You are working on a project that involves optimizing a complex mathematical model using Python and NumPy. As part of the optimization process, you need to calculate the value of `e_pri` based on certain mathematical operations. The code snippet provided contains relevant calculations for `e_pri`, but it seems to be in... | ```python
import numpy as np
def calculate_e_pri(latent, K, Omega, Lambda, Theta, L, X0, X1, p, eps_abs, eps_rel):
if not latent:
for k in np.arange(K):
assert np.all(L[k]==0)
dim = int(((p ** 2 + p) / 2).sum()) # number of elements of off-diagonal matrix
D1 = np.sqrt(sum([np.linalg.... | magicoder | python |
You are working on a package management system for a software repository. The system uses a dependency declaration syntax to specify the required versions of other packages. Each dependency declaration consists of the package name, version range, and optional conditions. A condition can be based on the package version,... | ```python
import re
def satisfies_dependency(package_version: str, dependency_declaration: str, condition: str = None) -> bool:
package, version_range = dependency_declaration.split('@')
min_version, max_version = version_range.split(':')
# Check if the package matches
if package != package_versio... | magicoder | python |
You are tasked with creating a Python function that processes a list of models and performs specific operations on related fields. The function should collect the primary keys (PKs) of related models and then use these PKs to filter and bulk create objects in a specified destination database.
You are given the followi... | ```python
def process_models(models, start, end, dest_db):
for model in models:
related_pks = _collect_related_pks(model)
filtered_objects = model._default_manager.filter(pk__in=related_pks[start:end])
filtered_objects.using(dest_db).bulk_create(filtered_objects)
```
In the solution, the `p... | magicoder | python |
You are given a Python code snippet that prints a pattern of numbers in a specific format. Your task is to understand the pattern and write a function to generate the same pattern based on the given input.
The pattern is printed using nested loops and involves the following steps:
1. Initialize a variable `num` to 1 a... | ```python
def print_pattern(n):
num = 1
inc = 1
for x in range(n, 0, -1):
for y in range(x, 0, -1):
print(" ", end="")
print("".join(str(num + i * inc) for i in range(x)))
num += 2 * x
inc += 2 * x
# Test the function with the example
print_pattern(3)
```
Output... | magicoder | python |
You are tasked with implementing a simple neural network training loop in Python. The given code snippet is a part of the training process for a neural network. The network is trained using mini-batch gradient descent with shuffling of the training data. The forward pass and backward pass are performed for each mini-ba... | ```python
class NeuralNetwork:
# other methods and attributes are omitted for brevity
def zero_grad(self):
for layer in self.layers:
layer.zero_grad()
def train(self, X, y, n_train_data, batch_size):
# shuffle the data
permutation = self._rand.permutation(n_train_data)
... | magicoder | python |
You are tasked with implementing a cache side-channel attack simulation in Rust. In a cache side-channel attack, an attacker can infer sensitive information by observing the cache access patterns of a victim process. Your goal is to simulate this attack by implementing a simplified version of the Multiple Address Cache... | ```rust
struct MultipleAddrCacheSideChannel {
// Define the struct fields as needed
}
impl MultipleAddrCacheSideChannel {
unsafe fn prepare(&self, batch: &mut Vec<u8>) {
// Simulate cache side-channel attack by manipulating cache access patterns
// Example: Access specific memory addresses base... | magicoder | rust |
You are tasked with creating a Java class that implements a string encryption and decryption mechanism using a custom encryption algorithm. The encryption algorithm is provided by the `StringEncryptor` interface, and you need to implement this interface to encrypt and decrypt strings. The code snippet provided includes... | ```java
import java.security.SecureRandom;
import java.util.Base64;
public class CustomStringEncryptor implements StringEncryptor {
private static final String ENCRYPTION_KEY = "YourEncryptionKey"; // Replace with a secure encryption key
@Override
public String encrypt(String input) {
try {
... | magicoder | java |
You are tasked with creating a Django management command that calculates the critical CSS for a given webpage. Critical CSS is the minimal set of CSS required to render the above-the-fold content of a webpage, which helps improve page load performance.
Your task is to implement the `calculate_critical_css` function wi... | ```python
from django.core.management.base import BaseCommand
from django_rq import job
from inline_static.css import transform_css_urls
from yourapp.exceptions import CriticalException
from yourapp.models import Critical
import logging
logger = logging.getLogger(__name__)
@job
def calculate_critical_css(critical_id,... | magicoder | python |
You are tasked with creating a command-line tool that processes a given set of files. The tool should be able to perform various operations on the files, such as counting the number of lines, extracting specific content, or performing custom operations. Your task is to implement a Java program that can be executed from... | ```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class FileProcessor {
public static void main(String[] args) {
if (args.length < 2) {
System.out.println("Usage: java -jar FilePro... | magicoder | java |
You are tasked with implementing a Python class that performs cryptographic signing using the RSA algorithm. The class should support the use of different hash functions for the signature generation process. Your task is to complete the implementation of the `RSAAlgorithm` class by providing the necessary methods and f... | ```python
import hashlib
from Crypto.PublicKey import RSA
from Crypto.Signature import pkcs1_15
from Crypto.Hash import SHA256
class RSAAlgorithm(AbstractSigningAlgorithm):
def __init__(self, hash_fun: object) -> None:
self.hash_fun = hash_fun
def sign(self, data: bytes) -> bytes:
key = RSA.ge... | magicoder | python |
You are working on a software system that manages assessment authoring. In this system, there is a class `AssessmentPartFormRecord` that represents a record for an `AssessmentPartForm`. This class inherits from two other classes: `abc_assessment_authoring_records.AssessmentPartFormRecord` and `osid_records.OsidRecord`.... | ```python
class AssessmentPartFormRecord(abc_assessment_authoring_records.AssessmentPartFormRecord, osid_records.OsidRecord):
"""A record for an ``AssessmentPartForm``.
The methods specified by the record type are available through the
underlying object.
def calculate_total_score(self):
total_... | magicoder | python |
You are tasked with implementing a class to represent a 2D vector and providing various operations for manipulating vectors. Your task is to complete the implementation of the Vector class by adding the necessary methods to perform vector operations.
The Vector class should have the following methods:
1. `__init__(sel... | ```python
import math
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def add(self, other):
return Vector(self.x + other.x, self.y + other.y)
def subtract(self, other):
return Vector(self.x - other.x, self.y - other.y)
def multiply(self, scalar):
... | magicoder | python |
You are tasked with implementing a custom learning rate scheduler for a deep learning model training process. The provided code snippet is part of a larger training script and demonstrates the loading of a checkpoint containing the optimizer state and the starting iteration number. Additionally, it initializes a learni... | ```python
import torch.optim as optim
class CustomLRScheduler:
def __init__(self, optimizer, mode='min', factor=0.1, patience=10, cooldown=0, min_lr=0, eps=1e-8):
self.optimizer = optimizer
self.mode = mode
self.factor = factor
self.patience = patience
self.cooldown = cooldo... | magicoder | python |
You are tasked with implementing a simplified version of a tunneling system in C++. The tunneling system is responsible for establishing connections between an application client and server. The provided code snippet is part of the tunneling system and demonstrates the handling of connections.
Your task is to create a... | ```cpp
#include <memory>
#include <iostream>
// Define the TcpConnectionPtr and any_cast<TunnelPtr> for demonstration purposes
class TcpConnection;
using TcpConnectionPtr = std::shared_ptr<TcpConnection>;
class Tunnel;
using TunnelPtr = std::shared_ptr<Tunnel>;
class Tunnel {
private:
TcpConnectionPtr appServer... | magicoder | cpp |
You are tasked with creating a Python function that processes a file containing bibliographic data in RIS format and performs specific operations on the data. The RIS format is a standardized tag-based file format used by many reference management software to store bibliographic citations. The function should read the ... | ```python
from pathlib import Path
from asreview.data import ASReviewData
def process_ris_file(input_file_path: str, output_file_path: str) -> bool:
try:
# Read the bibliographic data from the input RIS file
asr_data = ASReviewData.from_file(input_file_path)
# Modify the data (e.g., add or... | magicoder | python |
You are given a JSON object representing a company's organizational structure. The object contains employees and their respective managers. Each employee has a unique ID, a name, and a manager ID. The manager ID refers to the ID of the employee's direct manager. The top-level manager has a manager ID of null. Your task... | ```python
def organizational_hierarchy(json_data):
employees = {emp["id"]: emp for emp in json_data["employees"]}
top_manager = next(emp for emp in json_data["employees"] if emp["managerId"] is None)
def build_hierarchy(employee_id):
employee = employees[employee_id]
return {
"i... | magicoder | python |
You are tasked with creating a program to manage a product inventory for a brand. The brand has multiple products, and each product has various attributes such as name, price, and quantity. Your task is to implement a class to represent the products and a method to calculate the total value of the brand's inventory.
C... | ```python
class Product:
def __init__(self, name, price, quantity):
self.name = name
self.price = price
self.quantity = quantity
def total_value(self):
return self.price * self.quantity
class Brand:
def __init__(self, products):
self.products = products
def tot... | magicoder | python |
You are tasked with implementing a function to test the validity of a given UTF-8 query. UTF-8 is a variable-width character encoding capable of encoding all 1,112,064 valid code points in Unicode using one to four one-byte (8-bit) code units. The function should take a list of integers representing bytes and determine... | ```python
from typing import List
def test_utf8_query(data: List[int]) -> bool:
num_bytes = 0
for byte in data:
if num_bytes == 0:
if (byte >> 5) == 0b110:
num_bytes = 1
elif (byte >> 4) == 0b1110:
num_bytes = 2
elif (byte >> 3) == 0b1... | magicoder | python |
You are tasked with implementing a text extraction algorithm for HTML content. The provided code snippet is a partial class definition for a `ReadabilityTextExtractor` that implements the `HTMLTextExtractor` interface. Your goal is to complete the class by implementing the `extractText` method, which takes an HTML stri... | ```php
class ReadabilityTextExtractor implements HTMLTextExtractor {
public function extractText(string $html): string {
// Remove HTML tags and attributes
$text = strip_tags($html);
// Decode HTML entities
$text = html_entity_decode($text);
// Remove e... | magicoder | php |
You are working on a project to optimize energy distribution in a district. The project involves analyzing different types of buildings and their energy usage patterns. You have been provided with data related to the distribution of buildings, the percentage of agents in each building type, the percentage of primary ho... | ```python
def calculate_energy_distribution(buildings, agents, phh_agents, agriculture, dhn, pv_plants):
total_energy_distribution = 0
for building_type in buildings:
energy_distribution = buildings[building_type] * agents[building_type] * phh_agents[building_type] * agriculture[building_type] * dhn[bui... | magicoder | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.