query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with implementing a priority queue data structure using a linked list. The priority queue should support the following operations:
1. `enqueue(value, priority)`: Add a new element with the given value and priority to the priority queue.
2. `dequeue()`: Remove and return the element with the highest prior... | ```cpp
#include <iostream>
struct Node {
int value;
int priority;
Node* next;
};
class PriorityQueue {
private:
Node* head;
public:
PriorityQueue() : head(nullptr) {}
~PriorityQueue() {
while (head != nullptr) {
Node* temp = head;
head = head->next;
... | magicoder | cpp |
You are given a Python function that generates a list of binary trees. Each binary tree is represented by a TreeNode class, which has attributes `val`, `left`, and `right`. The function takes an integer `N` as input and returns a list of all possible unique binary trees with `N` nodes.
The TreeNode class is defined as... | ```python
def count_unique_binary_trees(N: int) -> int:
if N <= 1:
return 1
dp = [0] * (N + 1)
dp[0] = 1
dp[1] = 1
for i in range(2, N + 1):
for j in range(1, i + 1):
dp[i] += dp[j - 1] * dp[i - j]
return dp[N]
```
The `count_unique_binary_trees` function uses dyn... | magicoder | python |
You are working as a DevOps engineer for a company that uses Docker for containerization. Your team is responsible for managing a private Docker registry and ensuring that the necessary images are available for deployment. As part of this task, you need to automate the process of tagging and pushing Docker images to th... | ```python
import docker
def tag_and_push_image(source_image, target_registry, target_image):
client = docker.from_env()
# Tag the source image
tagged_image = client.images.get(source_image).tag(target_registry + '/' + target_image)
# Push the tagged image to the target registry
client.ima... | magicoder | python |
You are tasked with implementing a simplified version of the Adler-32 checksum algorithm in Rust. The Adler-32 checksum is a checksum algorithm that was developed by Mark Adler and is used for fast checksum computation of data. The algorithm operates on a stream of bytes and produces a 32-bit checksum value.
Your task... | ```rust
fn calculate_adler32_checksum(data: &[u8]) -> u32 {
const MOD_ADLER: u32 = 65521; // largest prime smaller than 65536
let mut s1: u32 = 1;
let mut s2: u32 = 0;
for &byte in data {
s1 = (s1 + u32::from(byte)) % MOD_ADLER;
s2 = (s2 + s1) % MOD_ADLER;
}
(s2 << 16) | s1
}
... | magicoder | rust |
You are tasked with implementing a version control system for a document management application. The system should support versioning of documents, tracking changes, and managing transactions. Your task is to design and implement a class hierarchy to support version control operations.
You are provided with a list of ... | ```python
class VersioningManager:
def __init__(self):
self.versions = []
self.changesets = []
self.transactions = []
def create_version(self, document, author):
version_number = len(self.versions) + 1
version = Version(version_number, document, author)
self.vers... | magicoder | python |
You are tasked with creating a Python program that utilizes the Google Cloud Speech-to-Text API to transcribe audio files. Your program should take an audio file as input and use the Google Cloud client library to perform speech recognition on the audio. The result of the recognition should then be printed to the conso... | ```python
from google.cloud import speech
import io
def perform_speech_recognition(audio_file_path):
# Instantiates a client
client = speech.SpeechClient()
# Loads the audio into memory
with io.open(audio_file_path, "rb") as audio_file:
content = audio_file.read()
audio = speech.Recogn... | magicoder | python |
You are tasked with implementing a function to replace escaped characters in a given object. The function should iterate through the sections and options of the object, and for any key-value pairs of type 'keyval', it should replace any escaped characters with their unescaped counterparts.
Write a function `replace_es... | ```python
def replace_escapes(object):
"""Replace any escaped character. e.g \, with , \= with = and so on"""
for section in object._mySections:
for option in object._configDef[section].keys():
if option in object[section]:
if object._configDef[section][option]['type'] == 'ke... | magicoder | python |
You are tasked with implementing a payment processing system for an e-commerce platform. The system should handle the creation of orders and the processing of payments using a third-party payment gateway such as Stripe. Your task is to write a function that processes a payment and verifies the correctness of the paymen... | ```python
def process_payment(stripe_token, order_data):
# Call the Stripe API to process the payment using the provided stripe token and order data
# Assume the response is stored in the variable 'response'
# Verify the correctness of the payment response
expected_status_code = 201
expected_owed_a... | magicoder | python |
You are tasked with creating a Python class that implements a simple web crawler. The web crawler should be able to visit a given URL, extract all the hyperlinks present on the page, and then recursively visit each of those hyperlinks to extract their hyperlinks, and so on. The web crawler should store the unique URLs ... | ```python
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
class SimpleCrawler:
def __init__(self, url):
self.start_url = url
self.visited_urls = set()
def crawl(self):
self._crawl_url(self.start_url)
def get_unique_urls(self):
return list(sel... | magicoder | python |
You are given a list of items, each with a specific weight and value. Your task is to implement a function to determine the items to be included in a knapsack of a given weight to maximize the total value. The function should return the indices of the selected items.
You are provided with a code snippet that reads the... | ```python
class Item:
def __init__(self, weight, value):
self.weight = weight
self.value = value
def calculate_used_items_in_knapsack(items, weight):
n = len(items)
dp = [[0 for _ in range(weight + 1)] for _ in range(n + 1)]
for i in range(1, n + 1):
for w in range(weight + 1):... | magicoder | python |
You are tasked with creating a program to filter and display student information based on certain criteria. The program should take a list of students, each represented by a dictionary containing their name, age, class, student ID, and profile picture. The program should then filter the students based on their age and ... | ```python
def filter_students(students, age_threshold):
filtered_students = []
for student in students:
if student['age'] < age_threshold:
filtered_students.append({
'name': student['name'],
'age': student['age'],
'class': student['class'],
... | magicoder | python |
You are tasked with implementing a simplified version of a query builder class in PHP. The class provides methods for constructing SQL queries for database operations. Your task is to implement the `orWhereNull` method and the `select` method of the query builder class.
The `orWhereNull` method is used to add a "WHERE... | ```php
/**
* Select.
*/
public function select($column = '*')
{
if (is_array($column)) {
$columns = implode(', ', $column);
} else {
$columns = $column;
}
$this->db->select($columns);
return $this;
}
```
In the `select` method, we first check if the provided column argument is a... | magicoder | php |
You are given a list of words, and your task is to write a function that returns the longest anagram group from the list. An anagram group is a set of words that can be formed by rearranging the letters of each other. For example, "listen" and "silent" are anagrams of each other.
Write a function `longest_anagram_grou... | ```python
def longest_anagram_group(words):
anagram_groups = {}
for word in words:
sorted_word = ''.join(sorted(word))
if sorted_word in anagram_groups:
anagram_groups[sorted_word].append(word)
else:
anagram_groups[sorted_word] = [word]
max_length = 0
lon... | magicoder | python |
You are tasked with creating a Python program to generate a 3D plot of a disc using the PyVista library. The disc should consist of 50 points in the circumferential direction. Your program should utilize the PyVista library to create the disc and then display the 3D plot with the edges visible.
Your task is to write a... | ```python
# Import the necessary module to create the disc.
import pyvista
# Use the PyVista library to generate a disc with 50 points in the circumferential direction.
mesh = pyvista.Disc(c_res=50)
# Display the 3D plot of the disc with the edges visible.
mesh.plot(show_edges=True, line_width=5)
```
The provided Py... | magicoder | python |
You are tasked with implementing a simple inventory management system for a role-playing game. The system should allow for the addition, removal, and retrieval of items and monsters on different game floors. Each floor can have a range of items and monsters associated with it. Your task is to implement the necessary fu... | ```rust
struct Item {
name: String,
// Add any other relevant fields for the item
}
struct Monster {
name: String,
// Add any other relevant fields for the monster
}
impl Floor {
fn add_item(&mut self, item: Item) {
self.items.push(item);
}
fn remove_item(&mut self, item: &Item) {... | magicoder | rust |
You are working on a web application that manages proposal groups. A proposal group is a collection of proposals submitted by users. Each proposal group has a unique group name and can contain multiple proposals. You are tasked with writing a test case for the functionality that allows users to edit a proposal group.
... | ```python
from django.test import TestCase
from django.test import RequestFactory
from yourapp.models import ProposalGroup, Proposal
from yourapp.views import ProposalGroupEditView
class ProposalGroupEditTestCase(TestCase):
def setUp(self):
self.factory = RequestFactory()
# Create test data - propo... | magicoder | python |
You are tasked with creating a program that simulates a simple file management system. Your program should be able to handle basic file operations such as creating, deleting, and listing files and directories. The program should also support navigating through directories and displaying the current working directory.
... | ```python
import os
def create_file(filename):
try:
with open(filename, 'w'):
pass
print(f"File '{filename}' created successfully.")
except FileExistsError:
print(f"File '{filename}' already exists.")
def delete_file(filename):
try:
os.remove(filename)
p... | magicoder | python |
You are tasked with implementing a class hierarchy for a content management system using PHP. The system should support modules and controllers, and each module should have a namespace and a controller namespace. Your task is to create a class hierarchy that models this system and provides the necessary properties and ... | ```php
class Module {
protected $namespace;
public function __construct($namespace) {
$this->namespace = $namespace;
}
public function getNamespace() {
return $this->namespace;
}
}
class Controller {
protected $namespace;
public function __construct($namespace) {
... | magicoder | php |
You are tasked with designing a vehicle tracking system that utilizes a sender and receiver to communicate vehicle data. The sender is responsible for sending vehicle information, while the receiver is responsible for processing and verifying the received data. Your task is to implement the sender and receiver classes ... | ```java
public class Vehicle {
// Existing code remains unchanged
public boolean validateVehicleData(String vehicleData) {
try {
Vehicle receivedVehicle = fromJsonString(vehicleData);
// Perform validation checks on receivedVehicle attributes
// Example: Check if id,... | magicoder | java |
You are given a code snippet from a Rust program that is responsible for counting the occurrences of different block IDs. The `counts` array is used to store the counts of each block ID. The code snippet shows how the counts are updated for block IDs in two different scenarios: when the block ID is `BlockId::NONE` and ... | ```rust
fn count_block_ids(func: &Function) -> Vec<(BlockId, i32)> {
let mut counts = vec![(BlockId::NONE, 0)]; // Initialize counts with BlockId::NONE
for param in &func.params {
if let Some((bid, _)) = param.default_value {
// Check if the block ID is already in the counts vector
... | magicoder | rust |
You are tasked with creating a program that parses and extracts specific information from an HTML document. The given HTML snippet represents a license text with placeholders denoted by `<NAME>`. Your task is to write a function that takes this HTML snippet as input and returns the name of the copyright holder, which i... | ```python
from bs4 import BeautifulSoup
def extract_copyright_holder(html):
soup = BeautifulSoup(html, 'html.parser')
copyright_line = soup.find('span', string="Copyright (c) 2015")
if copyright_line:
next_span = copyright_line.find_next('span', style=" font-family:'mono';")
if next_span:
... | magicoder | python |
You are tasked with creating a Python function that dynamically loads a specific class based on a given file extension. The function should be able to handle different file types and return the appropriate class instance based on the file extension.
You are provided with a code snippet that imports classes from differ... | ```python
import os
from electroPyy.io.BaseRawIO import BaseRawIO
from electroPyy.io.HdF5IO import HdF5IO
from electroPyy.io.NeuroExIO import NeuroExIO
from electroPyy.io.WinWcpRawIO import WinWcpRawIO
def load_data_from_file(file_path):
file_extension = os.path.splitext(file_path)[1].lower()
if file_exte... | magicoder | python |
You are tasked with creating a function that modifies a given code by inserting import statements and method calls for a set of plugins. The function `addPlugins` takes two parameters: `originalCode`, a string representing the original code, and `plugins`, an array of strings representing the names of the plugins to be... | ```typescript
function addPlugins(originalCode: string, plugins: string[]): string {
const importComment = '// import plugins here';
const useComment = '// use plugins here';
const importStatements = plugins.map((plugin) => `import ${plugin} from '${plugin}';`).join('\n');
const useStatements = plugins.map((pl... | magicoder | typescript |
You are tasked with implementing a Python class for a neural network layer. The class, named `CustomLayer`, is responsible for processing input data and performing specific operations based on the provided parameters. Your task is to complete the implementation of the `CustomLayer` class by filling in the missing parts... | ```python
import torch
import torch.nn.functional as F
class CustomLayer(torch.nn.Module):
def __init__(self, dic, wei, bias, pooling, regularization=None):
super(CustomLayer, self).__init__()
self.dic = dic
self.dis = lambda x: torch.norm(x, p=2, dim=-1)
self.wei = wei
self... | magicoder | python |
You are tasked with creating a Python script to automate the execution of a NAS (Neural Architecture Search) algorithm using the DARTS (Differentiable Architecture Search) method. The script should take in a configuration file specifying the search parameters and output directory, and then execute the DARTS algorithm u... | ```python
import subprocess
def run_darts_nas_search(config_file, output_dir):
darts_script = "scripts/search/DARTS.py"
config_path = f"configs/search/{config_file}"
out_dir = f"exp/search/{output_dir}"
command = f"python {darts_script} --cfg {config_path} OUT_DIR {out_dir}"
subprocess.run(command... | magicoder | python |
You are tasked with creating a script that extracts the latest Git commit hash from a given repository and exports it as an environment variable. Your script should be able to handle the scenario where the repository is not available or the Git command fails.
Your script should perform the following steps:
1. Check if... | ```bash
#!/bin/bash
# Check if the Git repository is available
if [ -d .git ]; then
# Extract the latest commit hash
commit_hash=$(git rev-parse HEAD)
# Export the commit hash as an environment variable
export GIT_HASH=$commit_hash
else
# Handle the scenario where the repository is not availab... | magicoder | shell |
You are tasked with implementing a Python function that simulates a simple reboot mechanism for a computer system. The function should take in a list of processes and their respective execution times, and then execute these processes in a specific order. The reboot mechanism involves running all the processes once, and... | ```python
def simulate_reboot(processes, reboot_time):
total_time = sum(time for _, time in processes) # Calculate the total time for original execution
total_time *= 2 # Double the total time for original and reverse execution
total_time += reboot_time # Add the reboot time
return total_time
``` | magicoder | python |
You are tasked with implementing a C++ range adaptor that wraps `boost::adaptors::indirected` and `boost::adaptors::indirect` for safe use with rvalues. The adaptor should be able to be called with zero or one arguments.
The zero-argument version is used for pipeline syntax (as an operand of the | operator), while the... | ```cpp
#include <iostream>
#include <vector>
#include <boost/range/adaptor/indirected.hpp>
#include <boost/range/adaptor/indirect.hpp>
template <typename Range>
class SafeIndirectAdaptor {
public:
SafeIndirectAdaptor() {}
SafeIndirectAdaptor(Range&& range) : range(std::forward<Range>(range)) {}
template ... | magicoder | cpp |
You are tasked with implementing a chess game in an object-oriented programming language. As part of this implementation, you need to create a class for representing a square on the chessboard. Each square can either be empty or contain a chess piece. The chess piece can be of any type (e.g., pawn, rook, bishop, etc.).... | ```java
public class Square {
private Piece piece;
// Constructor
public Square(Piece p) {
piece = p;
}
// Calculate to put place
public List<Coordinate> calculateToPutPlace(Board board) {
// Implement logic to calculate valid places to put the piece
List<Coordinate> va... | magicoder | java |
You are working on a web application that uses Django, and you need to implement a view for retrieving Styled Layer Descriptor (SLD) XML content. The provided code snippet shows a Django class-based view that retrieves an SLD from a Redis database and returns it as an HTTP response.
Your task is to extend this functio... | ```python
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseServerError
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from django.http import Http404
import redis
strict_redis = redis.StrictRedis(host='localhost', port=6379, db=0)
@method_decorator([csrf_ex... | magicoder | python |
You are tasked with implementing a Python function that simulates a simple web server application. The function should handle incoming HTTP requests, process them, and generate appropriate HTTP responses. Additionally, you need to write unit tests for this function using the `pytest` framework.
Your task is to complet... | ```python
# Implementation of the session_app function
def session_app(request):
if "in-test" in request.headers:
request.headers["in-test"] = "in-test-value"
else:
request.headers["in-test"] = "in-test-value"
return Response(headers={"out-test": "out-test-value"})
# Unit tests using pytest... | magicoder | python |
You are tasked with implementing a simple key-value store using Rust. The key-value store will support putting data into the store and retrieving it by key. However, the store will also support compression of the stored data. Your task is to implement the `KeyValueStore` struct and its associated methods.
You are prov... | ```rust
pub trait Compressor {
fn compress(&self, data: &[u8]) -> Vec<u8>;
fn decompress(&self, data: &[u8]) -> Vec<u8>;
}
pub struct NoopCompressor;
impl Compressor for NoopCompressor {
fn compress(&self, data: &[u8]) -> Vec<u8> {
data.to_vec()
}
fn decompress(&self, data: &[u8]) -> Vec<... | magicoder | rust |
You are tasked with creating a Python script to automate the compilation of Soy templates into JavaScript source files using the SoyToJsSrcCompiler tool. The given code snippet is a part of the script and shows the construction of a command to execute the compiler. The script takes input arguments such as the path to t... | ```python
import os
import subprocess
def compile_soy_to_js(args):
processed_lang_list = ','.join(args.processed_langs)
command = [
'java', '-jar', os.path.join(args.path_to_jar, 'SoyToJsSrcCompiler.jar'),
'--locales', processed_lang_list,
'--shouldProvideRequireSoyNamespaces',
... | magicoder | python |
You are tasked with creating a Python function that reads and unpickles data from a file using the `pickle` module. Your function should take a file path as input and return the unpickled data. However, there is a catch - the file may not exist, or it may not be accessible due to permission issues. In such cases, your ... | ```python
import pickle
import pathlib
class FileError(Exception):
pass
class UnpickleError(Exception):
pass
def read_and_unpickle(filename: pathlib.Path):
try:
with open(filename, "rb") as handle:
try:
data = pickle.load(handle)
return data
... | magicoder | python |
You are tasked with implementing a state manager for a simple game using Python and the Pygame library. The game has a constant frames per second (FPS) of 60 and a display size of 600x600 pixels. The provided code snippet initializes the game display and sets up a main loop for the game. Your task is to create a state ... | ```python
import pygame
class StateManager:
def __init__(self, display_width, display_height):
self.display = pygame.display.set_mode([display_width, display_height])
self.clock = pygame.time.Clock()
self.states = {}
self.current_state = None
def add_state(self, state_name, sta... | magicoder | python |
You are given two arrays, `array1` and `array2`, each containing hexadecimal values. Your task is to write a function `findCommonHexValues(array1, array2)` that returns an array containing the common hexadecimal values present in both `array1` and `array2`. The function should return the common values in ascending orde... | ```python
def findCommonHexValues(array1, array2):
set1 = set(array1)
set2 = set(array2)
common_values = list(set1.intersection(set2))
common_values.sort()
return common_values
``` | magicoder | python |
You are tasked with implementing a generic class that can store and manipulate a collection of elements of a specific type. Your task is to create a generic class `Gen` that takes a type parameter `D` and provides methods to add elements to the collection, retrieve elements from the collection, and calculate the averag... | ```python
from typing import Generic, TypeVar, List, Union
D = TypeVar('D')
class Gen(Generic[D]):
def __init__(self):
self.elements: List[D] = []
def add_element(self, element: D) -> None:
self.elements.append(element)
def get_elements(self) -> List[D]:
return self.elements
... | magicoder | python |
You are tasked with creating a program to analyze a wine dataset using cross-validation. The dataset contains various attributes of different types of wine, and the goal is to predict the quality of the wine based on these attributes. Your task is to implement a function that performs cross-validation on the dataset an... | ```python
import numpy as np
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import KFold
from sklearn import datasets
def perform_cross_validation(wine_dataset, num_folds):
kf = KFold(n_splits=num_folds, shuffle=True, random_state=42)
cross_validation_scores = cross_val_score(... | magicoder | python |
You are tasked with creating a program to validate and deserialize JSON data representing a board game's content. The `BoardContent` class represents the content of the board game, and the program should be able to handle various scenarios, including invalid JSON data.
Your task is to implement a method `DeserializeBo... | ```csharp
using System;
using System.Text.Json;
public class BoardContent
{
// Define properties and methods for the board content
}
public class BoardGame
{
public BoardContent DeserializeBoardContent(string json)
{
try
{
return JsonSerializer.Deserialize<BoardContent>(json);
... | magicoder | csharp |
You are tasked with implementing a sorting algorithm for a specific type of data structure. The data structure is a cross-tabulation (crosstab) table, which is used to summarize and analyze the relationship between two or more variables. In this problem, you will focus on sorting the row groups of the crosstab table.
... | ```java
public void sortRowGroupsByMeasure(int measureIndex, boolean ascending) {
// Create an array to store the indices of the row groups
Integer[] indices = new Integer[rowGroups.length];
for (int i = 0; i < indices.length; i++) {
indices[i] = i;
}
// Sort the indices array based on the ... | magicoder | java |
You are tasked with creating a function that will parse a given string containing a styled component in JavaScript and extract the component name and its styled properties.
Write a function `parseStyledComponent` that takes a string as input and returns an object containing the component name and its styled properties... | ```javascript
function parseStyledComponent(inputString) {
const componentNameRegex = /const\s+(\w+)\s+=\s+styled\.\w+/;
const styledPropertiesRegex = /`([\s\S]+)`/;
const componentNameMatch = inputString.match(componentNameRegex);
const styledPropertiesMatch = inputString.match(styledPropertiesRegex);
if (... | magicoder | javascript |
You are tasked with implementing a function that processes a configuration file and extracts specific information from it. The configuration file is in a custom format and contains various settings for a software application. Each setting is represented by a key-value pair, and the file may also include comments. Your ... | ```cpp
#include <string>
#include <sstream>
#include <unordered_map>
std::string extractConfigValue(const std::string& configFile, const std::string& key) {
std::unordered_map<std::string, std::string> configMap;
std::istringstream iss(configFile);
std::string line;
while (std::getline(iss, line))... | magicoder | cpp |
You are tasked with implementing a command-line argument parser in C#. The parser should be able to handle both named arguments (e.g., `-flag value`) and remaining arguments (i.e., arguments that are not associated with any specific flag).
Your task is to complete the `Parse` method in the `RemainingArgumentsParser` c... | ```csharp
public void Parse()
{
var remainingArguments = new List<string>();
var namedArguments = new Dictionary<string, string>();
while (_argIt.HasNext())
{
string arg = _argIt.GetNext();
if (arg.StartsWith("-"))
{
// Named argument
string flag = arg.T... | magicoder | csharp |
You are tasked with implementing a function that takes a list of integers representing the number of windows on each floor of a building and returns the total number of windows visible from the outside. The building is viewed from the front, and each window on a floor is directly above the window on the floor below it.... | ```python
def count_visible_windows(windows):
visible_windows = 0
max_height = 0
for height in windows:
if height > max_height:
visible_windows += height
max_height = height
else:
visible_windows += max_height
return visible_windows
```
The `... | magicoder | python |
You are tasked with creating a class that manages user verification emails using a mailer service and JSON Web Tokens (JWT) for token generation. Your goal is to implement a method that sends a verification link to a user's email address.
You are provided with a code snippet from a TypeScript class that includes a `Ma... | ```typescript
import { MailerService } from 'path-to-mailer-service';
import { JwtService } from 'path-to-jwt-service';
interface VerificationTokenPayload {
email: string;
}
class UserVerificationManager {
constructor(
private mailerService: MailerService,
private jwtService: JwtService,
) {}
public ... | magicoder | typescript |
You are tasked with creating a Python module that dynamically imports subpackages based on a predefined list of available subpackages. Your goal is to implement a function that, given a list of subpackage names, imports and returns the corresponding subpackages as modules.
You are provided with the following code snip... | ```python
import importlib
def import_subpackages(subpackage_names):
imported_subpackages = {}
for subpackage in subpackage_names:
try:
imported_subpackages[subpackage] = importlib.import_module(subpackage)
except ImportError:
print(f"Error: Subpackage '{subpackage}' not... | magicoder | python |
You are tasked with creating a simple PHP function that will parse a given HTML content and extract all the class names used in the `div` elements. Your function should return an array of unique class names found in the `div` elements of the HTML content.
Your function signature should be:
```php
function extractDivCl... | ```php
function extractDivClassNames($htmlContent) {
$classNames = [];
$dom = new DOMDocument();
$dom->loadHTML($htmlContent);
$divs = $dom->getElementsByTagName('div');
foreach ($divs as $div) {
if ($div->hasAttribute('class')) {
$classAttr = $div->getAttribute('class');
... | magicoder | php |
You are tasked with implementing a function to retrieve the console font size in a Windows environment. The function should handle error cases and return appropriate error codes.
Write a function `GetConsoleFontSize` that takes a handle to the console output and an index as input and returns the font size at the speci... | ```cpp
#include <Windows.h>
#include <iostream>
COORD GetConsoleFontSize(HANDLE hConsoleOutput, DWORD index) {
COORD defaultSize = { 0, 0 };
CONSOLE_FONT_INFOEX fontInfo;
fontInfo.cbSize = sizeof(CONSOLE_FONT_INFOEX);
if (!GetCurrentConsoleFontEx(hConsoleOutput, FALSE, &fontInfo)) {
// Error r... | magicoder | cpp |
You are tasked with implementing a contact form submission feature for a web application. The code snippet provided is a part of the backend logic for handling the form submission. The form includes fields for user email, carbon copy recipients, the editor's WordPress username, and the message body. The code snippet sh... | ```python
import messaging_module # Assuming the existence of a messaging module
def handle_contact_form_submission(user_email, carbon_copy, editor_wp_username, message):
try:
# Construct the message
constructed_message = f"From: {user_email}\nCC: {', '.join(carbon_copy)}\nEditor: {editor_wp_usern... | magicoder | python |
You are tasked with implementing a dynamic time warping (DTW) algorithm to compare two time series data. DTW is a method used to measure the similarity between two sequences that may vary in time or speed. In this problem, you are required to write a Python function that calculates the DTW distance between two given ti... | ```python
def dtw_distance(ts1, ts2):
n = len(ts1)
m = len(ts2)
# Create a 2D array to store the cumulative distances
dp = [[float('inf')] * (m + 1) for _ in range(n + 1)]
dp[0][0] = 0
# Calculate cumulative distances
for i in range(1, n + 1):
for j in range(1, m + 1):
... | magicoder | python |
You are tasked with implementing a function that splits a sequence of elements into fixed-size chunks. The function should handle various data types and provide the ability to apply a conversion function to the elements before splitting. Your task is to complete the implementation of the `splitFixed` function, ensuring... | ```python
def flattenSeq(e, result, conv):
if isinstance(e, (list, tuple)):
for el in e:
flattenSeq(el, result, conv)
else:
result.append(conv(e))
return result
def fixedSize(e):
if isinstance(e, (str, list, tuple)):
return len(e)
else:
return -1
def spl... | magicoder | python |
You are tasked with implementing a function that calculates the number of days between two given dates. The function should take in two parameters representing the start and end dates and return the number of days between them, inclusive of the start and end dates. You should account for leap years in your calculation.... | ```java
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class DateCalculator {
public static long calculateDaysBetweenDates(LocalDate startDate, LocalDate endDate) {
return ChronoUnit.DAYS.between(startDate, endDate) + 1;
}
public static void main(String[] args) {
... | magicoder | java |
You are tasked with implementing a function to identify and classify quadrilateral contours in an image using OpenCV and NumPy. The function should take an input binary image and return a list of quadrilateral contours that satisfy specific conditions.
Your task is to implement the `find_quadrilateral_contours` functi... | ```python
import cv2
import numpy as np
def find_quadrilateral_contours(bina):
quadrilateral_contours = []
contours, hierarchy = cv2.findContours(bina, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
cnt_len = cv2.arcLength(cnt, True)
cnt = cv2.approxPolyDP(cnt, 0.02*cnt_len, T... | magicoder | python |
You are working on a system that manages clusters of software packages. The code snippet provided is a part of the system and contains a dictionary `pattern` that maps a unique key to a software package. Additionally, there is a function call to `shapePairs()` which returns a DataFrame `matches` containing file names o... | ```python
import pandas as pd
def filter_matches(pattern, matches):
filtered_matches = matches[matches['file'].apply(lambda x: x in list(pattern.values()) or not (x.startswith('linux_') or x.startswith('FFmpeg_') or x.startswith('curl_') or x.startswith('nginx_') or x.startswith('openssl_') or x.startswith('redis_... | magicoder | python |
You are tasked with implementing a custom namespace management system in C++. Your goal is to create a class that allows users to add, remove, and list namespaces, as well as add and remove functions within those namespaces.
Your task is to implement the `NamespaceManager` class with the following functionalities:
1.... | ```cpp
#include <iostream>
#include <set>
#include <map>
class NamespaceManager {
private:
std::set<std::string> namespaces;
std::map<std::string, std::set<std::string>> functionsInNamespace;
public:
void addNamespace(std::string name) {
namespaces.insert(name);
}
void removeNamespace(std... | magicoder | cpp |
You are tasked with implementing a trajectory reconstruction algorithm for a computer vision application. The algorithm takes in a history of 2D points and a camera matrix, and returns a reconstructed trajectory.
You are given the following code snippet as a starting point:
```cpp
reconstruction::TplTrajectory recons... | ```cpp
reconstruction::TplTrajectory GReconstructTrajectory::on(const cv::GArray<std::vector<cv::Point2f>>& pointHistory, const cv::GMat& cameraMatrix)
{
// Perform trajectory reconstruction algorithm here
// Pseudocode for trajectory reconstruction:
// 1. Use the cameraMatrix to perform camera calibration and ob... | magicoder | cpp |
You are tasked with implementing a custom dataset class for a graph neural network (GNN) in Python. The dataset class should inherit from the `Dataset` class and be able to load and process data from a specified directory. The dataset will be used for training and testing the GNN model.
Your task is to complete the im... | ```python
import os
import pickle
from torch.utils.data import Dataset
class GNNdataset(Dataset): # train and test
def __init__(self, data_dir):
super().__init__()
self.data_dir = data_dir
self.file_list = os.listdir(self.data_dir)
def __len__(self):
return len(self.fil... | magicoder | python |
You are given an array `a` containing `n` elements, where the first `m` elements are already sorted in non-decreasing order, and the remaining elements are in the right half of the array. Additionally, you are given two integer variables `k` and `j`, which represent the current index for the sorted portion and the righ... | ```python
from typing import List
def mergeSortedRightHalf(a: List[int], m: int, k: int, j: int) -> List[int]:
r = a[m:] # Extract the right half of the array
i = m - 1 # Last index of the sorted portion
while i >= 0 and j < len(r):
if a[i] > r[j]:
a[k] = r[j]
j += 1
... | magicoder | python |
You are tasked with implementing a custom error type and its conversion traits in Rust. Your custom error type, `Error`, should be able to represent different error conditions and be convertible from other error types. You need to define the `Error` type and implement the `From` trait for converting from specific error... | ```rust
// Define the custom error type Error
struct Error {
message: String,
}
impl Error {
// Constructor method for Error
fn new(message: &str) -> Error {
Error {
message: message.to_string(),
}
}
}
// Implement the From trait for converting ParseFloatError to Error
impl... | magicoder | rust |
You are tasked with implementing a class that represents a configuration object for a network device using the YANG data modeling language. The provided code snippet outlines a partial interface for the `Config` class, which is used to manage and manipulate configuration data for network devices. Your task is to comple... | ```cpp
#include <ydk/entity.h>
#include <vector>
#include <string>
#include <memory>
class Config : public ydk::Entity {
public:
Config() {}
~Config() {}
bool has_data() const override {
// Implement the logic to check for the presence of data
// Return true if data is present, false other... | magicoder | cpp |
You are tasked with creating a program that extracts specific information from a GitHub repository URL. The program should be able to parse the repository owner's username, the repository name, and the programming language used in the repository.
Write a function `parse_github_url` that takes a GitHub repository URL a... | ```python
import requests
from bs4 import BeautifulSoup
def parse_github_url(url):
# Extract username and reponame from the URL
parts = url.split('/')
username = parts[-2]
reponame = parts[-1]
# Fetch the repository page to determine the programming language
repo_url = f'https://api.github.com... | magicoder | python |
You are tasked with implementing a generic function that loads and processes data based on its type. The provided code snippet is a part of a templated function `load` within a namespace `ee`. The function takes a `std::string` as input and returns a value of type `T`. The function uses a helper function `DataTraits<Re... | ```cpp
#include <iostream>
#include <string>
// Define the DataTraits template to handle different data types
template <typename T>
struct DataTraits {
static T load(const std::string& value) {
// Default implementation for unsupported types
throw std::runtime_error("Unsupported data type");
}
... | magicoder | cpp |
You are tasked with implementing a generic method to perform type checking and casting within a C# application. The method should take a collection of items and ensure that it contains items assignable to a specified type. Additionally, the method should return a constraint to further validate the type of the items in ... | ```csharp
using System.Collections.Generic;
using FluentAssertions;
public class TypeValidator
{
public AndConstraint<IEnumerable<TValue>> ValidateAndReturnConstraint<TValue>(IEnumerable<object> value)
{
value.Cast<object>().Should().ContainItemsAssignableTo<TValue>();
return new AndConstraint<... | magicoder | csharp |
You are tasked with implementing a stack data structure in Java. A stack is a last-in, first-out (LIFO) data structure that supports two main operations: push, which adds an element to the top of the stack, and pop, which removes the top element from the stack. Additionally, you need to implement a method that returns ... | ```java
class MinStack {
private Node top;
private class Node {
int value;
int min;
Node next;
Node(int value, int min, Node next) {
this.value = value;
this.min = min;
this.next = next;
}
}
public void push(int x) {
... | magicoder | java |
You are tasked with implementing a configuration validation and merging class for a web application. The class should be able to validate and merge configuration settings from multiple files, ensuring that the final configuration is consistent and error-free.
The `ConfigManager` class should have the following functio... | ```python
class ConfigManager:
def __init__(self):
self.config = {}
def load_config_from_file(self, file_path):
# Load configuration settings from a file and update the internal config dictionary
# Implementation depends on the file format (e.g., JSON, YAML, XML)
pass
def v... | magicoder | python |
You are tasked with implementing a module resolution algorithm for a simple TypeScript-like language. The language consists of modules, each defined in a separate file, and can import other modules using the `export * from '<module-name>'` syntax. When a module is imported, all the exports from the imported module shou... | ```typescript
function resolveModuleImports(importStatements: string[]): Map<string, string[]> {
const importMap = new Map<string, string[]>();
const processImport = (moduleName: string) => {
if (!importMap.has(moduleName)) {
importMap.set(moduleName, []);
}
};
for (const statement of importStat... | magicoder | typescript |
You are given a function `transformArray` that takes an array of integers as input and returns a new array based on the following rules:
1. If an element has two adjacent neighbors that are both even or both odd, it becomes even (i.e., it is incremented by 1).
2. If an element has two adjacent neighbors that are differ... | ```python
from typing import List
def transformedArray(arr: List[int]) -> List[int]:
def transformArray(arr: List[int]) -> List[int]:
outputArray = arr[:]
while True:
changed = False
for i in range(1, len(arr) - 1):
if (arr[i - 1] % 2 == 0 and arr[i] % 2 == 0... | magicoder | python |
You are given a list of integers in ascending order. Your task is to write a function `solution` that compresses the list into a string representation where consecutive integers are represented as ranges separated by commas. If a single integer appears, it should be represented individually. If there are gaps between i... | ```python
def solution(args):
out = []
beg = end = args[0]
for n in args[1:] + [""]:
if n != end + 1:
if end == beg:
out.append(str(beg))
elif end == beg + 1:
out.extend([str(beg), str(end)])
else:
out.a... | magicoder | python |
You are given a C++ code snippet that contains multiple nested namespace declarations. Your task is to write a function that counts the total number of nested namespaces in the given code snippet.
The code snippet is as follows:
```
}
} // namespace
} // namespace internal
} // namespace protobuf
} // namespace g... | ```cpp
#include <iostream>
#include <string>
int countNestedNamespaces(const std::string& codeSnippet) {
int count = 0;
int maxDepth = 0;
int currentDepth = 0;
bool inNamespace = false;
for (char c : codeSnippet) {
if (c == '{') {
if (inNamespace) {
currentDepth... | magicoder | cpp |
You are tasked with creating a script that sets up the classpath and runs a Java program using the specified classpath and Java options. The script should be able to handle multiple jar files in a directory and construct the classpath accordingly.
Given the code snippet provided, write a shell script that accomplishes... | ```bash
#!/bin/bash
# Set the CLASSPATH variable to include all the jar files in the PEEL_LIB_DIR directory
CLASSPATH=$(manglePathList $(echo ${PEEL_LIB_DIR}/*.jar . | sed 's/ /:/g'))
# Run the Java program using the constructed classpath and the specified Java options
${JAVA_RUN} -cp ${CLASSPATH} ${PEEL_JAVA_OPTS} e... | magicoder | shell |
You are tasked with creating a program to solve a specific problem from the Advent of Code 2020 challenge. The code snippet provided is using a macro `day_solver_from!` from the `d2020` library to solve the puzzle for Day 16 of the challenge.
The problem for Day 16 of Advent of Code 2020 involves parsing and analyzing... | ```rust
use std::collections::HashSet;
fn parse_input(input: &str) -> (Vec<(String, Vec<(u32, u32)>)>, Vec<u32>, Vec<Vec<u32>>) {
let mut sections = input.trim().split("\n\n");
let rules = sections.next().unwrap().lines().map(|line| {
let mut parts = line.split(": ");
let name = parts.next().un... | magicoder | rust |
You are tasked with implementing a Python class that represents an interface for interacting with a graph data structure. The graph is represented using an adjacency list and the interface should provide methods for adding and removing vertices and edges, as well as for retrieving information about the graph.
Your tas... | ```python
class Interface:
def __init__(self, graph):
self.graph = graph
def add_vertex(self, vertex):
if vertex not in self.graph:
self.graph[vertex] = []
def add_edge(self, from_vertex, to_vertex):
if from_vertex in self.graph and to_vertex in self.graph:
... | magicoder | python |
You are working on a security management system that involves handling file permissions and access control. The system uses a custom scripting language to define access rules and permissions. One of the tasks is to parse and interpret a specific type of script that manages permissions for a certain file type. The scrip... | ```python
import re
def extract_script_info(script):
# Extract function call using regex
function_call = re.search(r'(\w+)\((.*?)\)', script).group(0)
# Extract summary comment block content using regex
summary_content = re.search(r'<summary>(.*?)</summary>', script, re.DOTALL).group(1).strip()
r... | magicoder | python |
You are tasked with simulating a lottery game using Python. The game involves generating random numbers for both the user's ticket and the winning lottery numbers. Your goal is to write a program that simulates this lottery game and determines whether the user has won a prize.
Your program should perform the following... | ```python
import random
# Step 1: Generate a random ticket number for the user
user_ticket = random.randint(1, 10)
# Step 2: Generate a list of 5 unique random winning lottery numbers
lottery_numbers = random.sample(range(1, 21), 5)
# Step 3: Compare the user's ticket number with the winning lottery numbers
if user_... | magicoder | python |
You are tasked with implementing a simple class that represents a shopping cart. The class should have the ability to add items, remove items, calculate the total cost of the items in the cart, and apply a discount to the total cost. Additionally, the class should be able to print a list of items in the cart.
You need... | ```swift
class ShoppingCart {
// MARK: - Properties
private var items: [String: (price: Double, quantity: Int)] = [:]
// MARK: - Methods
func addItem(name: String, price: Double, quantity: Int) {
if let existingItem = items[name] {
items[name] = (price: existingItem.price, quant... | magicoder | swift |
You are tasked with creating a Python class to simulate a simple pendulum system. The class should allow for the simulation of the pendulum's motion and provide the ability to render the simulation in a graphical environment. Your task is to implement the `Pendulum` class with the following specifications:
- The `Pend... | ```python
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
class Pendulum:
def __init__(self, length, mass, damping, theta, omega):
self.length = length
self.mass = mass
self.damping = damping
self.theta = theta
self.omega = omega
... | magicoder | python |
You are tasked with implementing a message parsing algorithm for a specific communication protocol. The protocol uses a custom message format, and the goal is to extract and process individual messages from a continuous stream of data.
You are provided with a code snippet that demonstrates the basic structure of the m... | ```python
class UbloxMessage:
@staticmethod
def parse(data, raw=False):
# Define the logic for parsing individual messages from the data stream
# Extract message format, message data, and remaining data
# Return a tuple containing the message format, message data, and the remaining data
... | magicoder | python |
You are tasked with creating a Python function that manipulates version numbers in a configuration file. The function should read the current version from the configuration, increment it by a specified part, and then save the updated version back to the configuration file.
Write a Python function `bump_version` that t... | ```python
def bump_version(current_version, part):
# Split the current version into major, minor, and patch parts
major, minor, patch = map(int, current_version.split('.'))
# Increment the version based on the specified part
if part == 0:
major += 1
minor = 0
patch = 0
e... | magicoder | python |
You are tasked with implementing a stream event manager in TypeScript. The stream event manager is responsible for managing a collection of event providers and retrieving the next event from the providers in a round-robin fashion.
You are provided with a TypeScript code snippet that defines the structure of the stream... | ```typescript
export interface StreamEvent<T> {
data: T;
}
export interface EventProvider<T> {
getNextEvent: () => StreamEvent<T> | undefined;
}
export interface StreamEventManager<T> {
providers: EventProvider<T>[];
lastPublishedProvider: number;
}
export const makeManager = <T>(providers: EventProv... | magicoder | typescript |
You are tasked with implementing a neural network library in C++ that supports sequential model creation and manual layer creation. The library should allow loading pretrained models and weights. Your task is to implement the `Sequential` class and the `Dense` class, along with the necessary methods for model loading a... | ```cpp
#include <iostream>
#include <vector>
#include <memory>
// Define the shape of a 2D dimension
struct dim2d {
int rows;
int cols;
};
// Define the Layer interface
class Layer {
public:
virtual void init(dim2d shape) = 0;
virtual void load(dim2d inputShape, dim2d outputShape, std::vector<float> b... | magicoder | cpp |
You are given a list of linked lists, each representing a sorted list of integers. Your task is to merge these linked lists into a single sorted linked list.
Write a function `merge_linked_lists(linked_lists)` that takes in a list of linked lists and returns a new linked list that contains all the elements from the in... | ```python
import heapq
class Link:
def __init__(self, value):
self.value = value
self.next = None
def merge_linked_lists(linked_lists):
heap = []
for llist in linked_lists:
if llist:
heap.append((llist.value, llist))
heapq.heapify(heap)
result = current = L... | magicoder | python |
You are tasked with implementing a custom data structure in Rust to manage a collection of different types of elements. The data structure should support adding and retrieving elements, as well as providing specific methods for handling different types of elements.
You are given a code snippet that defines several met... | ```rust
// Define the CustomCollection data structure
struct CustomCollection<T> {
elements: Vec<T>,
}
impl<T> CustomCollection<T> {
// Method to create a new instance with a line of type U
fn new_line_othertongue(line: T) -> Self {
CustomCollection { elements: vec![line] }
}
// Method to ... | magicoder | rust |
You are tasked with implementing a file upload feature in a web application using Django. The application uses the Filebrowser package to manage and display uploaded images. However, the development team has encountered an issue with resizing images. The team has been advised not to use other resizing apps like sorl-th... | ```python
from PIL import Image
import os
def resize_and_save_image(image_path, output_path, width, height):
try:
with Image.open(image_path) as img:
resized_img = img.resize((width, height))
resized_img.save(output_path)
return True
except Exception as e:
pr... | magicoder | python |
You are tasked with creating a program to analyze a given source code file and identify potential issues based on specific patterns and rules. The program should parse the source code file and generate a report containing various types of warnings and success messages based on the analysis.
Your task is to implement a... | ```python
import re
def analyze_source_code(source_code_file):
report = ""
with open(source_code_file, 'r') as file:
source_code = file.read()
# Identify and report casts to the same type
cast_warnings = re.findall(r'(\w+\.cs\(\d+\)): \[WARNING\]: Found cast to the same type \"(\w+)\"'... | magicoder | python |
You are tasked with creating a Python script to preprocess and convert click data from the GCOM dataset into TFRecord files for session-based recommendation models. The GCOM dataset contains user click data, and the preprocessing involves converting the click data into sessions and then serializing the sessions into TF... | ```python
import subprocess
# Replace with the path to the unzipped GCOM dataset folder
DATA_DIR = "[REPLACE WITH THE PATH TO UNZIPPED GCOM DATASET FOLDER]"
# Construct the command for preprocessing
preprocess_command = f"python3 -m nar.preprocessing.nar_preprocess_gcom_dlrs \
--input_clicks_csv_path_regex '{DATA_DIR... | magicoder | python |
You are tasked with creating a program that simulates the rotation animation of a 2D shape using the CABasicAnimation class in Swift. The program should allow the user to specify the angle of rotation and the duration of the animation.
Write a function `rotateShape` that takes in the following parameters:
- `shape`: ... | ```swift
import UIKit
func rotateShape(shape: CALayer, angle: CGFloat, duration: TimeInterval) {
let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotationAnimation.fromValue = 0
rotationAnimation.toValue = angle
rotationAnimation.duration = duration
rotationAnimation.isRemo... | magicoder | swift |
You are tasked with creating a Python class that interacts with a database using the Pony ORM library. Your goal is to implement a class that can connect to a database, retrieve project information, and insert new project records. The provided code snippet is a starting point for the ORMProject class, and you need to c... | ```python
from pony.orm import Database, PrimaryKey, Optional, db_session
class ORMProject(db.Entity):
_table_ = 'mantis_project_table'
id = PrimaryKey(int, column='id')
name = Optional(str, column='name')
class ORMProjectManager:
def __init__(self, host, database, user, password):
self.db = D... | magicoder | python |
You are tasked with creating a Python module for handling input/output operations in a software project. The module should provide a factory function to create different types of input/output objects based on the specified format. The input/output objects will be used to read from or write to different types of data so... | ```python
from .iotools import FileIO, DatabaseIO, NetworkIO
def io_factory(format_string):
if format_string == "file":
return FileIO()
elif format_string == "database":
return DatabaseIO()
elif format_string == "network":
return NetworkIO()
else:
raise ValueError(f"Unsu... | magicoder | python |
You are tasked with implementing a custom layout algorithm for a grid-based user interface. The grid consists of cells, each of which can contain a view. The goal is to evenly distribute the views within the grid, ensuring that each cell is filled with a view and that the views are evenly spaced.
You are given a class... | ```swift
class CustomGridView {
var gridWidth: Double
var gridHeight: Double
var cellWidth: Double
var cellHeight: Double
var views: [UIView]
func layoutSubviews() {
let columns = Int(gridWidth / cellWidth)
let rows = Int(gridHeight / cellHeight)
var currentX = 0.0
var currentY = 0.0
... | magicoder | swift |
You are given a series of mathematical operations performed on double precision floating-point numbers. Your task is to implement a function that takes in the necessary input values and computes the final result based on the given code snippet.
The code snippet provided represents a sequence of mathematical operations... | ```java
public double computeFinalResult(double tmp258_, double tmp259_, double tmp14_, double tmp257_, double tmp12_, double tmp2_, double tmp16_, double tmp41_, double tmp58_, double tmp248_, double tmp156_, double tmp19_, double tmp63_) {
double tmp260_ = tmp258_ + tmp259_;
double tmp261_ = tmp260_ * tmp14_;... | magicoder | java |
You are tasked with implementing a function to calculate the metrics of a given dataset with a specified shift. The dataset consists of a list of integers, and the shift represents the number of positions each element in the dataset should be shifted to the right. The metrics to be calculated include the mean, median, ... | ```python
from collections import Counter
import statistics
def calculate_metrics_with_shift(dataset, shift):
shifted_dataset = [(x - shift) for x in dataset]
mean = sum(shifted_dataset) / len(shifted_dataset)
median = statistics.median(shifted_dataset)
mode = Counter(shifted_dataset).most_common(1)[0]... | magicoder | python |
You are tasked with implementing a Python decorator that performs parameter validation and default value assignment for a given function. The decorator should take a dictionary of parameter annotations and default values, and use them to validate and assign values to the function's parameters. If a parameter is missing... | ```python
def parameter_validator(annotation: dict):
"""
Decorator function that performs parameter validation and default value assignment for a given function.
Args:
annotation (dict): A dictionary containing parameter annotations and default values.
Returns:
function: The decorated function... | magicoder | python |
You are tasked with implementing a simplified version of a stack data structure in Python. A stack is a Last-In-First-Out (LIFO) data structure that supports two main operations: push, which adds an element to the top of the stack, and pop, which removes the top element from the stack. Your implementation should also s... | ```python
class MaxStack:
def __init__(self):
self.stack = []
self.max_stack = []
def push(self, x):
self.stack.append(x)
if not self.max_stack or x >= self.max_stack[-1]:
self.max_stack.append(x)
def pop(self):
if not self.stack:
return None... | magicoder | python |
You are tasked with implementing a custom loss function for a neural network using PyTorch. The loss function is called "lsce" and is used to calculate the loss between the predicted logits and the target values. The target values are represented as a tensor of integers. Your goal is to implement the "lsce" loss functi... | ```python
import torch
import torch.nn as nn
import unittest
class CustomLossFunction(nn.Module):
def __init__(self):
super(CustomLossFunction, self).__init__()
def forward(self, logits, target):
# Implement the lsce loss function
loss = torch.nn.functional.cross_entropy(logits, target... | magicoder | python |
You are tasked with implementing a skill level determination system for a role-playing game. The system should take a set of attributes and calculate the corresponding skill level based on predefined rules. The attributes include strength, agility, intelligence, and charisma, each represented by an integer value. The s... | ```java
public class SkillLevelDeterminer {
public String level(int strength, int agility, int intelligence, int charisma) {
int strengthAgilitySum = strength + agility;
int intelligenceCharismaSum = intelligence + charisma;
if (strengthAgilitySum > 150) {
return "Expert";
... | magicoder | java |
You are tasked with implementing a simplified model predictive control (MPC) algorithm for a mobile robot. The robot's state is represented by a 4-dimensional vector `state = [x, y, theta, v]`, where `x` and `y` are the position coordinates, `theta` is the orientation angle, and `v` is the velocity. The MPC algorithm u... | ```python
class MPCController:
def __init__(self, horizon, dt, plant_model):
self.horizon = horizon
self.dt = dt
self.plant_model = plant_model
def calculate_cost(self, predicted_states, reference_states):
total_cost = 0.0
for k in range(self.horizon):
error ... | magicoder | python |
You are tasked with implementing a function to decode energy sums from a given buffer. The buffer contains encoded energy sums in a specific format, and your task is to extract and decode these values. The encoding involves bitwise operations and masks, as shown in the following code snippet:
```python
'trace_length':... | ```python
def decode_energy_sums(buf: int) -> dict:
mask = {
'trace_length': (0xFFFF0000, 16), # Mask for trace_length: (0xFFFF0000, 16)
'trace_out_of_range': (0x0000FFFF, 0) # Mask for trace_out_of_range: (0x0000FFFF, 0)
}
decoded_sums = {
'trace_length': (buf & mask['trace_lengt... | magicoder | python |
You are tasked with implementing a custom annotation processor in Java that processes classes and fields annotated with `@JsonDateFormat`. The `@JsonDateFormat` annotation is used to specify the date format and timezone for fields in a JSON object. Your task is to create a processor that generates code to serialize and... | ```java
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import javax.... | magicoder | java |
You are tasked with implementing a Python class method for a statistical model. The method should handle the generation of a formula string based on the model's dependent variable and independent variables.
You are given a partial code snippet from the class method:
```python
else:
return f'{self.dependent_varia... | ```python
class StatisticalModel:
def __init__(self, dependent_variable, independent_variables):
self.dependent_variable = dependent_variable
self.independent_variables = independent_variables
def generate_formula(self):
x_formula = ', '.join(self.independent_variables)
return f... | magicoder | python |
You are tasked with implementing a function to parse data from an AppleSingle or AppleDouble container. These containers are used to store files on Apple file systems and may contain various types of data, including fonts. Your task is to create a Python function that can extract and parse the font data from an AppleSi... | ```python
def parse_apple_container(data):
"""
Parse font data from an AppleSingle or AppleDouble container.
"""
# Implement the parsing logic for AppleSingle or AppleDouble container data
# Extract and parse the font information from the container data
font_data = {} # Placeholder for parsed f... | magicoder | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.