query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with implementing a Redux slice for a cryptocurrency swapping feature. The provided code snippet includes the definition of a Redux slice for handling swapping actions and a reducer function. The slice contains action creators for setting the amount, token, swapping inputs, setting a dialog, and clearing... | ```javascript
// Action creator for swap failure
export const swapFailed = (errorMessage) => {
return {
type: 'swap/swapFailed',
payload: errorMessage
}
}
// Modified swapReducer to handle swapFailed action
const initialState = {
amount: 0,
token: null,
inputs: null,
dialog: null,
error: null //... | magicoder | javascript |
You are tasked with implementing a Python class that acts as a rate limiter for making HTTP requests. The rate limiter should prevent making more than a certain number of requests within a specified time frame. If the limit is exceeded, the rate limiter should raise a custom exception. Additionally, the rate limiter sh... | ```python
import urllib.parse
from time import time, sleep
import requests
class TooManyRequestsException(Exception):
pass
class UnexpectedCodeException(Exception):
pass
class RateLimiter:
def __init__(self, limit: int, interval: float):
self.limit = limit
self.interval = interval
... | magicoder | python |
You are tasked with creating a Python function that simulates a random word requester. The function should retrieve a random word and its definition from a MongoDB database and log the timestamp of the access. You are required to implement the function `random_word_requester` that accomplishes the following:
- Access ... | ```python
from pymongo import MongoClient
from datetime import datetime as dt
# Assuming the MongoDB client is already set up
client = MongoClient('mongodb://localhost:27017/')
db = client['your_database_name']
defs = db['your_collection_name']
def random_word_requester():
'''
This function returns a random w... | magicoder | python |
You are tasked with implementing a Swift protocol and its associated types and methods. The protocol `P` has an associated type `f` and a nested protocol `A`. Protocol `A` has an associated type `B` and a method `a`. Your goal is to create the protocol `P` and its nested protocol `A`, along with their associated types ... | ```swift
protocol A {
associatedtype B
func a() -> B
}
protocol P {
associatedtype f
var aInstance: A { get }
}
// Example implementation
struct ExampleA: A {
typealias B = Int
func a() -> Int {
return 42
}
}
struct ExampleP: P {
typealias f = String
var aInstance: A = Exa... | magicoder | swift |
You are tasked with implementing a Python class to represent a specific type of monoid operation. A monoid is a mathematical structure consisting of a set of elements and an associative binary operation that combines any two elements of the set to produce another element from the same set. In this problem, you will cre... | ```python
class Monoid:
def __init__(self, identity, operation):
self.identity = identity
self.operation = operation
def operate(self, a, b):
return self.operation(a, b)
# Example usage:
# Define the identity and operation for the monoid
identity = 0 # Example identity element
operati... | magicoder | python |
You are tasked with implementing a priority queue for data creation and removal. The priority queue should be able to manage different data creation actions based on their priority for creation and removal.
You are given a code snippet that defines a `DataCreatorAction` class. This class represents an action for creat... | ```python
from typing import Callable
import heapq
class DataPriorityQueue:
def __init__(self):
self.queue = []
self.index = 0
def add_action(self, action: DataCreatorAction):
heapq.heappush(self.queue, (action.priority_for_removal, -action.priority_for_creation, self.index, action.fun... | magicoder | python |
You are tasked with implementing a simplified version of a dependency injection container in C#. The container should be able to resolve and instantiate registered types based on their dependencies.
Your task is to create a class called `DependencyContainer` with the following requirements:
- The container should be a... | ```csharp
public enum Lifetime
{
Transient,
Singleton
}
public class DependencyContainer
{
private readonly Dictionary<Type, Type> _registeredTypes = new Dictionary<Type, Type>();
private readonly Dictionary<Type, object> _singletonInstances = new Dictionary<Type, object>();
public void Register<T... | magicoder | csharp |
You are tasked with creating a Discord bot that can cycle through different statuses and perform specific actions when it becomes ready. The bot should be able to change its status at regular intervals and execute additional tasks upon initialization. Your goal is to implement the necessary functionality to achieve thi... | To achieve the desired functionality, you can use the `asyncio` library to schedule the status changes and define the actions to be performed when the bot becomes ready. Below is a comprehensive solution to implement the required behavior:
```python
import discord
import asyncio
from itertools import cycle
# Initiali... | magicoder | python |
You are tasked with creating a program that manages a simple inventory system using Python's `shelve` module. The program should allow users to add, remove, update, and display items in the inventory. Additionally, the program should support command-line arguments using the `argparse` module for specifying the inventor... | ```python
import shelve
import argparse
import os
def create_inventory_file(file_name):
if not os.path.exists(file_name):
with shelve.open(file_name) as inventory:
pass # Create an empty inventory file
def add_item(file_name, item_name, quantity, price):
with shelve.open(file_name) as inv... | magicoder | python |
You are tasked with implementing a custom data structure called `UniqueStack` that behaves like a stack but only allows unique elements to be stored. The `UniqueStack` should support the following operations:
1. `push(element)`: Add an element to the top of the stack if it is not already present in the stack.
2. `pop()... | ```javascript
class UniqueStack {
constructor() {
this.stack = [];
this.set = new Set();
}
push(element) {
if (!this.set.has(element)) {
this.stack.push(element);
this.set.add(element);
}
}
pop() {
if (this.stack.length > 0) {
const element = this.stack.pop();
thi... | magicoder | javascript |
You are given a Python code snippet that simulates a process of selecting coins to reach a target sum. Your task is to implement a function that achieves the same functionality as the code snippet.
You need to implement a Python function `select_coins(coins, target)` where:
- `coins` is a list of objects representing ... | ```python
import random
def select_coins(coins, target):
selected_coins = set()
selected_coins_sum = 0
target_reached = False
while not target_reached:
coin = random.choice(coins)
if (len(selected_coins) == 0 and bool(random.getrandbits(1))) or (len(selected_coins) == 1 and coin not in... | magicoder | python |
You are given a list of reputation scores of players in a game, represented by the list `reputacoes_dos_jogadores`. The reputation scores are floating-point numbers. The code snippet provided is a part of a program that attempts to round the reputation scores to a certain number of decimal places. However, there seems ... | ```python
from typing import List
def round_reputation_scores(reputacoes_dos_jogadores: List[float]) -> List[float]:
rounded_scores = []
for score in reputacoes_dos_jogadores:
casas_dec = 12
booleano = True
while booleano:
if round(score, casas_dec) != round(rounded_scores[-... | magicoder | python |
You are tasked with creating a Python class that represents a political candidate for an election. The class should have attributes to store the candidate's name, party affiliation, and a list of elections they are participating in. Additionally, the class should have a method to add a new election to the candidate's l... | ```python
class Candidate:
def __init__(self, name, party_affiliation):
self.name = name
self.party_affiliation = party_affiliation
self.elections = []
def add_election(self, election):
self.elections.append(election)
def get_elections(self):
return self.elections
`... | magicoder | python |
You are tasked with creating a program that simulates a simple game of dice rolling. The game consists of the following rules:
- The player starts with a score of 0.
- The player rolls a six-sided die, and the number rolled is added to their score.
- If the player rolls a 6, they get an extra turn and the score from th... | ```python
import random
def simulate_dice_game():
score = 0
while True:
roll = random.randint(1, 6)
if roll == 6:
score += roll
else:
score += roll
if roll == 1:
break
return score
```
In this solution, we use a while loop to simul... | magicoder | python |
You are tasked with implementing a Python function that processes data for training a machine learning model. The function takes in several parameters and performs various operations based on the input. Your task is to complete the implementation of the function by filling in the missing parts.
The function `process_d... | ```python
from sklearn.preprocessing import StandardScaler
import pickle
def process_data_for_training(premodel_file, scale_strategy, xgb_params, train_TP_file, train_FP_file, out_model):
if premodel_file != 'no' and scale_strategy == 'standard':
premodel, normalizer = load_from_pickle(premodel_file, '../p... | magicoder | python |
You are tasked with implementing a simplified version of a data access layer for a social media application. The provided code snippet outlines two methods of an interface for accessing user-related data. The `count` method is used to retrieve the total count of a specific user's data, while the `findPage` method is us... | ```java
import java.util.List;
public class UserRepositoryImpl implements UserRepository {
private UserDataDAO userDataDAO; // Assume the existence of a UserDataDAO for data access
public UserRepositoryImpl(UserDataDAO userDataDAO) {
this.userDataDAO = userDataDAO;
}
// Implement the count me... | magicoder | java |
You are tasked with implementing a class that represents a simple JSON parser. Your class should be able to parse a JSON string and convert it into a corresponding object structure. For this problem, you need to implement the parsing logic for the JSONConstructor attribute, which is used to annotate a constructor to sp... | ```csharp
using System;
using System.Reflection;
[AttributeUsage(AttributeTargets.Constructor)]
public class JSONConstructor : Attribute
{
// Your implementation of the JSONConstructor attribute
}
public class JSONParser
{
public ConstructorInfo GetJSONConstructor(Type type)
{
ConstructorInfo[] co... | magicoder | csharp |
You are tasked with creating a Python script to automate the generation of data for training a Keras deep learning model. The script should take input parameters and use them to generate the necessary data for training the model.
Your task is to write a Python script that takes a list of input parameters and uses them... | ```python
import argparse
import numpy as np
from keras.preprocessing.image import ImageDataGenerator
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
def generate_image_data(num_samples, image_size, data_dir):
# Generate image data using Keras ImageDataGenerato... | magicoder | python |
You are tasked with creating a Python function that interacts with the Azure API to send requests. Your function should be able to handle different types of requests and return the response from the Azure service. You will need to implement the `azure_request` function, which takes in four parameters: `command` (string... | ```python
import requests
def initialize(file):
"""This functions creates a variety of commands to load.
It returns the cf.
"""
#load the config file
with open(file, 'r') as yaml:
cf=ruamel.yaml.round_trip_load(yaml, preserve_quotes=True)
return cf
def azure_request(command, endpoi... | magicoder | python |
You are tasked with implementing a swipe actions view for a mobile application. The swipe actions view allows users to perform actions by swiping left or right on a cell in a table or collection view. The provided code snippet includes a partial implementation of the `SwipeCellActionView` class and a protocol `SwipeAct... | ```swift
class SwipeCellActionView: UIView {
// ... (existing properties and methods)
func setupSwipeActions(_ actions: [SwipeActionButton]) {
buttons = actions
// Calculate the visible width based on the total width of action buttons
visibleWidth = actions.reduce(0) { $0 + max... | magicoder | swift |
You are tasked with implementing a Python function that performs a database migration. The function should handle both the upgrade and downgrade of a database schema. The upgrade_domain function should take in the following parameters:
- table_name: A string representing the name of the table to be modified.
- old_doma... | ```python
def upgrade_domain(table_name, old_domain, new_domain, old_columns, new_columns):
# Generate SQL commands to upgrade the table from old_domain to new_domain
sql_commands = []
# Drop old columns
for column in old_columns:
sql_commands.append(f"ALTER TABLE {table_name} DROP COLUMN {... | magicoder | python |
You are tasked with creating a custom derive macro for a simple XML serialization library in Rust. The library provides the `XmlRead` and `XmlWrite` traits for deserializing and serializing XML data, and the goal is to implement a custom derive macro for a struct that will automatically generate the necessary XML seria... | ```rust
use xml_serde::{XmlRead, XmlWrite};
#[derive(Debug, Default, XmlRead, XmlWrite)]
#[xml(tag = "w:tcPr")]
struct tcPr {
// Define the fields of the tcPr struct
// ...
}
// Implement the XmlWrite trait for the tcPr struct using a custom derive macro
// The custom derive macro generates the necessary XML ... | magicoder | rust |
You are tasked with creating a script to process a log file and extract specific information from it. The log file contains lines of the format "echo <number> >> <path>", where <number> is a sequence of digits and <path> is a file path. Your script should read the log file and calculate the total sum of all the numbers... | ```python
def calculate_sum_from_log(log_file_path):
sum_of_numbers = 0
with open(log_file_path, 'r') as file:
for line in file:
parts = line.split()
if len(parts) == 4 and parts[0] == 'echo' and parts[2] == '>>':
try:
number = int(parts[1])
... | magicoder | python |
You are tasked with creating a multi-threaded program to process a queue of JSON objects. The program should use Python's `concurrent.futures.ThreadPoolExecutor` to concurrently process the JSON objects in the queue. Each JSON object represents a task that needs to be executed, and the processing involves parsing the J... | ```python
import json
import queue
from concurrent.futures import ThreadPoolExecutor
def process_task(task):
result = {"id": task["id"], "result": task["data"] * 2}
return result
def process_queue(task_queue, num_threads):
results = {}
with ThreadPoolExecutor(max_workers=num_threads) as executor:
... | magicoder | python |
You are tasked with creating a message listener function for a ticketing system. The function should update the `userId` of a ticket and acknowledge the message once the update is complete. You are provided with a code snippet that sets up the necessary components for testing the message listener function.
Your task i... | ```javascript
listener.onMessage = async (data, msg) => {
// Update the userId of the ticket
const updatedTicket = await Ticket.findByIdAndUpdate(data.ticket.id, { userId: data.userId });
// Acknowledge the message
await msg.ack();
};
```
In the solution, the `onMessage` function is implemented to update the `... | magicoder | javascript |
You are tasked with creating a Rust function that simulates a simplified file permission adjustment process. The function `chownr` takes an absolute file path as input and attempts to change the ownership of the file and its contents to the current user. The function uses asynchronous programming and relies on external... | ```rust
use anyhow::{Result, anyhow};
// Simulated function to obtain the current user
async fn check_user() -> Result<String> {
// Simulated implementation to obtain the current user
// Returns the current user or an error if unable to retrieve it
unimplemented!()
}
// Simulated function to execute an as... | magicoder | rust |
You are tasked with creating a Discord bot that periodically updates its status to reflect the number of servers it is active in and the total number of users across all those servers. To achieve this, you need to implement a function that updates the bot's status at regular intervals.
Write a Python function `update_... | The `update_bot_status` function uses an infinite loop to continuously update the bot's status. It first sets the bot's status to online with the activity showing the number of servers it is active in. After 5 seconds, it updates the status to show the total number of users across all the servers. This process repeats ... | magicoder | python |
You are tasked with implementing a function that reshapes a given input array into a specified shape. The function should also handle the case where an output array is provided, ensuring that it has the same shape as the input array. Additionally, the function should raise appropriate exceptions if the provided output ... | ```python
import numpy as np
def reshape_array(input_array, new_shape, out_array=None):
reshaped_input = np.reshape(input_array, new_shape)
if out_array is not None:
if out_array.shape != reshaped_input.shape:
raise ValueError(f"If out array is provided, it should have the same shape a... | magicoder | python |
You are tasked with creating a program to guide a character through an island to collect gems. The island is represented as a grid, and the character can move forward, turn right, collect gems, and use portals to teleport to different locations on the island. The character starts at a specific location and needs to fol... | ```swift
// Define the Portal class
class Portal {
var color: String
init(color: String) {
self.color = color
}
}
// Define the World class
class World {
func place(_ portal: Portal, atStartColumn startColumn: Int, startRow: Int, atEndColumn endColumn: Int, endRow: Int) {
// Implem... | magicoder | swift |
You are tasked with creating a Python program that logs the start and end times of a main function, and also optionally logs a message if the program runs in verbose mode. Your program should also be able to profile the main function using Python's built-in profiling module.
Your program should have the following feat... | ```python
import sys
from time import strftime, localtime
import cProfile
def main():
# Your main function implementation goes here
pass
def log_start_end_time(verbose=False):
timeformat = "%Y-%m-%d %H:%M:%S"
startTime = strftime(timeformat, localtime())
main()
endTime = strftime(timeformat, l... | magicoder | python |
You are tasked with implementing a Python class that handles paginated API responses and enforces a maximum results limit. The class, named `PaginatedAPIHandler`, has the following attributes and methods:
Attributes:
- `MAX_RESULTS_LIMIT`: An integer representing the maximum number of results allowed.
Methods:
- `fet... | ```python
from typing import Optional, List
import requests
from typing_extensions import Literal
class PaginatedAPIHandler:
MAX_RESULTS_LIMIT = 1000
MAX_PER_PAGE = 50
def fetch_results(self, page: int, per_page: int, previous_token: Optional[str]) -> Optional[List[str]]:
if (
previous... | magicoder | python |
You are tasked with implementing a function that processes an array of messages and returns the indices of the newly added messages. The function should handle the case when the input array is empty.
You are given the following code snippet as a starting point:
```swift
/// 数组为空
guard let last = array.last else {
... | ```swift
protocol MessageDelegate {
func messageArray(arry: Any, date: Date) -> [String]
}
extension Array where Element == Int {
func indexPaths() -> [Int] {
return self
}
}
extension MessageDelegate {
func messageArray(arry: Any, date: Date) -> [String] {
// Implementation of message... | magicoder | swift |
You are tasked with creating a program that processes video frames and overlays text onto the frames. The provided code snippet is a part of a larger program that processes video frames and adds the score of an object detection algorithm to the top left corner of each frame. The variable `b` represents an object contai... | ```python
import cv2
def add_score_to_frames(input_video_path: str, output_video_path: str) -> None:
cap = cv2.VideoCapture(input_video_path)
frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = cap.get(cv2.CAP_PROP_FPS)
fourcc = cv2.Vid... | magicoder | python |
You are tasked with implementing a Python class for creating Segregated Witness (SegWit) transactions, a feature introduced in Bitcoin to address scalability and transaction malleability issues. SegWit transactions separate the witness data (signatures) from the transaction data, allowing for more efficient use of bloc... | ```python
import struct
class SWitnessTransaction(STransaction):
def __init__(self, version, flag, ins, outs, witness, locktime):
super().__init__(version, ins, outs, locktime) # Call the constructor of the STransaction class
self.flag = flag
self.witness = witness
```
In the solution, the... | magicoder | python |
You are tasked with implementing a file management system that involves cleaning file names to ensure compatibility with Windows-style paths. Your goal is to create a function that takes a file name as input and returns the cleaned version of the name, ensuring that it is compatible with Windows-style paths.
You are p... | ```python
import os
class FileManager:
def _clean_name(self, name):
"""
Cleans the name so that Windows style paths work
Args:
name: A string representing the file name
Returns:
A string representing the cleaned file name compatible with Windows-style paths
... | magicoder | python |
You are tasked with creating a WebSocket-based multiplayer game server for Connect 4. The provided code snippet is a configuration for the server's routing using Django Channels, a package that extends Django to handle WebSockets, chat protocols, and other asynchronous features.
The `application` variable is a Protoco... | ```python
from channels.generic.websocket import AsyncWebsocketConsumer
import json
class Connect4Consumer(AsyncWebsocketConsumer):
async def connect(self):
# Accept the WebSocket connection
await self.accept()
# Add the connected user to the game room or create a new room
await se... | magicoder | python |
You are tasked with creating a function that takes two non-negative integers as arguments and returns their sum in binary form. The binary sum should be a string.
Create a function `add_binary` that takes two non-negative integers `a` and `b` as input and returns their sum in binary form.
For example:
- `add_binary(1... | ```python
def add_binary(a, b):
return bin(a + b)[2:]
```
The `add_binary` function takes two non-negative integers `a` and `b` as input. It returns the sum of `a` and `b` in binary form by first adding `a` and `b`, then converting the sum to binary using the `bin` function. The binary representation obtained is t... | magicoder | python |
You are given a string `s` consisting of lowercase English letters. Your task is to find the length of the longest substring that contains at most two distinct characters.
Write a function `longestSubstring` that takes in a string `s` and returns the length of the longest substring with at most two distinct characters... | ```python
def longestSubstring(s: str) -> int:
if len(s) < 3:
return len(s)
max_length = 0
left = 0
right = 0
char_map = {}
while right < len(s):
char_map[s[right]] = right
if len(char_map) == 3:
del_idx = min(char_map.values())
left = del_idx + ... | magicoder | python |
You are tasked with creating a web application for managing subscriptions, subscription types, customers, and projects. The given code snippet is a part of the backend logic for retrieving data from the database based on the user's tenant ID. The code uses a PHP framework with a database abstraction layer, and it seems... | ```php
function fetchTableData($tableName, $columns, $tenantId, $order = 'id', $asc = 'asc') {
$columnList = implode(',', $columns);
$query = "select `id`," . $columnList . " from `" . $tableName . "` WHERE `tenant_id` = ? order by `" . $order . "` " . $asc;
$results = DB::select($query, $tenantId);
$d... | magicoder | php |
You are tasked with creating a web scraping program to extract data from a website. Your program should utilize Python's Scrapy framework to parse a webpage and extract specific information. In this scenario, you are required to extract the UUID, timestamp, and URL of the webpage.
Your task is to complete the `parse` ... | ```python
import scrapy
import uuid
import datetime as dt
class MySpider(scrapy.Spider):
name = 'my_spider'
start_urls = ['http://www.example.com']
def parse(self, response):
yield {
"uuid": str(uuid.uuid1()),
"timestamp": dt.datetime.now(),
"url": response.url,... | magicoder | python |
You are tasked with implementing a command-line interface (CLI) function that allows users to choose from a list of examples. The function should display the available examples and prompt the user to select one. If the user chooses an example, the function should return the selected example. If the user chooses to quit... | ```rust
use std::io;
fn let_user_choose_example(examples: Vec<Option<String>>) -> Result<String, Box<dyn std::error::Error>> {
println!("Choose an example:");
for (i, optional_example) in examples.iter().enumerate() {
if let Some(example) = optional_example {
println!("{}) {}", i + 1, exam... | magicoder | rust |
You are tasked with implementing a Python function that retrieves a list of all available drivers and their details from a transportation management system. The function should handle various scenarios, including cases where no drivers are available. Additionally, you need to write unit tests to ensure the correctness ... | ```python
import unittest
class TestUtils(unittest.TestCase):
def test_get_all_drivers_empty(self):
drivers = get_all_drivers()
self.assertEqual([], drivers)
def get_all_drivers():
# Simulate retrieving drivers from a transportation management system
# In a real system, this would involve ... | magicoder | python |
You are tasked with implementing a secure keychain manager for a mobile application. The keychain manager should provide methods for saving and retrieving sensitive data, such as access tokens, securely in the device's keychain. The keychain manager should handle errors gracefully and provide informative messages to th... | ```swift
import Security
class KeychainManager {
enum KeychainError: Error {
case saveError
case retrieveError
}
func saveAccessToken(_ accessToken: String) {
let accessTokenData = accessToken.data(using: .utf8)!
let query: [String: Any] = [
kSecCla... | magicoder | swift |
You are tasked with implementing a function that manipulates socket options in a networking application. The function will take in a raw socket, a protocol constant, an option constant, and a mutable pointer to an option value, and it will return a boolean indicating whether the operation was successful or not.
The fu... | ```rust
use std::os::raw::{c_int, c_void};
use std::net::{RawSocket, SocketOption, SocketType, IpAddr, Ipv6Addr, Ipv6MulticastScope};
use std::mem;
fn manipulate_socket_option(
socket: RawSocket,
protocol: c_int,
option: c_int,
optval: *mut c_void,
optlen: &mut socklen_t
) -> bool {
let res... | magicoder | rust |
You are tasked with creating a program that utilizes the `SyntacticSimplifier` module to simplify a given syntactic expression. The `SyntacticSimplifier` module provides a method `simplify_expression` that takes a syntactic expression as input and returns the simplified form of the expression. The simplified expression... | ```python
from syntactic_simplifier import SyntacticSimplifier
def simplify_syntactic_expression(expression: str) -> str:
simplifier = SyntacticSimplifier()
simplified_expression = simplifier.simplify_expression(expression)
return simplified_expression
``` | magicoder | python |
You are tasked with simulating a drag-and-drop functionality in a web application using JavaScript. Your goal is to implement the `makeDnd` function, which takes the following parameters:
- `mouse`: An object representing the mouse interaction capabilities.
- `sourceIndex`: The index of the source element to be dragged... | ```javascript
async function makeDnd(mouse, sourceIndex, targetIndex, positions) {
const sourcePosition = positions[sourceIndex - 1];
const targetPosition = positions[targetIndex - 1];
// Simulate mouse press at the source element
await mouse.press(sourcePosition.x, sourcePosition.y);
// Simulate dragging t... | magicoder | javascript |
You are tasked with implementing a dynamic programming solution to find the length of the longest common subsequence (LCS) of two given strings.
A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. For example, "ace"... | ```python
def longestCommonSubsequence(s1: str, s2: str) -> int:
m, n = len(s1), len(s2)
# Create a 2D array to store the length of LCS for subproblems
dp = [[0] * (n + 1) for _ in range(m + 1)]
# Fill the dp array using bottom-up dynamic programming approach
for i in range(1, m + 1):
for j... | magicoder | python |
You are tasked with implementing a simple RSA encryption and decryption program. The program should take user input for a message to be encrypted, generate public and private keys, encrypt the message using the public key, and then decrypt the encrypted message using the private key.
Your task is to complete the imple... | ```python
from Crypto.Util.number import getPrime
from Crypto.PublicKey import RSA
def generate_keypair(p, q):
n = p * q
phi = (p-1) * (q-1)
e = 65537 # Common choice for e
d = pow(e, -1, phi)
return ((e, n), (d, n))
def encrypt(message, public_key):
e, n = public_key
encrypted_msg = [pow... | magicoder | python |
You are tasked with creating a plugin for a Minecraft server using the Bukkit API. The plugin needs to handle a custom command that allows players to check their in-game currency balance. The currency system is managed by another part of the server and is accessible through an external API. Your plugin should be able t... | ```java
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class BalanceCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command co... | magicoder | java |
You are working on a data visualization project and need to create a program that generates a plot with two subplots. The first subplot will display a line plot of a time series data set, while the second subplot will display a line plot of the Mean Squared Error (MSE) values. The code snippet provided below is a part ... | ```python
import matplotlib.pyplot as plt
# Function to generate the time series data
def generate_time_series_data(G, k1, k2, k3, num_points):
t_set = [i for i in range(num_points)] # Generate time values
n_set = [G * (k1 * i + k2 * i**2 + k3 * i**3) for i in range(num_points)] # Generate data values
re... | magicoder | python |
You are working on a computer vision project and need to convert Bayer-encoded images to grayscale using OpenCV. The Bayer encoding pattern is a popular method for capturing color information in a single sensor array. OpenCV provides constants for converting Bayer-encoded images to grayscale, but the encoding pattern u... | ```cpp
namespace cvu {
enum class EBayerCode {
BG, // GigE Vision Bayer code
GB, // GigE Vision Bayer code
RG, // GigE Vision Bayer code
GR // GigE Vision Bayer code
};
int bayerCodeGray(EBayerCode code)
{
switch(code)
{
// OpenCV code is shifted one down and one left from
// the one ... | magicoder | cpp |
You are tasked with implementing a featurization and correlation analysis tool for a text dataset. The provided code snippet is a part of a Python script that performs featurization, correlation computation, and filtering of top n-grams based on their correlations.
Your task is to implement the `Featurizer` class and ... | ```python
from collections import defaultdict
import os
import numpy as np
from scipy.stats import pearsonr
from sklearn.feature_extraction.text import CountVectorizer
class Tokenizer:
def __init__(self, filter_punct=True, ws_norm=True, strip=True, replace_digits=True):
self.filter_punct = filter_punct
... | magicoder | python |
You are tasked with implementing a Python function that simulates a simplified version of a gradient descent optimization algorithm. The function takes in several parameters and performs a series of operations on the gradients and parameters to update the model weights. Your task is to complete the implementation of th... | The `optimize_model` function takes in the parameters `params`, `grads`, and `moments` and performs the required operations on the gradients and parameters as specified. The function first applies weight decay to the gradients using the `apply_decay` function, then scales the gradients by the reciprocal scale if it is ... | magicoder | python |
You are tasked with creating a Python class that manages user authentication and authorization for a web application. The class should utilize Flask-Login and itsdangerous libraries to handle user sessions and remember me functionality. Additionally, the class should interact with a user service proxy and an organizati... | ```python
from datetime import timedelta
from flask.ext.login import UserMixin, LoginManager, current_user, login_user
from itsdangerous import URLSafeTimedSerializer
from flod_frontend import app
from proxy import user_service_proxy, organisations_service_proxy
import os
AUTH_ADMIN_USER_ID = 'FlodSuperUser'
class Us... | magicoder | python |
You are tasked with implementing a function that generates HTML code for a customizable component. The function should take in several parameters to customize the appearance and content of the component. The HTML code should be generated based on the provided parameters.
The function signature is as follows:
```javasc... | ```javascript
function generateComponent(prefixCls, align, author, datetime, content, actions) {
const authorSpan = author ? `<span class="${prefixCls}-author">${author}</span>` : '';
const datetimeSpan = datetime ? `<span class="${prefixCls}-datetime">${datetime}</span>` : '';
const contentDiv = content ? `<div ... | magicoder | javascript |
You are tasked with implementing a class to simulate a simple computer mouse. The class should provide methods to retrieve the current vertical scroll position and the status of the mouse buttons. Your task is to create the `Mouse` class with the specified methods and then use it to solve a given scenario.
Create a cl... | ```python
class Mouse:
def __init__(self, scroll_y, down_buttons):
self.scroll_y = scroll_y
self.down_buttons = down_buttons
def GetScrollY(self):
return self.scroll_y
def GetDownButtons(self):
return self.down_buttons
# Scenario
# Instantiate a Mouse object with scroll po... | magicoder | python |
You are tasked with implementing a keyboard shortcut manager for a web application. The manager should allow users to define custom keyboard shortcuts and associate them with specific actions within the application.
Your task is to create a class `ShortcutManager` with the following functionalities:
1. `addShortcut(k... | ```javascript
class ShortcutManager {
constructor() {
this.shortcuts = new Map();
}
addShortcut(keyCombination, action) {
this.shortcuts.set(keyCombination, action);
}
removeShortcut(keyCombination) {
this.shortcuts.delete(keyCombination);
}
handleEvent(event) {
let matchedShortcut = nu... | magicoder | javascript |
You are tasked with implementing a Java method to convert a transit map into a JSON object. The transit map is represented as a graph, where each node represents a location and each edge represents a transit route between two locations. The method should take the transit map as input and produce a JSON object that repr... | ```java
import org.json.JSONArray;
import org.json.JSONObject;
public class TransitMapConverter {
public JSONObject convertTransit(TransitMap transitMap) throws Exception {
JSONObject transitJson = new JSONObject();
JSONArray locationsArray = new JSONArray();
for (Location location : trans... | magicoder | java |
You are given a Python code snippet that manipulates a deque `d` and a variable `max`. A deque is a double-ended queue, which is a data structure that allows insertion and deletion at both ends. The code snippet performs a series of operations on the deque `d` and the variable `max` based on certain conditions. Your ta... | ```python
from collections import deque
def process_deque(d):
if not d:
return []
max_values = []
max_val = d.popleft()
max_values.append(max_val)
while d:
if d[0] <= max_val:
max_val = d.popleft()
max_values.append(max_val)
elif d[-1] <= max_val:
... | magicoder | python |
You are given an array of integers. For each element in the array, you need to find the count of elements to its right that are smaller than the current element. Your task is to implement a function `mapToTotalSmallerElementToTheRight` that takes in an array of integers and returns a new array where each element repres... | ```swift
extension Array where Element: Comparable {
func mapToTotalSmallerElementToTheRight() -> [Int] {
var result = [Int](repeating: 0, count: count)
var sortedArr = [(index: Int, value: Element)]()
for (index, value) in enumerated() {
sortedArr.append((index, value))... | magicoder | swift |
You are tasked with implementing a custom mapper interface for a water station order detail entity in a Java application. The `SsWaterstationOrderDetailMapper` interface extends the `BaseMapper` interface and is responsible for mapping data between the `SsWaterstationOrderDetail` entity and the underlying data storage.... | ```java
public interface SsWaterstationOrderDetailMapper extends BaseMapper<SsWaterstationOrderDetail> {
// Method signature for inserting a new order detail
void insert(SsWaterstationOrderDetail orderDetail);
// Method signature for retrieving an order detail by its ID
SsWaterstationOrderDetail select... | magicoder | java |
You are tasked with developing a mutation-based fuzzer for testing software. The fuzzer has several configurable parameters that determine its behavior. Your goal is to implement a function that takes these parameters into account and generates mutated test cases for the software under test.
You are provided with the ... | ```python
import random
def generate_mutated_test_case(seed, USE_CUSTOM_MUTATOR, USE_CROSSOVER, USE_GAUSSIAN, USE_PROBABILITY_STEPS_SPECIAL,
PROBA_LIMIT_WITHIN_EPSILON, WRITE_AE_ONLY_IF_BETTER_OUTSIDE_BRANCHES, ALWAYS_OPTIMIZE,
MUTATE_DEPTH, DEFAULT_EPSILON... | magicoder | python |
You are tasked with implementing a simple command-line utility that simulates a computer reboot process. The utility should prompt the user for confirmation before proceeding with the reboot. If the user confirms, the utility should display a countdown from 3 to 1, simulating the shutdown process, and then display a me... | ```python
import time
def simulate_reboot():
confirmation = input("Are you sure you want to reboot the system? (yes/no): ")
if confirmation.lower() == "yes":
print("Initiating system shutdown...")
for i in range(3, 0, -1):
print(i)
time.sleep(1)
print("System reb... | magicoder | python |
You are tasked with creating a program that processes a list of exported modules from a TypeScript file and calculates the total number of GitHub stars associated with each module. The TypeScript file contains comments, and the exported modules are listed at the end of the file. Each exported module is preceded by the ... | ```python
import re
def calculate_total_stars(typescript_snippet):
stars_pattern = r'<gh_stars>(\d+)'
module_pattern = r'export \* from .+?;'
total_stars = 0
# Extract total stars for the TypeScript file
total_stars_match = re.search(stars_pattern, typescript_snippet)
if total_stars_match:
... | magicoder | python |
You are tasked with creating a Python function that processes a list of strings representing measurements and calculates the average and standard deviation of these measurements. The measurements are in the format "measurement=value", where "value" is a floating-point number. Your function should return a tuple contain... | ```python
import re
import statistics
def calculate_avg_and_std(measurements):
values = []
for measurement in measurements:
match = re.search(r'measurement=([\d.]+)', measurement)
if match:
value = float(match.group(1))
values.append(value)
avg = sum(values) / l... | magicoder | python |
You are tasked with creating a Python program to validate user input for a registration form. The program should prompt the user to enter their first name, last name, email, and password. The input for each field should be validated according to specific criteria.
The validation criteria are as follows:
1. First name ... | ```python
import re
def validate_name(name):
return name.isalpha() and len(name) > 0
def validate_email(email):
return re.match(r"[^@]+@[^@]+\.[^@]+", email) is not None
def validate_password(password):
return len(password) >= 8 and any(c.isupper() for c in password) and any(c.islower() for c in password... | magicoder | python |
You are working on a project that involves processing astronomical data stored in HDF5 format. The code snippet provided is part of a Python script that appends columns to an HDF5 file. The `append_column_to_hdf5` function takes four arguments: the input HDF5 file (`infile`), the data to be appended, the group within t... | ```python
import h5py
import numpy as np
def calculate_and_append_angular_separation(infile, prediction_icrs_dec_rad, pointing_icrs_ra_rad, pointing_icrs_dec_rad):
with h5py.File(infile, 'a') as f:
events_group = f['events']
# Calculate angular separation using haversine formula
de... | magicoder | python |
You are given a directory containing multiple files with the naming convention `scaffoldXXXX:YYYYYYYY-ZZZZZZZZ__stats.txt`, where `XXXX` represents the scaffold number, `YYYYYYYY` represents the start position, and `ZZZZZZZZ` represents the end position. Each file contains statistical data related to genetic analyses. ... | ```python
import os
# Directory containing the input files
input_directory = '/path/to/input_directory'
# Output file for combined content
output_file = '/path/to/window_heterozygosity.txt'
# Iterate through each file in the directory
with open(output_file, 'w') as combined_file:
for filename in os.listdir(input... | magicoder | python |
You are given an array of integers representing the positions of crabs on a line. Each integer represents the position of a single crab. Additionally, you are given two integers, `minPos` and `maxPos`, representing the minimum and maximum positions on the line, respectively.
Your task is to write a function that calcu... | ```typescript
function calculateFuelCost(crabs: number[], minPos: number, maxPos: number): number {
const crabPositions = new Map<number, number>()
for (const crab of crabs) {
crabPositions.set(crab, (crabPositions.get(crab) ?? 0) + 1)
}
let totalCost = 0
for (let i = minPos; i <= maxPos; i++) {
le... | magicoder | typescript |
You are tasked with implementing a function that calculates the factorial of a given non-negative integer. The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. For example, the factorial of 5 (denoted as 5!) is 5 * 4 * 3 * 2 * 1 = 120.
Write a function `factorial` ... | ```rust
fn factorial(n: u64) -> u64 {
if n == 0 || n == 1 {
return 1;
}
let mut result = 1;
for i in 2..=n {
result *= i;
}
result
}
fn main() {
// Test cases
assert_eq!(factorial(0), 1);
assert_eq!(factorial(1), 1);
assert_eq!(factorial(5), 120);
assert_eq!(... | magicoder | rust |
You are tasked with implementing a naming context server for a distributed system. The naming context server is responsible for maintaining a mapping of names to object references, allowing clients to look up and access remote objects by their names. Your task is to implement the `BBNamingContextServer` class, which sh... | ```cpp
#include <mutex>
#include <unordered_map>
class BBNamingContextServer {
public:
void bind(const std::string& name, const ObjectReference& objectRef) {
std::lock_guard<std::mutex> lock(mutex_);
namingMap_[name] = objectRef;
}
void unbind(const std::string& name) {
std::lock_guard<std::mutex> ... | magicoder | cpp |
You are tasked with implementing a function to generate all possible Pauli stabilizer operators for a given number of qubits. Pauli stabilizer operators are tensor products of Pauli matrices (I, X, Y, Z) acting on individual qubits. The stabilizer operators form a basis for the stabilizer group, which is essential in q... | ```python
def generate_stabilizer_operators(n):
pauli_matrices = ['I', 'X', 'Y', 'Z']
operators = [''.join(p) for p in product(pauli_matrices, repeat=n)]
return operators
```
The `generate_stabilizer_operators` function uses the `product` function from the `itertools` module to generate all combinations of... | magicoder | python |
You are tasked with creating a Python function that processes a Django model definition and extracts information about the fields and their relationships. The model definition is provided as a string in the format of a Django migration file, which includes the fields and their relationships.
Your task is to implement ... | ```python
import re
def extract_model_info(model_definition: str) -> dict:
model_info = {}
# Extract model name
model_name_match = re.search(r"name='(\w+)'", model_definition)
if model_name_match:
model_info['model_name'] = model_name_match.group(1)
# Extract fields and their type... | magicoder | python |
You are tasked with implementing a data processing function that extracts and processes data from a continuous stream. The function should retrieve a specific portion of the data, convert it from hexadecimal to decimal, and then emit the processed data to a socket for real-time updates.
You are given a code snippet th... | ```python
import time
import socketio
# Assume the get_data function retrieves the data from an external source
def get_data():
# Implementation not provided
pass
# Implementation of the reload_px function
def reload_px():
data = get_data()
if data is None:
return
px = str(int(data[74:138]... | magicoder | python |
You are tasked with implementing a custom data structure in Swift that mimics the behavior of a stack, but with an added feature. The stack should support the usual push and pop operations, but it should also provide a method to retrieve the maximum element in the stack at any given time. Your task is to design and imp... | ```swift
struct MaxStack {
private var stack: [(value: Int, max: Int)] = []
mutating func push(_ element: Int) {
let currentMax = stack.last.map { max($0.max, element) } ?? element
stack.append((value: element, max: currentMax))
}
mutating func pop() -> Int? {
return stack.popL... | magicoder | swift |
You are tasked with implementing a custom `Publisher` extension in Swift that provides a method for coalescing the output and failure of a publisher into a single `Result` type. The `Publisher` type is part of the Combine framework, which provides a declarative Swift API for processing values over time.
Your task is t... | ```swift
import Combine
extension Publisher {
/// A single value sink function that coalesces either one `Output` or one `Failure` as a `Result`-type.
func sink(result: @escaping ((Result<Self.Output, Self.Failure>) -> Void)) -> AnyCancellable {
return sink(receiveCompletion: { completion in
... | magicoder | swift |
You are tasked with implementing a thread-safe context manager in Swift using pthread library. The context manager should allow for the creation and management of context objects associated with different threads. The provided code snippet initializes a pthread key for managing the context objects.
Your task is to com... | ```swift
import Foundation
class ContextManager<T> {
private static let key: pthread_key_t = {
var key = pthread_key_t()
pthread_key_create(&key) { obj in
Unmanaged<ContextManager<T>>.fromOpaque(obj!).release()
}
return key
}()
init() {
// Initialize the... | magicoder | swift |
You are tasked with implementing a class that manages asynchronous execution of rules in a rule-based system. The class should handle the execution and validation of rules, as well as the coordination of asynchronous tasks.
Your task is to implement the `RuleManager` class with the following requirements:
- The class ... | ```csharp
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
public class RuleManager
{
private Dictionary<string, Task> ruleTasks = new Dictionary<string, Task>();
public async Task ExecuteRuleAsync(string ruleName, Func<Task> action)
{
if (ruleTasks.ContainsKey(ruleNam... | magicoder | csharp |
You are tasked with implementing a function to generate an image pyramid from a given input image. An image pyramid is a multi-scale representation of an image, typically used in computer vision and image processing applications. The pyramid is constructed by repeatedly downscaling the original image and storing each s... | ```python
def get_pyramid(img, min_height, pyr_factor):
res = [img]
while img.shape[0] > min_height:
img = downscale(img, pyr_factor)
res.append(img)
return res
```
In the solution, the `get_pyramid` function initializes a list `res` with the original input image `img`. It then enters a loo... | magicoder | python |
You are tasked with implementing a command-line tool for version control in a software development environment. The tool should support the following commands: `bump`, `undo`, and `bump.undo`. The `bump` command is used to increment the version number, the `undo` command is used to revert the last version change, and t... | ```python
class VersionControlSystem:
def __init__(self):
self.version = 1
self.history = []
def bump(self):
self.version += 1
self.history.append(('bump', self.version))
def undo(self):
if self.history:
action, version = self.history.pop()
i... | magicoder | python |
You are given a list of animals in alphabetical order. Your task is to implement a function that searches for a specific animal in the list using a binary search algorithm. If the animal is found, the function should return its index in the list; otherwise, it should return -1.
The function signature is:
```python
de... | ```python
def binary_search_animal(animal_list, target_animal):
left = 0
right = len(animal_list) - 1
while left <= right:
mid = (left + right) // 2
if animal_list[mid] == target_animal:
return mid
elif animal_list[mid] < target_animal:
left = mid + 1
... | magicoder | python |
You are tasked with implementing a custom data structure called `UnionDict` that behaves like a dictionary but also supports attribute-style access for nested dictionaries. The `UnionDict` should allow you to access nested dictionaries using dot notation, similar to accessing attributes of an object in object-oriented ... | ```python
class UnionDict(dict):
def __getattr__(self, item):
if item in self:
return self[item]
else:
self[item] = UnionDict()
return self[item]
def __setattr__(self, key, value):
self[key] = value
def __getitem__(self, item):
if item in... | magicoder | python |
You are tasked with implementing a simplified version of a middleware system for handling request context in a web application. The provided code snippet shows a simplified version of a `RequestContextMiddleware` class that is responsible for initializing the request context using a hypothetical `request_context` modul... | ```python
class MiddlewareMixin:
pass # Placeholder for the MiddlewareMixin class, not implemented for this problem
class RequestContextMiddleware(MiddlewareMixin):
def process_request(self, request):
request_context.init_by_request(request)
# Simulated request_context module for testing purposes
cla... | magicoder | python |
You are tasked with implementing a module dependency resolver for a package manager. The package manager uses a custom module system for organizing and managing dependencies of different packages. Each package can have dependencies on other packages, and the resolver needs to determine the correct order in which to ins... | ```rust
fn resolve_dependencies(packages: &[(String, Vec<String>)]) -> Result<Vec<String>, String> {
let mut graph: HashMap<String, Vec<String>> = HashMap::new();
let mut indegree: HashMap<String, usize> = HashMap::new();
// Build the dependency graph and calculate the indegree of each package
for (pac... | magicoder | rust |
You are tasked with creating a web form validation function for a user registration form. The form contains fields for "Nama Lengkap" (Full Name) and "Nama Pengguna" (Username). The form is processed using PHP, and the form data is sent to the server using the POST method. The form fields are required, and the user sho... | ```php
<?php
function validateForm($formData) {
$errors = array();
// Validate Nama Lengkap
if (empty($formData['nama'])) {
$errors['nama'] = 'Nama Lengkap is required';
} elseif (!preg_match('/^[a-zA-Z\s]+$/', $formData['nama'])) {
$errors['nama'] = 'Nama Lengkap should only contain le... | magicoder | php |
You are tasked with implementing a domain parsing function in Rust. The function should take a byte slice as input and parse out the domain name from the beginning of the slice. The domain name is defined as a sequence of characters ending with a period (.) or a space ( ). If the domain name is followed by a space, the... | ```rust
use nom::{bytes::complete::take_while, character::complete::space1, combinator::opt, error::VerboseError, sequence::pair, IResult};
fn parse_domain<'a, E>(input: &'a [u8]) -> IResult<&'a [u8], &'a [u8], E>
where
E: nom::error::ParseError<&'a [u8]>,
{
let (input, domain) = take_while(|c: u8| c != b'.' &... | magicoder | rust |
You are tasked with creating a Rust library for working with mathematical curves and fields. The library should provide a clean and easy-to-use interface for performing operations on various types of curves and fields.
Your task is to implement the necessary modules and structures to support this library. Specifically... | ```rust
// Define the curves module
pub mod curves {
// Define the Curve trait with associated types
pub trait Curve {
type Point;
type Scalar;
// Define methods for performing operations on curves
fn add_points(&self, p1: Self::Point, p2: Self::Point) -> Self::Point;
fn... | magicoder | rust |
You are tasked with implementing a file caching system in Python. The file caching system should provide a way to store Python objects in files and retrieve them later. You are given a partial implementation of the `FileCacher` class, which includes a `__str__` method and an `object_to_file` method.
The `__str__` meth... | ```python
import pickle
import logging
from pathlib import Path
class FileCacher:
def __init__(self, dir_path):
self.dir_path = Path(dir_path)
self.dir_path.mkdir(parents=True, exist_ok=True)
def __str__(self):
string = "FileCacher["
string += str(self.dir_path.resolve())
... | magicoder | python |
You are tasked with creating a program that simulates a simple migration system for a database. The program should be able to execute migration scripts in a specific order and keep track of the executed migrations.
You are given a code snippet from a migration file in a PHP framework. The migration file is used to ins... | ```python
class MigrationManager:
def __init__(self):
self.executed_migrations = []
def execute_migration(self, migration_script):
if migration_script not in self.executed_migrations:
# Execute the migration script here
print(f"Executing migration: {migration_script}")
... | magicoder | python |
You are working on a deployment script for a software project. The script needs to perform a series of operations on the built products directory. However, there is a critical bug in the script that needs to be fixed. The bug is causing the script to unintentionally delete a system file. Your task is to identify the bu... | To fix the bug and prevent unintentional deletion of system files, the code snippet can be modified to use the `${BUILT_PRODUCTS_DIR}` variable as the base directory for the removal operation. Here's the corrected code snippet:
```
cd "${BUILT_PRODUCTS_DIR}"
sudo rm -rf "${BUILT_PRODUCTS_DIR}/System/Library/Extension... | magicoder | python |
You are tasked with implementing a simplified version of the `cd` command found in Unix-like operating systems. The `cd` command is used to change the current working directory. In this problem, you need to write a function that simulates the behavior of the `cd` command by updating the current working directory based ... | ```python
def changeDirectory(currentDir: str, inputDir: str) -> str:
if inputDir.startswith('/'): # Absolute path
return inputDir.rstrip('/') # Remove trailing slash if present
else: # Relative path
components = currentDir.split('/')
components.extend(inputDir.split('/'))
sta... | magicoder | python |
You are given a TypeScript class representing a binary tree node:
```typescript
class Node {
value: string;
depth: number;
width: number;
left: Node | null;
right: Node | null;
constructor(value: string) {
this.value = value;
this.depth = 0;
this.width = 0;
this... | ```typescript
class Node {
value: string;
depth: number;
width: number;
left: Node | null;
right: Node | null;
constructor(value: string) {
this.value = value;
this.depth = 0;
this.width = 0;
this.left = null;
this.right = null;
}
getNodesAtDepth... | magicoder | typescript |
You are tasked with implementing a Python function that calculates the average of a given list of numbers, excluding the maximum and minimum values. The function should take a list of numbers as input and return the average of the remaining values. You should also write a helper function that collects statistics over a... | ```python
import numpy as np
def calculate_average(numbers):
if len(numbers) <= 2:
return 0 # Handle edge case when the list has less than 2 elements
else:
numbers.sort() # Sort the list in ascending order
return sum(numbers[1:-1]) / (len(numbers) - 2) # Calculate the average excludi... | magicoder | python |
You are tasked with creating a Python program that processes audio files from YouTube videos and generates a summary of the video content based on the transcript. The program should utilize various libraries and APIs to achieve this functionality.
Your task is to implement a function `generate_video_summary(video_url)... | ```python
import os
import pafy
from pydub import AudioSegment
from youtube_transcript_api import YouTubeTranscriptApi
from collections import Counter
import re
def generate_video_summary(video_url):
video = pafy.new(video_url)
best_audio = video.getbestaudio()
audio_file = best_audio.download(filepath="te... | magicoder | python |
You are tasked with implementing a chessboard visualization using the provided code snippet as a starting point. The code snippet defines constants for the width and height of the chessboard, the number of rows and columns, and the size of each square on the board.
Your task is to write a Python function that takes in... | ```python
import pygame
# Constants from the provided code snippet
WIDTH, HEIGHT = 800, 700
ROWS, COLS = 7, 8
SQUARE_SIZE = HEIGHT // ROWS
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
# Initialize Pygame
pygame.init()
win = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Chessboard")
# Fu... | magicoder | python |
You are tasked with implementing a simple expression evaluator in Java. Your goal is to create a class `Expr` that can handle basic arithmetic expressions and evaluate them. The `Expr` class should support addition, subtraction, multiplication, and division operations. The expression will be provided as a string in inf... | ```java
import java.util.Stack;
public class Expr {
private String expression;
public Expr(String t) {
expression = t;
}
public int evaluate() {
char[] tokens = expression.toCharArray();
Stack<Integer> values = new Stack<>();
Stack<Character> operators = new Stack<>()... | magicoder | java |
You are tasked with implementing a function to process requests for a ticket management system. The function should handle various parameters and return the appropriate data based on the request. Your task is to write a function that processes the request and returns the required data.
You are given a code snippet tha... | ```python
def process_request():
# Implement the process_request function to handle the request parameters and return the appropriate data
# Extract the request parameters
component = self.req.args.get("component")
status = self.req.args.get("status")
milestone = self.req.args.get("milestone")
q... | magicoder | python |
You are tasked with implementing a class method that retrieves references for a given list of items. The method should take an array of item IDs as input and return an array of references for those items. Each item ID corresponds to a list item, and the references for these items need to be retrieved.
You are given th... | ```php
/**
* Retrieves references for the given list item IDs.
*
* @param string[] $listItemIds An array of item IDs for which references need to be retrieved.
* @return string[] An array of references corresponding to the input item IDs.
*/
public function retrieveReferences(array $listItemIds) {
// Simulatin... | magicoder | php |
You are tasked with implementing a multi-threaded message processing system. The system consists of a message queue and a set of worker threads that retrieve messages from the queue and process them. The message queue is a shared resource that can be accessed by multiple threads concurrently. Your goal is to implement ... | ```java
private void processMessage(Document message) {
sendMessage(message);
}
```
The `processMessage` method simply calls the `sendMessage` function to send the message to its destination. Since the worker threads are responsible for retrieving messages from the queue and processing them, the `processMessage` m... | magicoder | java |
You are tasked with implementing a custom template environment for a text processing system. The given code snippet defines certain configuration parameters and filters for the template environment. The `texenv` object is used to set the variable start and end strings, comment start and end strings, and a filter for es... | ```python
class CustomTemplateEnvironment:
def __init__(self):
self.variable_start_string = '((('
self.variable_end_string = ')))'
self.comment_start_string = '((='
self.comment_end_string = '=))'
self.filters = {}
def set_variable_strings(self, start_string, end_string)... | magicoder | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.