query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with creating a Python function that simulates a simple file logging system. Your function should initialize a logger with different log levels and direct the logs to specific files based on the severity of the log message.
You are given a code snippet that includes a function `initialize_logger` with t... | ```python
import os
def initialize_logger(output_dir, console_log_level, info_log="info.log", warn_err_log="warn_error.log", all_log="all.log", verbose=True):
"""
Initialize a logger with different log levels and direct the logs to specific files.
:param output_dir: A string representing the directory whe... | magicoder | python |
You are tasked with creating a Python class that handles the compression and manipulation of zip files. Your class should have the following functionalities:
1. `add_file(filename, content)`: A method that takes a filename and its content as input and adds it to the zip file.
2. `set_file_permissions()`: A method that... | ```python
import zipfile
import io
class ZipHandler:
def __init__(self):
self._content_handler = io.BytesIO()
self._zip_file = zipfile.ZipFile(self._content_handler, 'a', zipfile.ZIP_DEFLATED)
def add_file(self, filename, content):
self._zip_file.writestr(filename, content)
def se... | magicoder | python |
You are tasked with implementing a Trie data structure in Swift. A Trie, also known as a prefix tree, is a tree-like data structure used to store a dynamic set of strings where the keys are usually strings. Each node in a Trie represents a single character of a string. The root node is empty, and each node contains lin... | ```swift
public class Trie<ElementType: Collection> where ElementType.Element: Hashable {
public typealias Node = TrieNode<ElementType.Element>
public let root: Node
public init() {
root = Node()
}
public func insert(_ word: ElementType) {
var current = root
for element in word {
if... | magicoder | swift |
You are tasked with implementing a function to handle pawn moves in a chess game. The given code snippet is part of a larger chess engine implementation and is responsible for processing pawn moves. The snippet shows a part of the code where the program checks for en passant moves and updates the defenses for a piece b... | ```python
def handlePawnMoves(game_state, defenses, piece_attacks, ep_square):
moves = [] # List to store the valid pawn moves
for square, piece in game_state.board.items():
if piece.color == game_state.current_player and piece.type == 'pawn':
i = square.index
value = piece_att... | magicoder | python |
You are tasked with creating a Python program that automates the process of downloading a specified number of images from Google Images based on a user input search query. The program should prompt the user to enter a search query and the number of images to download. It should then use web scraping techniques to fetch... | ```python
import os
import requests
from selenium import webdriver
import time
user = os.getlogin()
driver = webdriver.Chrome()
directory = os.path.join(os.getcwd(), 'data')
inp = input("Enter the search query: ")
url = 'https://www.google.com/search?q=' + str(inp) + '&source=lnms&tbm=isch&sa=X&ved=2ahUKEwie44_AnqLpA... | magicoder | python |
You are tasked with implementing a simple module system for a programming language. The module system should allow users to define and import modules, and resolve dependencies between modules. Each module can have dependencies on other modules, and the module system should ensure that dependencies are resolved in the c... | ```python
from typing import List, Tuple
def resolveModules(modules: List[Tuple[str, List[str]]]) -> List[str]:
dependency_map = {module: set(dependencies) for module, dependencies in modules}
resolved_modules = []
while dependency_map:
resolved_something = False
for module, dependencies i... | magicoder | python |
You are tasked with creating a utility function that parses a given styled-component's CSS-in-JS code and extracts the CSS properties defined within it. The input will be a string representing the styled-component's CSS-in-JS code, and the output should be an object containing the extracted CSS properties.
The CSS-in-... | ```javascript
function parseStyledComponent(cssInJS) {
const regex = /{([^}]+)}/; // Regex to match content within curly braces
const match = cssInJS.match(regex);
if (match) {
const propertiesString = match[1];
const properties = propertiesString.split(';')
.map(prop => prop.trim())
.filter(p... | magicoder | javascript |
You are tasked with implementing a method to retrieve user data using a provided user ID and access token. The method should handle potential errors and log appropriate messages. You are given a code snippet that includes a function to retrieve the user ID from a data dictionary and log an error if the ID is not presen... | ```python
import logging
class UserDataRetriever:
def __init__(self):
self.logger = logging.getLogger(__name__)
def get_user_data(self, user_id, access_token):
if user_id and access_token: # Check if user_id is not empty and access_token is valid
try:
# Retrieve us... | magicoder | python |
You are tasked with implementing a Python decorator that enforces a rule on the input parameters of a function. The decorator should be able to match fundamental types, such as int, float, str, etc., and apply the specified rule to the input parameters of the decorated function.
Your task is to implement the `@rule` d... | ```python
def apply_rule_decorator(rule_check):
def decorator(func):
def wrapper(*args, **kwargs):
for arg in args:
if not rule_check(type(arg)):
raise TypeError(f"Input parameter {arg} does not match the specified rule")
return func(*args, **kwarg... | magicoder | python |
You are tasked with implementing a metadata parser for a simplified version of the mistune markdown parser. The metadata in this context refers to key-value pairs that are specified at the beginning of a markdown document within a specific format. The metadata is enclosed within a pair of triple dashes (`---`) and cons... | ```python
def parse_metadata(markdown: str) -> dict:
metadata = {}
if markdown.startswith('---'):
end_index = markdown.find('---', 3)
if end_index != -1:
metadata_text = markdown[3:end_index].strip()
lines = metadata_text.split('\n')
for line in lines:
... | magicoder | python |
You are working on a bioinformatics project and need to create a Python class to manage file paths and lists. Your task is to implement a class called `FileManager` with the following requirements:
1. The class should have an attribute `_tmp_dir` representing the path to a temporary directory.
2. Upon instantiation, i... | ```python
import os
class FileManager:
def __init__(self, tmp_dir):
self._tmp_dir = tmp_dir
if not os.path.isdir(self._tmp_dir):
os.mkdir(self._tmp_dir)
# Path to third-party utilities
self._kmc_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "KMC", "bin... | magicoder | python |
You are tasked with creating a Python class that processes time information for class schedules. Your task is to implement a method that takes a string containing time information and converts it into a datetime object. The time information is in the format "start_time-end_time", where both start_time and end_time are ... | ```python
from datetime import datetime, time, date
class ClassSchedule:
def __init__(self, class_day):
self._class_day = class_day
self.date = None
def process_time_string(self, time_string):
hours = [hr.replace("h", "") for hr in time_string.split("-")]
start_time = time(int(... | magicoder | python |
You are tasked with implementing a command-line argument parser for a program that processes either images or vector fields and calculates the error using either absolute difference or squared difference. The given code snippet shows the initialization of two command-line switch arguments using the TCLAP library. Your ... | ```cpp
#include <iostream>
#include <tclap/CmdLine.h>
int main(int argc, char** argv) {
try {
TCLAP::CmdLine cmd("Command description message", ' ', "0.9");
TCLAP::SwitchArg vecSwitchArg("v", "vectorFields", "inputs are vector fields, not images", cmd, false);
TCLAP::SwitchArg sqrErrArg("s", "squaredErr... | magicoder | cpp |
You are tasked with creating a program to manage a library's book inventory. The program should allow users to add new books, display the list of available books, and edit the details of existing books. Each book should have a unique identifier, title, author, and quantity in stock.
You need to implement a class `Book... | ```python
class BookInventory:
def __init__(self):
self.books = {}
def add_book(self, id, title, author, quantity):
if id in self.books:
print(f"Book with ID {id} already exists.")
else:
self.books[id] = {'title': title, 'author': author, 'quantity': quantity}
... | magicoder | python |
You are tasked with creating a program that can extract the HTML tags from a given HTML file and count the occurrences of each tag. Your program should ignore any attributes within the tags and consider only the tag names. For example, if the input HTML file contains `<div>`, `<span>`, and `<div>` tags, your program sh... | ```python
from bs4 import BeautifulSoup
from collections import defaultdict
from typing import Dict
def countHTMLTags(htmlFile: str) -> Dict[str, int]:
tag_counts = defaultdict(int)
soup = BeautifulSoup(htmlFile, 'html.parser')
for tag in soup.find_all():
tag_name = tag.name.lower()
tag_cou... | magicoder | python |
You are tasked with creating a program to manage events. The program should display a list of events and their details. You are given a code snippet from a web application that displays events using a template engine. The snippet uses PHP syntax and the Laravel Blade template engine.
Given the code snippet:
```php
@se... | ```php
function displayEvents($events) {
$html = '<h1 class="text-center">Events</h1>';
if (count($events) > 0) {
$html .= '<ul>';
foreach ($events as $event) {
$html .= '<li>';
$html .= '<strong>' . $event['name'] . '</strong><br>';
$html .= 'Date: ' . $event... | magicoder | php |
You are tasked with implementing a Python function that processes model options and returns the appropriate output based on the specified parameters. The function takes in two optional boolean parameters, `return_distance_clusters` and `return_str`. If `return_distance_clusters` is set to True and the model type is eit... | ```python
from typing import Optional, Union
def process_model_options(return_distance_clusters: Optional[bool] = False,
return_str: Optional[bool] = False,
model_type: str = "KMeans") -> Union[str, None]:
def model_clusters_distances():
# Logic to calc... | magicoder | python |
You are given a positive integer `n`. Your task is to write a function or method to calculate the total number of divisors of the product of all numbers from 1 to `n` (inclusive). For example, if `n` is 3, then the product of all numbers from 1 to 3 is 6, and the total number of divisors of 6 is 4 (1, 2, 3, 6).
Write ... | ```python
def total_divisors(n: int) -> int:
prime_factors = [0] * (n + 1)
for i in range(2, n + 1):
if prime_factors[i] == 0:
for j in range(i, n + 1, i):
count = 0
temp = j
while temp % i == 0:
temp //= i
... | magicoder | python |
You are tasked with creating a reinforcement learning environment for a multi-agent system using the `make_multi_agent` function. The environment is based on the "CartPole-v1" game and is initialized with two agents. However, there is a bug in the code that sets the action space for the environment. The `env.action_spa... | The issue with the code snippet is that it incorrectly sets the `env.action_space_sample` attribute using a lambda function that always returns the `bad_action` dictionary. This causes the environment to always sample the bad action, leading to an error being raised.
To fix the issue, the code should properly set the ... | magicoder | python |
You are tasked with writing a Python script to manage log files using various compression formats. The script should perform the following operations:
1. Compress the 'logs' directory into three different archive formats: ZIP, TAR, and 7z.
2. Rename each compressed archive file in the 'logs' directory to prepend 'stic... | ```python
import lzma
import bz2
import gzip
def make_xz(directory):
with lzma.open('logs.xz', 'w') as xzf:
for root, dirs, files in os.walk(directory):
for file in files:
with open(os.path.join(root, file), 'rb') as f:
xzf.write(f.read())
def make_bz2(direc... | magicoder | python |
You are tasked with implementing a function to draw sprites on a bitmap for a circus-themed video game. The provided code snippet is a part of the function `circusc_state::draw_sprites`, which is responsible for drawing sprites on the screen. The function iterates through the sprite data and extracts information such a... | ```cpp
void circusc_state::draw_sprites(bitmap_ind16 &bitmap, const rectangle &cliprect)
{
int offs;
uint8_t *sr = m_spritebank ? m_spriteram : m_spriteram_2;
for (offs = 0; offs < m_spriteram.bytes(); offs += 4)
{
int code = sr[offs + 0] + 8 * (sr[offs + 1] & 0x20);
int color = sr[offs... | magicoder | cpp |
You are tasked with creating a Python function that processes a request to delete a share link. The function should utilize a serializer to validate the request data and return an appropriate response based on the validation result.
Write a Python function `delete_share_link(request, *args, **kwargs)` that takes in a ... | ```python
from rest_framework.response import Response
from rest_framework import status
from .serializers import DeleteShareLinkSerializer # Import the DeleteShareLinkSerializer from the appropriate module
def delete_share_link(request, *args, **kwargs):
# Create an instance of DeleteShareLinkSerializer with the... | magicoder | python |
You are tasked with creating a program that analyzes the license information from a given URL and extracts the license name and the organization responsible for the license. The license information is provided in the form of a URL to a text file containing the license details. The program should read the content from t... | ```python
import requests
from bs4 import BeautifulSoup
def extract_license_info(url):
response = requests.get(url)
if response.status_code == 200:
soup = BeautifulSoup(response.content, 'html.parser')
license_name = soup.find('title').text
organization = soup.find('a', href="/foundatio... | magicoder | python |
You are tasked with creating a program to handle a word search game. The game board is represented as a 2D grid of characters, and the goal is to find specific words within the grid. The words can be oriented horizontally or vertically, and they may overlap with each other. Your task is to implement a function that can... | ```cpp
#include <iostream>
#include <vector>
#include <string>
enum class Direction { Horizontal, Vertical };
class Board {
private:
std::vector<std::vector<char>> grid;
public:
Board(const std::vector<std::vector<char>>& initialGrid) : grid(initialGrid) {}
std::string read(int row, int col, Direction d... | magicoder | cpp |
You are tasked with implementing a generic data structure in Rust that represents a fixed-size array and provides methods for manipulating the array elements. The array should support operations such as accessing elements, modifying elements, and returning the array's length.
Your task is to implement the `FixedSizeAr... | ```rust
// Define the FixedSizeArray struct
struct FixedSizeArray<T, const N: usize> {
data: [T; N],
}
impl<T: Default, const N: usize> FixedSizeArray<T, N> {
// Constructor method to create a new FixedSizeArray
fn new() -> Self {
FixedSizeArray {
data: [T::default(); N],
}
... | magicoder | rust |
You are tasked with implementing a caching mechanism for a function that performs expensive computations. The cache should store the results of previous function calls to avoid redundant computations. However, the cache has limited space, and if it becomes full, the least recently used (LRU) entry should be evicted to ... | ```python
class Node:
def __init__(self, key, value):
self.key = key
self.value = value
self.prev = None
self.next = None
class Cache:
def __init__(self, capacity):
self.capacity = capacity
self.cache = {}
self.head = Node(0, 0)
self.tail = Node(0... | magicoder | python |
You are tasked with creating a program to optimize the routing of data between devices in a network. The network is represented as a graph, where each node corresponds to a device and the edges represent the flow of data between devices. Your goal is to minimize the number of device converters needed to ensure that dat... | ```cpp
void OptimizeDataFlow(Graph* graph) {
for (auto&& item : graph->nodes) {
for (auto&& output : item.outputs) {
if (output.output_id == Node::kDependency) {
continue;
}
Device* src_device = item.arg.device;
Device* dst_device = graph->nodes[output.node_id].arg.device;
if... | magicoder | cpp |
You are tasked with creating a PHP class that handles REST API requests and responses. Your class should be able to send HTTP requests to a specified endpoint, handle the response, and provide methods for accessing the response data.
Create a class named `RestApiClient` with the following requirements:
- The class sho... | ```php
use Psr\Http\Message\ResponseInterface;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
class RestApiClient
{
private $baseUrl;
private $httpClient;
public function __construct(string $baseUrl)
{
$this->baseUrl = rtrim($baseUrl, '/');
$this->httpClient = new Cli... | magicoder | php |
You are given a code snippet that appears to be incomplete or contains errors. Your task is to analyze the code and identify the issues, then correct the code to make it syntactically and logically correct.
Given code snippet:
```
struct B<T where B:a{typealias e=e
```
Your task is to:
1. Identify and correct any syn... | The given code snippet has several issues that need to be addressed. Let's analyze and correct the code step by step.
1. The generic constraint `where B:a` is incomplete and lacks clarity. It seems like it's trying to specify a protocol or superclass for the generic type `B`, but it's not properly defined.
2. The `ty... | magicoder | swift |
You are tasked with implementing a BatchGenerator class in Python to facilitate the creation of data generators for training and validation sets. The BatchGenerator class should be capable of generating batches of data from input features (X) and corresponding labels (y) for training a machine learning model. The class... | ```python
import numpy as np
class BatchGenerator:
def __init__(self, X, y, shuffle=False):
self.X = X
self.y = y
self.shuffle = shuffle
self.num_samples = X.shape[0]
self.index_array = np.arange(self.num_samples)
if self.shuffle:
np.random.shuffle(self.i... | magicoder | python |
You are tasked with creating a web application that manages Call Detail Records (CDRs) for a telecommunications company. The application should allow users to view, add, edit, and delete CDRs. Each CDR contains information such as the caller's phone number, the recipient's phone number, call duration, call start time, ... | ```php
// CdrController.php
namespace app\controllers;
use Yii;
use yii\web\Controller;
use app\models\Cdr;
use yii\data\ActiveDataProvider;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
class CdrController extends Controller
{
// Other controller actions...
public function actionIndex()
... | magicoder | php |
You are tasked with creating a Python program to visualize data on a map of China using the pyecharts library. The code snippet provided is a part of the program that sets the title and visual map options for the map visualization. Your task is to complete the program by incorporating data and generating the map visual... | ```python
from pyecharts.charts import Map
from pyecharts import options as opts
# Sample dataset (replace with actual dataset)
data = [("北京", 100), ("天津", 50), ("上海", 80), ("重庆", 70), ("河北", 60)]
# Create a map instance for China
china_map = (
Map()
.add("Dataset Title", data, "china")
.set_global_opts(
... | magicoder | python |
You are tasked with implementing a Python function that retrieves a list of running processes on a Unix-based system and returns a dictionary containing process information. The function should be able to handle various scenarios, such as filtering processes by name, user, or status.
You are provided with a partial co... | ```python
import psutil
def get_process_list(name=None, user=None, status=None):
processes = []
try:
for proc in psutil.process_iter(['pid', 'name', 'username', 'cpu_percent', 'memory_info', 'status']):
process_info = proc.info
if (name is None or process_info['name'] == name) a... | magicoder | python |
You are tasked with implementing a function to determine whether a given string is "nice" according to a specific set of rules. A string is considered "nice" if it contains at least one pair of two letters that appears at least twice in the string without overlapping, and it also contains at least one letter which repe... | ```python
def isNice(string):
pair_found = False
repeat_with_gap_found = False
for i in range(len(string) - 1):
pair = string[i:i+2]
if string.count(pair) >= 2:
pair_found = True
break
for i in range(len(string) - 2):
if string[i] == string[i+2]:
... | magicoder | python |
You are given a binary tree represented by a pointer to its root node. Your task is to implement a function `levelOrderBottom` to return the bottom-up level order traversal of the tree's nodes' values. The bottom-up level order traversal means that the nodes at the deepest level should be listed first, followed by the ... | ```cpp
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
vector<vector<int>> levelOrderBottom(TreeNode *root) {
if (root == nullptr) {
return {};
}
vector<vector<int>> result;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
int size = q.size(... | magicoder | cpp |
You are tasked with creating a Python function that retrieves exchange rates from an API and returns the exchange rate for a specific target currency. The function will take in the base currency, the target currency, and the API endpoint as input parameters. You need to implement the function `get_exchange_rate` that p... | ```python
import requests
def get_exchange_rate(base_currency: str, target_currency: str, api_endpoint: str) -> float:
url = f"{api_endpoint}?base={base_currency}&symbols={target_currency}"
print("Requesting ", url)
r = requests.get(url)
root = r.json()
print("Returned ", root)
rates = root.get... | magicoder | python |
You are tasked with implementing a parallelized function to perform a mathematical operation on arrays using OpenMP. The provided code snippet contains macros and a function for setting up OpenMP environment variables.
You need to implement the `fun` function, which takes three arrays `X`, `Y`, and `Z`, along with the... | ```c
// 2. macros //
///////////////
#define EXPORT extern "C" __declspec(dllexport)
/////////////
// 3. main //
/////////////
EXPORT void setup_omp(){ // required when using vs
SetEnvironmentVariable("OMP_WAIT_POLICY", "passive");
}
EXPORT void fun(double *X, double *Y, double *Z, int NX, int NY, int threads)... | magicoder | c |
You are working on a project that involves processing and analyzing large volumes of image data. You have decided to use the `senseTk` library, which provides various tools and functionalities for image processing. One of the key features of the `senseTk` library is its ability to perform image segmentation, which is t... | ```python
import senseTk
def perform_image_segmentation(input_image_path):
# Load the input image
input_image = senseTk.loadImage(input_image_path)
# Perform image segmentation using senseTk library
segmented_image = senseTk.segmentImage(input_image)
return segmented_image
```
In this solution, t... | magicoder | python |
You are tasked with implementing a function to import records from the CIPRS (Court Integrated Program Reporting System) into a database. The provided code snippet is a part of a Python module for importing CIPRS records. The function `import_ciprs_records` takes three parameters: `files`, `user`, and `parser_mode`. Th... | ```python
import logging
from dear_petition.petition.etl.extract import parse_ciprs_document
from dear_petition.petition.types import petition_offense_records, identify_distinct_petitions
logger = logging.getLogger(__name__)
def import_ciprs_records_custom(files, user, parser_mode):
for file in files:
try... | magicoder | python |
You are tasked with implementing a function to determine whether a given string is a valid C++ namespace declaration. In C++, a namespace declaration is a way to organize code into a group of related functionalities. A valid namespace declaration follows the syntax rules defined by the C++ language.
You need to create... | ```cpp
#include <string>
#include <stack>
bool isValidNamespace(const std::string& input) {
std::stack<char> stack;
bool isNamespaceKeywordFound = false;
for (char c : input) {
if (c == '{') {
if (isNamespaceKeywordFound) {
stack.push(c);
}
} else if... | magicoder | cpp |
You are tasked with implementing a retry mechanism for connecting to a database management system (DBMS) in a Python application. The provided code snippet contains configuration parameters for controlling the retry behavior and logging settings.
Your task is to write a Python function that attempts to connect to the ... | ```python
import logging
import time
import random
DB_START_ATTEMPTS = 2
DB_CONNECT_ATTEMPTS = 50
DB_CONNECT_SLEEP = 0.2 # seconds
LOG = logging.getLogger(__name__)
LOG_handler = logging.StreamHandler()
LOG_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
LOG_handler.setFormatter... | magicoder | python |
You are tasked with implementing a data aggregation function that takes a list of data points and aggregates them based on a specified method. The function should default to using the average aggregation method if no method is specified.
You need to implement the `aggregate_data` function, which takes in two parameter... | ```python
def aggregate_data(data_points, aggregate_with='average'):
if not data_points:
return None # Return None for empty input list
if aggregate_with == 'average':
return sum(data_points) / len(data_points)
elif aggregate_with == 'sum':
return sum(data_points)
elif aggregat... | magicoder | python |
You are given the definition of a singly linked list node and a function to reverse a linked list. Your task is to implement a function to reverse every k nodes (where k is a positive integer) in the linked list. If the number of nodes in the linked list is not a multiple of k, then the remaining nodes should be left a... | ```python
def reverse_k_nodes(head, k):
if k <= 1 or head is None:
return head
current = head
next_node = None
prev_tail = None
new_head = None
while current is not None:
count = 0
prev = None
tail = current
while current is not None and count < k:
... | magicoder | python |
You are tasked with implementing a custom iterator class in Python that selects elements randomly from a given list. Your iterator should allow for repeated random selections until all elements have been iterated through at least once. Additionally, the iterator should be able to reset and start the random selection pr... | ```python
import random
from typing import List
class RandomChoiceIterator:
def __init__(self, data: List[int]):
self.data = data
self.index = 0
self.shuffled_data = data.copy()
random.shuffle(self.shuffled_data)
def __iter__(self):
return self
def __next__(self) -... | magicoder | python |
You are tasked with implementing a C++ type trait to determine whether a given type is an array or not. The provided code snippet is a part of the ArduinoJson library and contains a partial implementation of the `is_array` type trait. Your task is to complete the implementation of the `is_array` type trait to correctly... | ```cpp
// ArduinoJson - arduinojson.org
// Copyright <NAME> 2014-2018
// MIT License
#pragma once
namespace ArduinoJson {
namespace Internals {
template <typename T>
struct is_array : false_type {};
template <typename T>
struct is_array<T[]> : true_type {};
template <typename T, size_t N>
struct is_array<T[N]> : t... | magicoder | cpp |
You are tasked with implementing a data preprocessing pipeline for natural language processing (NLP) tasks. The pipeline involves loading and processing text data using specific configurations and parameters. Your goal is to write a function that takes in raw text data and various settings, and outputs the preprocessed... | ```python
import spacy
import torch
from torch.utils.data import DataLoader, Dataset
import numpy as np
class CustomDataset(Dataset):
def __init__(self, data, labels, tokenizer, max_length, limit_vocab_size):
self.data = data
self.labels = labels
self.tokenizer = tokenizer
self.max_... | magicoder | python |
You are tasked with creating a program to analyze and visualize typing speed data. The program should calculate the average words per minute (WPM) of a user and display it in a bar chart using a JavaScript library.
You are given a code snippet that sets up the configuration for the chart. The `responsive` property is ... | ```javascript
function generateWPMChart(data) {
// Calculate average WPM
const averageWPM = data.reduce((total, wpm) => total + wpm, 0) / data.length;
// Chart configuration
const chartConfig = {
type: 'bar',
data: {
labels: data.map((_, index) => `Typing Session ${index + 1}`),
datasets: [... | magicoder | javascript |
You are given a 2D maze represented by a 2D array of characters. The maze consists of cells, some of which are blocked (denoted by 'X') and others are open (denoted by '0'). The objective is to find a path from the top-left corner of the maze to the bottom-right corner, moving only right or down, and avoiding the block... | ```cpp
#include <iostream>
using namespace std;
bool isPath(int m, int n, char maze[10][10]) {
bool dp[10][10] = {0}; // Initialize a boolean array to store the path information
// Base case: the destination cell is reachable if it is not blocked and the previous cell is reachable
dp[0][0] = (maze[0][0] ... | magicoder | cpp |
You are tasked with creating a program to manage a database of books using Android's content provider and loader framework. Your program should retrieve book information from a content provider and display it in a list view. Each book entry should include the title, author, and publication year.
You are provided with ... | ```java
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorL... | magicoder | java |
You are tasked with creating a Python function that processes a list of texts using a part-of-speech (POS) tagger and stores the POS tags for each text in a specific data structure. Additionally, the function should handle a separate list of test texts and store their POS tags as well. Your task is to implement the fun... | ```python
from typing import List, Tuple
def process_pos_tags(train_text: List[str], test_text: List[str]) -> Tuple[List[List[Tuple[str, str]]], List[List[Tuple[str, str]]]]:
all_pos_tags = []
test_pos_tags = []
pos_tagger = YourPOSTagger() # Replace YourPOSTagger with the actual POS tagger instance
... | magicoder | python |
You are tasked with creating a function that simulates a simplified password encryption process. The function should take a password as input and return the encrypted hash of the password using a salt generated with a given complexity level.
Write a function `encryptPassword` that takes a password string and a complex... | ```typescript
import bcrypt from 'bcrypt';
const encryptPassword = async (password: string, complexityLevel: number): Promise<string> => {
const salt = await bcrypt.genSalt(complexityLevel);
const hash = await bcrypt.hash(password, salt);
return hash;
};
``` | magicoder | typescript |
You are tasked with creating a program that processes command-line arguments to determine the appropriate action to take. The program should handle a specific set of target names and execute corresponding actions based on the provided target.
Your program should accept a single command-line argument representing the t... | ```bash
TARGET=$1
case $TARGET in
"GDSwift"*)
# Execute action for GDSwift target
echo "Processing GDSwift target..."
;;
"AnotherTarget"*)
# Execute action for AnotherTarget
echo "Processing AnotherTarget..."
;;
*)
# Handle unrecognized targets
echo "Error: Unrecognized target nam... | magicoder | shell |
You are tasked with implementing a class to represent a directed graph and providing a method to find the shortest path between two nodes using Dijkstra's algorithm.
Your task is to implement the `DirectedGraph` class with the following methods:
- `addNode(node)`: Add a node to the graph.
- `addEdge(source, destinatio... | ```java
import java.util.*;
class DirectedGraph {
Map<String, Node> nodes;
public DirectedGraph() {
this.nodes = new HashMap<>();
}
public void addNode(Node node) {
nodes.put(node.id, node);
}
public void addEdge(Node source, Node destination, int weight) {
source.edg... | magicoder | java |
You are tasked with implementing a Python class for performing backups. The class, named `Backup`, has the following methods and attributes:
Attributes:
- `included_folders`: a list of folders to be included in the backup
- `excluded_folders`: a list of folders to be excluded from the backup
- `output_dir`: the direct... | ```python
import os
class Backup:
size_limit = 0 # Default size limit
def __init__(self, included_folders, excluded_folders, output_dir, size_limit):
self.included_folders = included_folders
self.excluded_folders = excluded_folders
self.output_dir = output_dir
self.size_limit ... | magicoder | python |
You are tasked with implementing a function that links values in a lambda calculus expression to a stack of strings. The lambda calculus expression is represented using a custom data structure, and the linking process involves replacing certain values with their corresponding linked values from the stack.
You are give... | ```rust
impl LinkedLambda {
fn link(&self, stack: &[String]) -> Value<LinkedLambda> {
match self {
Value::Lambda(lambda) => Value::Lambda(lambda.link(stack).into()), // Recursively link the lambda
Value::Tuple(fields) => {
Value::Tuple(fields.iter().map(|field| field.... | magicoder | rust |
You are tasked with creating a Python function that processes a list of package dependencies and returns a dictionary representing the dependencies in a more structured format. The input list contains package names and their dependencies in a specific format, and the function should parse this information and return a ... | ```python
def process_dependencies(install_requires):
dependencies_dict = {}
for item in install_requires:
if ':' in item:
package, dependencies = item.split(':')
dependencies_dict[package.strip()] = [dep.strip() for dep in dependencies.split(',')]
else:
depen... | magicoder | python |
You are tasked with creating a web application that displays detailed information about equipment registered in a system. The application should utilize the Yii PHP framework and display the equipment details using the `DetailView` widget. Your task is to write a function that takes an equipment model and generates the... | ```php
/**
* Generates the HTML code for displaying equipment details using the DetailView widget.
*
* @param EquipmentRegister $model the equipment model
* @return string the HTML code for displaying the equipment details
*/
function generateEquipmentDetailView($model) {
return DetailView::widget([
'm... | magicoder | php |
You are tasked with creating a Discord bot command that retrieves a list of League of Legends (LoL) players based on the specified region and player pseudonym. The bot command should take in the region and player pseudonym as input parameters and then fetch the list of LoL players from the specified region matching the... | ```python
import requests
# Function to fetch LoL players based on region and pseudonym
def fetch_lol_players(region, pseudonym):
api_key = 'your_riot_games_api_key'
base_url = 'https://{region}.api.riotgames.com/lol/summoner/v4/summoners/by-name/{pseudonym}'
url = base_url.format(region=region, pseudonym=... | magicoder | python |
You are given a list of integers representing the daily temperature values for a particular location. Your task is to write a Python function to calculate the mean temperature for each month. The input list contains temperature values for each day in chronological order, and each month may have a different number of da... | ```python
from typing import List
def calculate_monthly_mean(temperatures: List[int]) -> List[float]:
months = {}
month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
month_temps = [0] * 12
for i, temp in enumerate(temperatures):
month = i % 12
month_temps[month] += temp
... | magicoder | python |
You are tasked with creating a Python program to manage Docker containers. Your program should be able to remove a specified Docker container and then remove the corresponding Docker image. You are given the following information:
- The code snippet provided demonstrates the commands to remove a Docker container named... | ```python
import docker
def remove_container_and_image(container_name):
client = docker.from_env()
try:
# Remove the specified container
client.containers.get(container_name).remove(force=True)
# Retrieve the image name and tag associated with the removed container
... | magicoder | python |
You are tasked with creating a program that manages translations for a multilingual application. The program should be able to load and retrieve translations based on a specified language code. Each translation is represented as a key-value pair, where the key is a string identifier and the value is the translated text... | ```csharp
public class TranslationManager
{
private Dictionary<string, Dictionary<string, string>> translations;
public void LoadTranslations(string languageCode)
{
// Assume translations are loaded from a data source such as a database or file
// For demonstration purposes, translations ar... | magicoder | csharp |
You are working on a data management system that involves defining and managing tables and their columns. You need to create a Python function that takes a list of table names and their corresponding column names as input and generates SQL Alchemy models for these tables and columns.
Write a function `generate_sqlalch... | ```python
from sqlalchemy import Column, String, Integer
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
def generate_sqlalchemy_models(table_columns):
model_definitions = ""
for table_name, columns in table_columns.items():
table_class_name = table_name.capitalize() ... | magicoder | python |
You are working as a system administrator for a company that uses a Unix-based operating system. Your task is to create a script that automates the process of applying patches and testing them on the system. The provided code snippet is a part of the script that prepares for applying patches and testing. The script inc... | ```sh
# Contents of ver.sh
# Set the version variable VP
VP="1.2.3"
# Complete script for applying patches and testing
#!/bin/sh
# Prepara para aplicar parches y probar
. ./ver.sh
cd /usr
cmd="doas rsync --delete -ravz src${VP}-orig/ src/"
echo $cmd
eval $cmd
cmd="(cd /usr/src/lib/libc; doas make clean)"
echo $cmd
ev... | magicoder | shell |
You are tasked with creating a Python function to calculate the average Seebeck coefficient for a given material. The Seebeck coefficient is a measure of the magnitude of the thermoelectric effect in a material, representing its ability to generate a voltage difference when subjected to a temperature gradient. The func... | ```python
def calculate_average_seebeck(seebeck_coefficients):
average_seebeck = {"n": {}, "p": {}}
for carrier in ["n", "p"]:
for temperature, conditions in seebeck_coefficients[carrier].items():
average_seebeck[carrier][temperature] = {}
for condition, values in conditions.ite... | magicoder | python |
You are tasked with understanding and refactoring a Python code snippet that initializes various services and configurations for a web application. Your goal is to identify potential issues and improve the code's structure and readability.
Given the provided code snippet, analyze the following aspects:
1. Identify any... | The provided code snippet initializes various services and configurations for a web application. However, it contains some potential issues and lacks clarity in its structure. Here's a refactored version of the code with explanations for the changes made:
```python
from .services import export, mail, tickets, cart, or... | magicoder | python |
You are tasked with designing a module system for a financial management software. The software needs to handle various aspects of financial transactions, including bills, deposits, withdrawals, money nodes, organizations, persons, products, statements of accounts, transaction entities, transactions, types, finance, an... | To organize the financial management components and handle database connections, you can create the following module structure:
```rust
mod finance {
pub mod bills;
pub mod depodraws;
pub mod money_nodes;
pub mod organisations;
pub mod persons;
pub mod products;
pub mod statement_of_account... | magicoder | rust |
You are tasked with creating a function to validate booking times for a scheduling system. The function should determine whether a given time string is a valid booking time in the format "HH:MM" (24-hour format). The function should return true if the time is valid and false otherwise.
You are provided with a code sn... | ```php
public static function isValidBookingTime(string $dateString): bool
{
$format = 'H:i';
$dateObj = \DateTime::createFromFormat($format, $dateString);
// Check if the date string matches the expected format and is a valid time
return $dateObj !== false && $dateObj->format($format) === $dateString;... | magicoder | php |
You are tasked with creating a Python function that simulates a guessing game. The game will involve guessing a secret word within a limited number of attempts. The secret word will be stored in a variable named `secret`. The player will input their guesses, and the function will provide feedback on whether the guess i... | ```python
def guess_game(secret, max_attempts):
attempts = 0
while attempts < max_attempts:
guess = input("Enter your guess: ")
if guess == secret:
return "Congratulations! You guessed the word correctly.\nYou won!"
else:
attempts += 1
if attempts < ma... | magicoder | python |
You are tasked with creating a log message generator for a network security application. The generator should produce log messages in a specific format using predefined lists of hostnames, IP addresses, source IPs, usernames, facilities, and severities. The log message format is given by the `FORMAT` string, which incl... | ```python
import random
import time
HOSTNAME = ['defence-first.rs', 'defence-first.de', 'defence-first.ru']
HOSTIP = ['172.16.17.32', '192.168.127.12', '172.16.58.3']
SOURCEIP = ['192.168.3.11', '192.168.127.12', '172.16.58.3', '172.16.58.3', '172.16.17.32']
USERNAMES = ['user1', 'user2', 'user3', 'user4', 'user5']
FA... | magicoder | python |
You are tasked with implementing a lazy loading mechanism for Python modules. Lazy loading is a design pattern where the actual loading of a resource is delayed until it is accessed for the first time. In this case, you need to create a `lazy` function that takes the name of a module as a string and returns a lazy-load... | ```python
def lazy(module_name):
class LazyModule:
def __init__(self, module_name):
self.module_name = module_name
self.module = None
def __getattr__(self, attr):
if self.module is None:
self.module = __import__(self.module_name)
retur... | magicoder | python |
You are tasked with creating a Python program that utilizes the `python-holidays` library to determine whether a given date is a holiday in a specific country. Your program should prompt the user to input a date and a country, and then output whether the date is a holiday in that country or not.
Your program should us... | ```python
import holidays
from datetime import date
def check_holiday():
try:
input_date = input("Enter the date (YYYY-MM-DD): ")
input_country = input("Enter the country code (e.g., US, GB, IN): ")
# Fetch the list of holidays for the specified country
holiday_list = holidays.Coun... | magicoder | python |
You are tasked with simulating a game of combat using two decks of cards. The game is played between two players, and each player has their own deck of cards. The game proceeds in rounds, with each round having a specific set of rules for determining the winner and updating the players' decks.
The game of combat is pl... | ```python
from typing import List
def play_combat(deck1: List[int], deck2: List[int]) -> int:
deck1 = deck1.copy()
deck2 = deck2.copy()
while deck1 and deck2:
card1 = deck1.pop(0)
card2 = deck2.pop(0)
if card1 > card2:
deck1.extend([card1, card2])
elif card2 > ... | magicoder | python |
You are tasked with implementing a data structure called `LimitedSet` that represents a set with a maximum capacity. The `LimitedSet` should have the following functionalities:
- Initialize with a maximum capacity and an optional initial list of elements.
- Add elements to the set, with the following conditions:
- If... | ```python
from typing import List, Any
from random import random
class LimitedSet:
def __init__(self, capacity: int, initial_elements: List = []):
self.capacity = capacity
self.elements = initial_elements[:capacity]
def add(self, element: Any) -> Any:
if len(self.elements) < self.capac... | magicoder | python |
You are tasked with implementing a data shredder and materializer for a Parquet schema in TypeScript. The provided code snippet outlines the interface for the shredder module, which contains two functions: `shredRecord` and `materializeRecords`.
The `shredRecord` function takes in three parameters:
1. `schema`: A Parq... | ```typescript
import { ParquetSchema, RowInterface, RowBufferInterface } from './types'; // Assuming the types file contains the necessary interfaces
export namespace shredder {
export function shredRecord(schema: ParquetSchema, record: RowInterface, buffer: RowBufferInterface): void {
// Implementation of... | magicoder | typescript |
You are tasked with implementing a thread-safe resource disposal mechanism using C++11's standard library features. The provided code snippet includes a catch block and a mutex declaration, which are essential components for the problem.
Your task is to create a class, `ResourceDisposer`, that manages the disposal of ... | ```cpp
#include <mutex>
#include <vector>
#include <memory>
class ResourceDisposer {
public:
void addResource(std::shared_ptr<Resource> resource) {
std::lock_guard<std::mutex> lock(disposeMutex);
resources.push_back(resource);
}
void disposeResources() {
std::lock_guard<std::mutex>... | magicoder | cpp |
You are working on a Tekton pipeline for a cloud-native application deployment. The pipeline is designed to retrieve sensitive information from a secret store and use it during the deployment process. The `echo $TEKTON_SECRET` command is used to print the value of the environment variable `TEKTON_SECRET` to the console... | ```python
import os
import base64
def retrieve_secret():
tekton_secret = os.environ.get('TEKTON_SECRET')
if tekton_secret:
return tekton_secret
else:
raise ValueError("TEKTON_SECRET environment variable is not set")
def deploy_with_secret(encrypted_secret):
# Example: Use the encrypted... | magicoder | python |
You are tasked with implementing a custom Swift attribute that restricts the visibility of certain functions when imported from another module. The attribute should prevent specific functions from being accessible when imported by other modules, effectively hiding them from external use.
Your task is to create a custo... | ```swift
// Custom Swift attribute to restrict function visibility when imported from another module
@_spi(OtherModule)
public func extendedFunctionShouldntAppear() {}
// Module A
// Define a function with the @_spi attribute
@_spi(ModuleB)
public func restrictedFunction() {
print("This function should not be acce... | magicoder | swift |
You are given a list of prefixes and a mask value. Your task is to implement a function that takes the list of prefixes, the mask value, and an index as input, and returns a list of indices where the bitwise AND of the index and the mask is equal to any of the prefixes.
The function signature is:
```python
def find_ma... | ```python
from typing import List
def find_matching_indices(prefixes: List[int], mask: int, index: int) -> List[int]:
output = []
for prefix in prefixes:
if (index & mask) == prefix:
output.append(prefix)
return output
```
The `find_matching_indices` function iterates through the list ... | magicoder | python |
You are tasked with implementing a slot processing system for a virtual inventory in a game. The inventory consists of slots, each of which can hold an ItemStack. The code snippet provided is a part of the processing logic for these slots. The `process` function takes an ItemStack `oldStack` and performs some operation... | Issues in the provided code snippet:
1. The comparison `if (newStack == oldStack)` is checking for reference equality between the newStack and oldStack, which is not the intended behavior. It should check for value equality instead.
2. The condition `if (slot.isItemValid(oldStack))` is not being used effectively as it ... | magicoder | java |
You are working on a project that involves classifying data using machine learning algorithms. You have a dataset containing various features and corresponding labels. Your task is to create a program that uses the K-Nearest Neighbors (KNN) and Linear Discriminant Analysis (LDA) algorithms to classify the data and visu... | ```python
import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
# Load the dataset (replace with actual dataset loading code)
features, labels = load... | magicoder | python |
You are tasked with implementing a data anonymization function that takes a string as input and transforms it based on certain rules. The function should replace alphabetic characters with shuffled alphabetic characters and numeric characters with shuffled numeric characters. Additionally, for a specific data type (e.g... | ```javascript
/**
* Anonymizes the input value based on the specified data type.
* @param {string} value - The input value to be anonymized.
* @param {AnonymizeDataType} type - The data type for anonymization.
* @returns {string} - The anonymized value.
*/
function anonymizeValue(value, type) {
const lowerAlpha ... | magicoder | javascript |
You are tasked with implementing a function to validate a given project path in a C++ application. The project path is represented as a string and needs to adhere to specific criteria to be considered valid. The function should return a boolean value indicating whether the project path is valid or not.
The project pat... | ```cpp
#include <iostream>
#include <string>
#include <regex>
bool isValidProjectPath(const std::string& projectPath) {
// Check if the project path is not empty
if (projectPath.empty()) {
return false;
}
// Check if the project path contains any whitespace characters
if (std::any_of(proje... | magicoder | cpp |
You are tasked with creating a Java class to manage versioning information for a software application. The class should handle the version number, build date, and commit information. Your task is to implement the `VersionNo` class and ensure that it can be used to manage and display the application's versioning details... | ```java
// VersionNo class to manage versioning information
class VersionNo {
private int major;
private int minor;
private int patch;
private String label;
// Constructor to initialize version details
public VersionNo(int major, int minor, int patch, String label) {
this.major = major;... | magicoder | java |
You are tasked with creating a Rust module that implements a simple calculator. The calculator should support basic arithmetic operations such as addition, subtraction, multiplication, and division. Additionally, it should provide a function to calculate the square root of a number.
Your task is to implement the modul... | ```rust
// m3.rs
use std::f64;
pub fn add(a: f64, b: f64) -> f64 {
a + b
}
pub fn subtract(a: f64, b: f64) -> f64 {
a - b
}
pub fn multiply(a: f64, b: f64) -> f64 {
a * b
}
pub fn divide(a: f64, b: f64) -> Option<f64> {
if b == 0.0 {
None
} else {
Some(a / b)
}
}
pub fn squa... | magicoder | rust |
You are tasked with implementing a function to write a vector of arterial input function (AIF) values to a file. The function should validate that the size of the input vector matches the number of predefined times, and if not, it should throw an exception with a descriptive error message.
You are given the following ... | ```cpp
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <stdexcept>
#include <boost/format.hpp>
class mdm_exception : public std::exception {
public:
mdm_exception(const std::string& func, const boost::format& message) {
std::cerr << "Exception in function " << func << ":... | magicoder | cpp |
You are tasked with creating a Python function that processes feature sets for a software project. The function should take a list of feature sets and a project name as input and return the count of features in each feature set for the specified project. Additionally, the function should ensure that each feature set co... | ```python
def process_feature_sets(feature_sets, project):
feature_counts = {}
for feature_set in feature_sets:
if project in feature_set["features"]:
count = feature_set["features"][project]
if "spec" in feature_set and "features" in feature_set["spec"]:
expected... | magicoder | python |
You are working on a project to monitor specific high-level triggers (HLT) in a physics analysis framework. The code snippet provided is a part of the configuration for monitoring the VBF (Vector Boson Fusion) SUSY (Supersymmetry) triggers in the framework. The configuration involves setting up a monitoring sequence fo... | ```python
import re
def parse_hlt_monitoring_config(config):
result = {}
folder_match = re.search(r"FolderName\s*=\s*'([^']*)'", config)
if folder_match:
result["FolderName"] = folder_match.group(1)
hlt_paths_match = re.search(r"hltPaths\s*=\s*\[([^\]]*)\]", config)
if hlt_paths_m... | magicoder | python |
You are tasked with implementing a function to calculate the time complexity of a given algorithm. The function `timed.caller` takes four arguments: `dummy`, `n`, `i`, and `prob_id`. The `dummy` argument is a function representing the algorithm to be analyzed, `n` is the size of the input, `i` is the number of iteratio... | ```python
def calculate_time_complexity(dummy, n, i, prob_id):
import time
start_time = time.time()
for _ in range(i):
dummy(n)
end_time = time.time()
elapsed_time = end_time - start_time
# Assuming linear growth in time with input size
time_complexity = elapsed_time / n
if t... | magicoder | python |
You are tasked with simulating the movement of a robotic arm using a programming language that supports object-oriented concepts. The robotic arm has various components, each of which can be manipulated independently. The code snippet provided is a part of a larger program that controls the movement of the robotic arm.... | ```python
class RoboticArm:
def __init__(self):
self.rightArm = ArmComponent()
def simulateArmMovement(self, sequence):
for command in sequence:
component_name, action, *args = command
component = getattr(self, component_name)
if action == 'attach':
... | magicoder | python |
You are tasked with implementing a simplified version of a presenter pattern in Swift. The provided code snippet is part of a larger application that manages screens and their corresponding presenters. The `submitPersonScreen` function is called when a user submits a form to add a new person, and it is responsible for ... | ```swift
// Implementation of SubmitPersonScreenView protocol
class PersonSubmitScreen: SubmitPersonScreenView {
func submitPersonScreen(_ screen: SubmitPersonScreenView, didSubmit context: PersonContext) {
// Implementation for handling the submitted person context
// This could involve processing ... | magicoder | swift |
You are tasked with implementing a function that validates a given URL against a set of predefined rules. The function should return a boolean value indicating whether the URL is valid according to the specified criteria.
The function should be named `validateURL` and should take a single parameter:
- `url` (string): ... | ```javascript
function validateURL(url) {
const urlPattern = /^(https?:\/\/)([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.[a-z]{2,}(\/[a-zA-Z0-9-\/]*)?$/;
return urlPattern.test(url);
}
```
The `validateURL` function uses a regular expression to match the input URL against the specified rules. Here's a breakdown of the regular... | magicoder | javascript |
You are tasked with implementing a Gaussian density calculation for 2D and 3D point clouds. The Gaussian density is a measure of the density of points around each point in space, calculated using a Gaussian function. Your task is to create a Python class that can compute the Gaussian density for a given set of points i... | ```python
import numpy as np
import freud
class GaussianDensity:
def __init__(self, width, r_max, sigma):
self.width = width
self.r_max = r_max
self.sigma = sigma
self.density = None
def compute(self, system):
box, points = system
if len(points[0]) == 2: # 2D p... | magicoder | python |
You are given a scenario where a group of friends is planning a trip to a theme park. Each friend has a specific budget and a list of rides they want to go on. The goal is to maximize the total happiness of the group by allocating the friends to rides in such a way that their combined happiness is maximized, while resp... | ```rust
fn maximize_happiness(happiness: &[i32], cost: &[i32], budget: i32) -> i32 {
let n = happiness.len();
let mut dp = vec![vec![0; (budget + 1) as usize]; n + 1];
for i in 1..=n {
for j in 0..=budget as usize {
if cost[i - 1] > j as i32 {
dp[i][j] = dp[i - 1][j];
... | magicoder | rust |
You are tasked with implementing a button component in a React application. The button component can have two types: "Accept" and "Cancel". The appearance and behavior of the button should change based on its type. The "Accept" button should have a yellow background with a specific SVG shape, and the "Cancel" button sh... | ```jsx
import React from 'react';
const ButtonType = {
Accept: 'accept',
Cancel: 'cancel',
};
const Button = ({ type, value }) => {
const handleClick = () => {
if (value.onPress) {
value.onPress();
}
};
if (type === ButtonType.Accept) {
return (
<div className={`accept-button-box ${... | magicoder | jsx |
You are tasked with implementing a data processing class that can handle different types of columns in a dataset. The class should have methods to process string and timestamp columns and return the processed values. However, the given code snippet contains an incomplete implementation of the data processing class. You... | ```java
public class DataProcessor {
// ... other methods and fields
@Override
public Double stringColumn(String value) {
return Double.parseDouble(value);
}
@Override
public Double timestampColumn(String value) {
return Double.parseDouble(value);
}
public Integer inte... | magicoder | java |
You are tasked with implementing a custom error handling system for a messaging application. The system should be able to handle different types of errors that may occur during message processing. To achieve this, you need to define an enum for the different types of error messages and implement a function to handle th... | ```rust
// Define the enum for message types
enum MessageType {
InvalidMessageType,
NetworkError,
PermissionDenied,
InvalidRecipient,
}
// Implement the function to handle errors
fn handle_error(message_type: MessageType) -> &'static str {
match message_type {
MessageType::InvalidMessageTyp... | magicoder | rust |
You are working on a project management system for a company that employs different types of employees with various skills. The company uses an enum class called `EmployeeSkill` to represent the skills that an employee can possess. The `EmployeeSkill` enum class has the following definition:
```java
public enum Employ... | ```java
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class EmployeeService {
public List<Employee> findEmployeesWithSkills(Set<EmployeeSkill> requiredSkills, List<Employee> allEmployees) {
List<Employee> employeesWithSkills = new ArrayList<>();
... | magicoder | java |
You are tasked with implementing a Mean Squared Error (MSE) class for a neural network framework. The MSE class is responsible for computing the loss and its derivative with respect to the network's predictions. The provided code snippet is a part of the `MSE` class and shows the `deriv` method, which computes the deri... | ```cpp
#include <vector>
#include <cstdint>
class MSE {
private:
double loss;
public:
// Constructor and other methods are not shown for brevity
// Compute the derivative of the MSE loss function
std::vector<double> deriv(const std::vector<double>& prediction, int8_t expected_int) const {
// ... | magicoder | cpp |
You are tasked with simulating a security system in a high-security facility. The security system consists of a series of scanners positioned at various depths within the facility. Each scanner has a location that moves back and forth along a track, and they are synchronized to start at different times. Your goal is to... | ```rust
fn find_minimum_delay(system: &SecuritySystem) -> isize {
let mut delay = 0;
loop {
if system.check(delay as usize) {
return delay as isize;
}
delay += 1;
if delay > std::usize::MAX as isize {
return -1;
}
}
}
```
The `find_minimum_del... | magicoder | rust |
You are working on a deployment script for a web application that involves setting up a MySQL database and granting privileges to a user. The script needs to execute SQL commands to create a database and grant specific privileges to a user.
Write a Bash script that takes the following inputs:
- `$username`: MySQL user... | ```bash
#!/bin/bash
# Input variables
username=$1
password=$2
user=$3
pass=$4
# Check if all input variables are provided
if [ -z "$username" ] || [ -z "$password" ] || [ -z "$user" ] || [ -z "$pass" ]; then
echo "Usage: ./deploy.sh <username> <password> <user> <pass>"
exit 1
fi
# Execute SQL commands to create ... | magicoder | shell |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.