query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with implementing a generic callback mechanism in Java. Your goal is to create a class that allows the registration of callback functions and the subsequent invocation of these callbacks with relevant data. The callback function should accept three parameters: a long representing the start time, a Callba... | ```java
// Sample usage of CallbackData and CallbackManager
public class Main {
public static void main(String[] args) {
CallbackData<String, Integer> data = new CallbackData<>();
data.addData("key1", 100);
data.addData("key2", 200);
CallbackManager<String, Integer> manager = new Ca... | magicoder | java |
You are tasked with implementing a custom loss function for a neural network using TensorFlow. The provided code snippet is a part of a larger neural network class, where `p` is a tensor representing the output of a specific layer, `y` is the ground truth label, and `y_hat` is the predicted output of the network for a ... | ```python
def custom_loss(self, p, y, y_hat):
"""
Calculate the custom loss for each sample in the batch and compute the mean loss.
Args:
p: Tensor representing the output of a specific layer (shape: [batch_size, output_size])
y: Ground truth labels (shape: [batch_size, num_classes])
y_hat: Pre... | magicoder | python |
You are tasked with creating a program that can analyze HTML code and identify the presence of a specific HTML element within it. Your program should be able to parse the HTML code and determine if a given HTML element exists within it.
Write a function called `checkHTMLElement` that takes two parameters:
1. `htmlCode... | ```javascript
function checkHTMLElement(htmlCode, element) {
// Remove all whitespace and newlines from the HTML code
const sanitizedHTML = htmlCode.replace(/\s/g, '');
// Create a regular expression to match the specified HTML element
const elementRegex = new RegExp(`<${element}\\b[^>]*>.*?<\\/${element}>`);
... | magicoder | javascript |
You are tasked with implementing a function that serves dashboard thumbnails based on the provided image name and resolution. The function should handle asynchronous operations and utilize a third-party service for loading the images. You are given a code snippet from a TypeScript/JavaScript application that partially ... | ```typescript
public async serveDashboardThumbnails(
ctx: DefaultContext,
next: Next
): Promise<void {
await next();
const { imgName } = ctx.params;
const { resolution = this.sm.getString() } = ctx.query;
if (this.options.includes(resolution)) {
const imgPath = `${resolution}/${imgName}`;
ctx.set... | magicoder | typescript |
You are tasked with implementing a garbage collection algorithm for a custom programming language. The language has a lexer module for tokenizing input, a stream module for handling input streams, and a utility module for various helper functions. The garbage collection algorithm needs to identify and reclaim memory th... | To implement a garbage collection algorithm for the custom programming language, we can use a mark-and-sweep approach. This involves traversing the memory space, marking reachable objects, and then sweeping through the memory to reclaim memory from unmarked objects.
Here's a high-level overview of the garbage collecti... | magicoder | python |
You are tasked with implementing a card-swiping feature in a mobile application. The card-swiping functionality involves a `CardSwiper` class that manages a collection of cards displayed in a vertical stack. The `insertCards` method is responsible for inserting new cards at specified indexes within the card stack. The ... | ```swift
public class CardSwiper {
private var verticalCardSwiperView: UICollectionView // Assuming verticalCardSwiperView is a UICollectionView
// Other properties and methods of the CardSwiper class
/**
Inserts new cards at the specified indexes.
Call this method to insert one or more new car... | magicoder | swift |
You are given an array of integers `arr` and a target value `target`. Your task is to find two distinct elements in the array whose sum is closest to the target. If there are multiple pairs with the same sum closest to the target, return the pair with the smallest sum.
Write a function `closestSumPair(arr: List[int], ... | ```python
from typing import List, Tuple
def closestSumPair(arr: List[int], target: int) -> Tuple[int, int]:
arr.sort()
left, right = 0, len(arr) - 1
closest_sum = float('inf')
result = (arr[left], arr[right])
while left < right:
current_sum = arr[left] + arr[right]
if abs(current_... | magicoder | python |
You are tasked with implementing a program to process and categorize keyboard shortcuts. Keyboard shortcuts can be of one out of two forms: 1. Characters (e.g., 'a'); 2. Combinations of modifier keys (Ctrl, Alt, Shift) and characters (e.g., Ctrl+C, Alt+Shift+Z). Your program should be able to identify and categorize th... | ```python
from typing import List, Tuple
def categorizeShortcuts(shortcuts: List[str]) -> Tuple[List[str], List[str]]:
single_char_shortcuts = []
combination_shortcuts = []
for shortcut in shortcuts:
if '+' in shortcut:
combination_shortcuts.append(shortcut)
else:
s... | magicoder | python |
You are tasked with creating a Python program that simulates a simple text-based game. The game involves navigating through a maze to find a hidden treasure. The maze is represented as a 2D grid, where each cell can be either empty or blocked. The player can move in four directions: up, down, left, and right. The game ... | ```python
from typing import List, Tuple
class MazeGame:
def __init__(self, maze: List[List[str]], start: Tuple[int, int], treasure: Tuple[int, int]):
self.maze = maze
self.player_position = start
self.treasure_position = treasure
def display_maze(self) -> None:
for i in range(... | magicoder | python |
You are tasked with implementing a class for handling messages in a messaging system. The class, `RBCMessage`, is responsible for encapsulating a payload and providing a method to check the validity of the message. The payload is stored as a private member variable `payload_`. The `RBCMessage` class has the following s... | ```cpp
#include <iostream>
#include <string>
class RBCMessage {
public:
RBCMessage(const std::string& payload) : payload_(payload) {}
std::string get_payload() const {
return payload_;
}
bool is_valid() const {
return isExplicitCPPType(payload_);
}
private:
std::string payload_;
bool isExplic... | magicoder | cpp |
You are tasked with implementing a function that performs a hexadecimal string validation using the SSE (Streaming SIMD Extensions) instruction set. The function should take a hexadecimal string as input and return a boolean value indicating whether the input string is a valid hexadecimal representation.
Your task is ... | ```rust
fn black_box<T>(_: T) -> i32 {
3
}
fn hex_check_sse(input: &[u8]) -> bool {
// Define the mask for valid hexadecimal characters
let hex_mask: i8 = 0x0F;
// Define the mask for valid ASCII characters (0-9, A-F, a-f)
let ascii_mask: i8 = 0x40;
// Define the mask for the case-insensitive... | magicoder | rust |
You are tasked with implementing a class that represents a cloud storage system. The class should have the following functionalities:
1. Initialize the cloud storage system with a given capacity in bytes and track the current usage in bytes.
2. Allow for uploading files to the cloud storage, which increases the curren... | ```python
class CloudStorage:
def __init__(self, capacity_bytes):
self.capacity_bytes = capacity_bytes
self.current_usage_bytes = 0
def upload_file(self, file_size_bytes):
if self.current_usage_bytes + file_size_bytes <= self.capacity_bytes:
self.current_usage_bytes += file_... | magicoder | python |
You are working on a ray tracing algorithm to simulate the interaction of light with 3D objects. The function `first_hit` is used to find the first intersection of a ray with a collection of triangles in the scene. The function takes in the ray, minimum intersection distance `min_t`, a list of triangles, and returns in... | ```cpp
bool first_hit(const Ray& ray, float min_t, const std::vector<Triangle>& triangles, int& hit_id, float& t, Vector3& n) {
bool hit = false;
float closest_t = std::numeric_limits<float>::max();
for (size_t i = 0; i < triangles.size(); ++i) {
const Triangle& tri = triangles[i];
float cu... | magicoder | cpp |
You are tasked with implementing a custom exception class and a method to encode the exception details into a dictionary. The provided code snippet includes a class `BadRequest` which inherits from the built-in `Exception` class. The `BadRequest` class has an `encode` method that returns a dictionary containing the exc... | ```python
class CustomException(Exception):
def __init__(self, message, **kwargs):
self.kwargs = kwargs
self.message = message
def encode(self):
encoded = {"details": self.message}
encoded.update(self.kwargs)
return encoded
class Formatter:
def format_output(self, i... | magicoder | python |
You are tasked with implementing a function that expands a given product object by including additional information for the specified attributes. The product object contains various attributes, and the expansion involves retrieving and adding detailed information for specific attributes from an external data source.
Y... | ```python
import requests
def fetch_detailed_info(attribute):
# Simulated function to fetch detailed information for the given attribute from an external source
# Replace this with actual API calls or data retrieval logic
return f"Detailed information for {attribute}"
def expand_product(product):
for ... | magicoder | python |
You are tasked with creating a program that analyzes a given text file to count the occurrences of specific words. Your program should read the text file, tokenize the words, and then count the occurrences of each word. However, the program should exclude any words that appear in a specified list of common stop words.
... | ```python
def word_count(text_file, stop_words):
word_counts = {}
with open(text_file, 'r') as file:
content = file.read()
words = content.split()
for word in words:
word = word.strip('.,!?"\'').lower()
if word not in stop_words:
if w... | magicoder | python |
You are tasked with implementing a class that manages a collection of unique strings. The class should provide methods to add a string to the collection, remove a string from the collection, and check if a given string is present in the collection. Additionally, the class should support retrieving the total count of st... | ```java
public class UniqueStringCollection {
private Node[] buckets;
private int size;
public UniqueStringCollection() {
this.buckets = new Node[16]; // Initial capacity
this.size = 0;
}
public void addString(String str) {
if (!containsString(str)) {
int index ... | magicoder | java |
You are tasked with creating a program that counts the occurrences of each word in a given text file and then displays the top N most frequently occurring words. For this problem, you should assume that a word is any sequence of characters separated by whitespace. Punctuation should be ignored, and all words should be ... | ```python
import re
from collections import Counter
def count_top_words(file_path, n):
with open(file_path, 'r') as file:
text = file.read().lower() # Read the file and convert all text to lowercase
words = re.findall(r'\b\w+\b', text) # Find all words using regular expression
word_counts... | magicoder | python |
You are tasked with implementing a method to parse and extract information from a given code snippet. The code snippet represents a part of a C# method that is used to configure a client for making requests to an API. Your task is to extract the verb and resource URL from the given code snippet and return them as a key... | ```csharp
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
public class Program
{
public static Dictionary<string, string> ExtractRequestInfo(string codeSnippet)
{
Dictionary<string, string> requestInfo = new Dictionary<string, string>();
// Define the patt... | magicoder | csharp |
You are given a list of tokens, where each token is a string. Your task is to implement a function that processes the tokens based on the following rules:
1. If a token contains a "(" or ")" and has a length greater than 1, split the token into two parts: the left side and the right side of the parenthesis.
2. If the l... | ```python
def process_tokens(tokens):
index = 0
while index < len(tokens):
token = tokens[index]
if ("(" in token or ")" in token) and len(token) > 1:
parenthesis_index = token.find("(")
parenthesis = "("
if parenthesis_index < 0:
parenthesis_i... | magicoder | python |
You are tasked with creating a Python script to decrypt a message encrypted using the Nova Arts Cryptor (NAC) algorithm. The NAC algorithm is a proprietary encryption method used by a fictional company, Nova Arts, and the provided code snippet is a part of the decryption process for NAC v1.0.1.
The NAC encryption algo... | ```python
import subprocess
def decrypt_nac_message(encrypted_message, decryption_key):
# Check compatibility
macos_version = int(subprocess.check_output(["sw_vers", "-productVersion"]).decode().split('.')[1])
if macos_version <= 7:
print("Error! NAC needs at least OS X 10.8 (Mountain Lion)")
... | magicoder | python |
You are tasked with creating a script to automate the reformatting and committing of code files in a given directory. The script should find all files in the specified directory that match the pattern "mg_*", reformat them using the clang-format tool, and then commit the changes to a git repository with a specific comm... | ```bash
#!/bin/bash
# Check if directory path is provided as command-line argument
if [ $# -ne 1 ]; then
echo "Usage: $0 <directory_path>"
exit 1
fi
directory_path=$1
# Find files matching the pattern "mg_*" in the specified directory
matching_files=$(find "$directory_path" -name "mg_*")
# Check if any file... | magicoder | shell |
You are tasked with implementing a parallelized edit distance calculation using the Levenshtein distance algorithm. The Levenshtein distance between two strings is the minimum number of single-character edits (insertions, deletions, or substitutions) required to change one string into the other.
You are given a Python... | ```python
import numpy as np
from tqdm import tqdm
from multiprocessing import Pool
from Levenshtein import distance
def dp_edit_distance(s1, s2):
# Calculate the length of the input strings
len_s1, len_s2 = len(s1), len(s2)
# Define a function to calculate Levenshtein distance for a given substring pair
... | magicoder | python |
You are tasked with implementing a custom base conversion library in Rust. Your library should support converting numbers from decimal to various bases and vice versa. To achieve this, you need to define a `Base` enum representing different bases and implement the necessary conversion functions.
The `Base` enum should... | ```rust
use num_traits::ToPrimitive;
use std::fmt;
#[derive(Debug, PartialEq)]
enum Base {
Base2,
Base8,
Base10,
Base16,
}
trait BaseConvert {
fn to_base(&self, base: &Base) -> String;
fn from_base(value: &str, base: &Base) -> Option<Self> where Self: Sized;
}
impl BaseConvert for u32 {
f... | magicoder | rust |
You are tasked with implementing a generic Swift protocol that defines a comparator function for comparing values of a specific type. The protocol should include a fixed reference value and a function to compare two values against this reference. Your task is to complete the implementation of the protocol by providing ... | ```swift
protocol Comparator {
associatedtype C: Comparable
/// Provides the fixed value to compare against.
var reference: C { get }
/// Provides the comparator function to use to compare the values.
func compare(_ value1: C, _ value2: C) -> Bool
}
extension Comparator {
/// Default ... | magicoder | swift |
You are tasked with implementing a function to analyze and visualize bimodal data distribution. The function should take a set of samples and plot a histogram, scatter plot, and probability density function (PDF) for the given data.
You are provided with a code snippet that partially implements this functionality usin... | ```python
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
def analyze_bimodal_distribution(samps, name):
fig, ax = plt.subplots()
ax.hist(samps, bins=1000, kde=False, alpha=0.5, label='Histogram')
ax.scatter(samps, np.ones(len(samps)), alpha=0.1, marker='x', color='red', label='Sca... | magicoder | python |
You are tasked with implementing a function to solve the N-Queens problem. The N-Queens problem is a classic chess-based problem where the goal is to place N queens on an N×N chessboard in such a way that no two queens threaten each other. In chess, a queen can move horizontally, vertically, and diagonally, so no two q... | ```python
def n_queens(n):
def under_attack(col, queens):
return col in queens or any(abs(col - x) == len(queens) - i for i, x in enumerate(queens))
def solve(n):
solutions = [[]]
for i in range(n):
solutions = [solution + [i] for solution in solutions
... | magicoder | python |
You are tasked with implementing a Python function to load data from either a CSV file or a JSON file into a SQLite database. The function should be able to handle both file types and populate the database with the data from the file. You are provided with a code snippet that demonstrates the use of the `initiate_db`, ... | ```python
import os
from scripts.funcs import load_csv_into_db, load_json_into_db, initiate_db
def load_data_into_db(file_path: str, db_connection, db_cursor):
file_extension = os.path.splitext(file_path)[1]
if file_extension == '.csv':
years = list(range(1992, 2000)) # Example years list
try... | magicoder | python |
You are tasked with implementing a Python class to represent complex numbers and performing various operations on them. A complex number is a number that comprises a real part and an imaginary part, typically expressed in the form `a + bi`, where `a` is the real part, `b` is the imaginary part, and `i` is the imaginary... | ```python
class Complex:
def __init__(self, parts):
self.real = parts[0]
self.imaginary = parts[1]
def __add__(self, other):
return Complex([self.real + other.real, self.imaginary + other.imaginary])
def __sub__(self, other):
return Complex([self.real - other.real, self.ima... | magicoder | python |
You are tasked with creating a Python program that simulates a simple web server using the Flask framework. Your program should include a route that accepts a POST request with a JSON payload and returns a response based on the payload data. The payload will contain a key-value pair where the key is "operation" and the... | ```python
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/calculate', methods=['POST'])
def calculate():
data = request.get_json()
operation = data.get('operation')
num1 = data.get('num1')
num2 = data.get('num2')
if operation not in ["add", "subtract", "multiply", "di... | magicoder | python |
You are tasked with creating a C++ program that simulates a simple banking system. The program should allow users to create accounts, deposit and withdraw funds, and check their balance. Each account should have a unique account number, and the program should support multiple accounts.
Your program should include the ... | ```cpp
#include <iostream>
#include <vector>
#include <string>
class Account {
private:
static int nextAccountNumber;
int accountNumber;
std::string accountHolderName;
double balance;
public:
Account(const std::string& name, double initialDeposit) {
accountNumber = nextAccountNumber++;
... | magicoder | cpp |
You are tasked with writing a function to generate the nth row of Pascal's Triangle. Pascal's Triangle is a triangular array of binomial coefficients, where each number is the sum of the two directly above it in the previous row. The first few rows of Pascal's Triangle look like this:
```
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
... | To generate the nth row of Pascal's Triangle, we can use the property that each element in the row can be calculated using the combination formula: C(n, k) = n! / (k! * (n-k)!), where n is the row number and k is the element index within the row.
We can optimize the algorithm to use only O(k) extra space by using a si... | magicoder | python |
You are tasked with creating a Python class that manages user authentication for various social media services. The class should include a method for authenticating users based on their social media service and username.
Your task is to implement the `authenticate` method within the `UserAuthenticator` class. The meth... | ```python
from yourapp.models import SocialUserData # Import the SocialUserData model from your app
class UserAuthenticator:
def authenticate(self, request, service=None, username=None, **kwargs):
try:
user_data = SocialUserData.objects.get(service=service, username=username)
retur... | magicoder | python |
You are tasked with implementing a custom collection class in C# that represents a collection of `Web` objects. The `Web` class represents a web entity in a SharePoint environment. Your custom collection class should implement the `IWebCollection` interface, which extends `IQueryable<IWeb>` and `IDataModelCollection<IW... | ```csharp
// The solution provides a custom implementation of the IWebCollection interface, representing a collection of Web objects in a SharePoint environment. The CustomWebCollection class implements the necessary methods and properties to support querying and managing a collection of Web objects while adhering to t... | magicoder | csharp |
You are tasked with creating a program that analyzes the frequency of words in a given text. Your program should take a string of text as input and output a dictionary containing the frequency of each word in the text. For the purpose of this problem, a word is defined as a sequence of characters separated by spaces, a... | ```python
def word_frequency(text):
# Remove punctuation and convert text to lowercase
text = text.lower().replace('.', '').replace(',', '').replace('!', '').replace('?', '')
# Split the text into words
words = text.split()
# Create a dictionary to store word frequencies
frequency_dict... | magicoder | python |
You are given an array `parr` of positive integers and a positive integer `M`. Your task is to write a function `porking(i, curval)` that calculates the number of ways to form a product less than or equal to `M` by multiplying a subset of the elements of `parr`. The function should take two parameters: `i` (the current... | ```python
def porking(i, curval):
if i == len(parr):
return 1
if curval > M:
return 0
return porking(i, curval * parr[i]) + porking(i + 1, curval)
# Example usage
parr = [2, 3, 4]
M = 10
result = porking(0, 1)
print(result) # Output: 7
```
The `porking` function uses recursion to calculat... | magicoder | python |
You are tasked with implementing a notification system using the provided code snippet as a starting point. The code snippet includes the registration of notifier options, a function to retrieve the notification transport, and a basic notifier class. Your task is to extend this code to create a notification system that... | ```python
# Import necessary modules
import oslo_messaging
from oslo_config import cfg
# Define notifier options
notifier_opts = [
cfg.StrOpt('default_transport', default='rabbit', help='Default transport for notifications'),
# Add more options as needed
]
# Register notifier options
CONF = cfg.CONF
CONF.regi... | magicoder | python |
You are tasked with implementing a neural network architecture using PyTorch for a specific problem. The architecture consists of three linear layers: `fc21`, `fc22`, and `fc3`. The input dimension for `fc21` and `fc22` is 400, and the output dimension is 20. The input dimension for `fc3` is 20, and the output dimensio... | ```python
import torch
import torch.nn as nn
class CustomNetwork(nn.Module):
def __init__(self):
super(CustomNetwork, self).__init__()
self.fc21 = nn.Linear(400, 20)
self.fc22 = nn.Linear(400, 20)
self.fc3 = nn.Linear(20, 400)
def forward(self, x):
out1 = self.fc21(x)
... | magicoder | python |
You are tasked with implementing a class in PHP to handle the system level data associated with SMPP (Short Message Peer-to-Peer) external interface. The class should be able to make a request to retrieve this data and handle the response accordingly.
Your task is to create a PHP class named `SystemSMPPGetRequest22` w... | ```php
<?php
namespace CWM\BroadWorksConnector\Ocip\Models;
/**
* SystemSMPPGetRequest22
*
* Request the system level data associated with SMPP external interface.
* The response is either a SystemSMPPGetResponse21 or an ErrorResponse.
*/
class SystemSMPPGetRequest22
{
/**
* Send request for system leve... | magicoder | php |
You are tasked with creating a custom hook in React that manages the state of a form. The hook should handle the form's input values, validation, and submission. Your task is to implement the custom form management hook and create a simple form component that utilizes this hook.
Your custom hook, named `useForm`, shou... | ```jsx
import React, { useState } from 'react';
const useForm = (initialValues, validationRules, onSubmit) => {
const [values, setValues] = useState(initialValues);
const [errors, setErrors] = useState({});
const handleChange = (e) => {
const { name, value } = e.target;
setValues((prevValues) => ({
... | magicoder | jsx |
You are tasked with creating a script to automate the submission of a job to a high-performance computing (HPC) cluster using the Slurm workload manager. The script should set up the necessary environment, specify job parameters, and execute a Python script for a deep learning application.
Your task is to write a Bash... | ```bash
#!/bin/bash
#SBATCH --job-name=TransformerLM
#SBATCH --gres=gpu:1
module load cuda/9.2
echo $CUDA_VISIBLE_DEVICES
nvidia-smi
echo $PWD
# run the application
python3 main.py -m transformer -b 128 -d wiki2 -g 0 > slurm-tfLM-wiki2-$SLURM_JOB_ID.out
```
The provided Bash script sets the job name to "TransformerL... | magicoder | shell |
You are tasked with implementing a Python function that simulates a simple text-based game. The game involves navigating through a maze represented by a 2D grid. The player starts at the top-left corner of the grid and must reach the bottom-right corner while avoiding obstacles represented by walls.
You are provided w... | ```python
def navigate_maze(maze):
def is_valid_move(x, y):
return 0 <= x < len(maze) and 0 <= y < len(maze[0]) and maze[x][y] == 0
def dfs(x, y):
if x == len(maze) - 1 and y == len(maze[0]) - 1:
return True
if is_valid_move(x, y):
maze[x][y] = -1 # Mark as visi... | magicoder | python |
You are tasked with implementing a logging service for an API framework. The provided code snippet is a part of a PHP class method that handles exceptions and returns an internal server error response. Your goal is to create a logging service class that can handle and log exceptions, and then modify the given method to... | ```php
class LoggerService {
public function logException($exception) {
// Implement logging of the provided exception
// For example, log to a file, database, or external service
}
}
class ExampleClass {
private $services;
public function __construct($services) {
$this->servic... | magicoder | php |
You are tasked with creating a Python script that processes binary files and generates a summary table for each file. The script should accept multiple binary file inputs and produce a summary table containing relevant information extracted from each file. The summary table should be structured and organized for easy a... | ```python
import argparse
import struct
def process_binary_file(file_path):
# Define the structure of the binary file and extract relevant information
# Example: Assuming the binary file contains integer and float values
with open(file_path, 'rb') as file:
# Read and process the binary file data
... | magicoder | python |
You are tasked with implementing a middleware system for a web application framework. The framework uses a PHP-based middleware system to handle authentication and authorization for different routes. The code snippet provided is a part of the middleware configuration for the application.
The code snippet shows a route... | ```php
// Define the authGuard middleware function
function authGuard($request, $response, $next)
{
// Check if the user is authenticated (e.g., using session or token-based authentication)
if ($userAuthenticated) {
// Check if the user has the necessary permissions to access the route
if ($user... | magicoder | php |
You are tasked with implementing a function to validate the consistency of complementarity coefficients in a graph analysis library. The complementarity coefficients represent the degree of complementarity between different elements of a graph. The coefficients are expected to fall within a specific range, and their co... | ```python
import numpy as np
def validate_complementarity_coefs(C, mode):
if mode == "edges":
return (C >= -1e-6).all() and (C <= 1+1e-6).all()
elif mode == "nodes":
m0 = C[["tclust", "tclosure"]].min(axis=1)
m1 = C[["tclust", "tclosure"]].max(axis=1)
return (C["sim"].between(m0... | magicoder | python |
You are working on a PHP application that interacts with a database to retrieve data related to different plans. The given code snippet is part of a class method that is responsible for constructing a SQL query to fetch data for a specific plan. Your task is to complete the implementation of the `get_for_plan` method b... | ```php
public function get_for_plan($planID, $Paging)
{
if ($Paging && $Paging->enabled()) {
$sql = $Paging->select_sql();
} else {
$sql = 'SELECT * FROM ' . $this->table;
}
$sql .= ' WHERE planID=' . $this->db->pdb($planID);
// Additional handling for pagination
if ($Paging &&... | magicoder | php |
You are given a set of points in a 2D plane and a set of queries, each represented as a triplet of integers `(x, y, r)`. For each query, you need to determine the number of points that lie within or on the boundary of the circle centered at `(x, y)` with radius `r`.
Write a function or method that takes in the points ... | ```cpp
#include <vector>
#include <cmath>
int squared(int x) {
return x * x;
}
std::vector<int> countPoints(std::vector<std::vector<int>>& points, std::vector<std::vector<int>>& queries) {
std::vector<int> result;
for (const auto& q : queries) {
const int rSquared = q[2] * q[2];
int count ... | magicoder | cpp |
You are tasked with implementing a custom progress tracking mechanism for a data processing pipeline. The pipeline is designed to process data using a generator and log the progress to a specified logger. The provided code snippet is a method within a class that aims to achieve this functionality. The `progress` method... | ```python
import logging
from tqdm import tqdm
from io import StringIO
class TqdmToLogger:
def __init__(self, logger, level=logging.DEBUG):
self.logger = logger
self.level = level
self.buffer = StringIO()
def write(self, message):
self.buffer.write(message)
if '\n' in m... | magicoder | python |
You are given a sorted array `seg_point` containing distinct integers, and a value `val_size`. Your task is to write a function to find the smallest subarray of `seg_point` such that the difference between the maximum and minimum elements in the subarray is less than or equal to `val_size`. If no such subarray exists, ... | ```python
from typing import List
def find_smallest_subarray(seg_point: List[int], val_size: int) -> List[int]:
min_len = float('inf')
result = []
left = 0
right = 0
while right < len(seg_point):
if seg_point[right] - seg_point[left] <= val_size:
if right - left + 1 < min_len:
... | magicoder | python |
You are tasked with creating a Node.js script that dynamically loads and initializes modules based on a given list of module names. Each module should be imported and initialized using a specific function or method provided by the module itself. Your goal is to create a function that takes an array of module names as i... | ```javascript
const initializeModules = async (moduleNames) => {
const initializedModules = {};
for (const moduleName of moduleNames) {
let initializedModule;
switch (moduleName) {
case 'keccak':
const Keccak = await import('keccak');
initializedModule = Keccak.create();
brea... | magicoder | javascript |
You are tasked with creating a script to automate the process of fetching data from various sources and performing cleanup operations. Your goal is to write a Node.js script that accomplishes the following tasks:
1. Fetch sponsors and backers from the Open Collective platform by executing the `fetch_supporters.js` scr... | ```javascript
const util = require('util');
const exec = util.promisify(require('child_process').exec);
async function fetchAndCleanupData() {
try {
// Fetch sponsors and backers from Open Collective
await exec('node ./src/scripts/fetch_supporters.js');
console.log('Sponsors and backers fetched successfu... | magicoder | javascript |
You are given a Python code snippet that initializes a complex number `c` and an integer `n`. Your task is to implement a function that generates the Mandelbrot set based on these inputs.
The Mandelbrot set is a set of complex numbers for which the function f(z) = z^2 + c does not diverge when iterated from z = 0. The... | ```python
def mandelbrot_set(c, n):
# Initialize a 2D array to store the iteration counts
mandelbrot = [[0 for _ in range(800)] for _ in range(800)]
for x in range(800):
for y in range(800):
# Map pixel coordinates to the complex plane
zx = 3.5 * (x - 400) / 400
... | magicoder | python |
You are working on a deep learning project that involves building a model for image classification. The given code snippet is a part of the model construction process using the Keras library in Python. The model is designed to take input from a base model and produce a final classification output. The code snippet incl... | ```python
import keras
from keras.models import Model
from keras.layers import Dropout, Dense, Concatenate
from keras.initializers import RandomNormal
def construct_classification_model(base_model, feature_tensors):
# Apply dropout and create dense layers for each feature tensor
dropout_tensors = [Dropout(0.5)... | magicoder | python |
You are tasked with implementing a trie data structure to efficiently store and retrieve a collection of words. A trie, also known as a prefix tree, is a tree-like data structure used to store a dynamic set of strings. Each node in the trie represents a single character of the string, with the root node representing an... | ```python
class TrieNode:
def __init__(self):
self.children = {}
self.is_end_of_word = False
def makeTrie(words):
root = TrieNode()
for word in words:
current = root
for char in word:
if char not in current.children:
current.children[char] = TrieN... | magicoder | python |
You are tasked with implementing a graph data structure in C#. The graph should support both directed and undirected edges and should be able to store any type of data as vertices. Additionally, you need to implement a method to perform a depth-first search (DFS) traversal on the graph.
Your graph should be implemente... | ```csharp
using System;
using System.Collections.Generic;
namespace GraphEngine
{
public class Graph<T>
{
private Dictionary<T, List<T>> adjacencyList;
public Graph()
{
adjacencyList = new Dictionary<T, List<T>>();
}
public void AddVertex(T vertex)
... | magicoder | csharp |
You are tasked with implementing a multi-worker file processing system. The system consists of a main worker and multiple child workers, each responsible for processing a specific file. The main worker is responsible for coordinating the processing and saving the data to a file. The code snippet provided is a partial i... | ```python
from typing import List, Union
class MultiWorkerFileProcessor:
_Done_Flag = 0
_Run_Children_History_Flag = {"history": False}
def _is_children_worker(self) -> bool:
# Check if the current process is a child worker
# Implementation not provided
def _is_main_worker(self) -> bo... | magicoder | python |
You are tasked with implementing a Python function that generates an MD5 hash for a given input string and measures the time taken to compute the hash. Your function should also compare the time taken for different input sizes and analyze the performance.
Write a Python function `md5_performance_analysis` that takes a... | ```python
import hashlib
import time
from typing import List, Dict, Union, Tuple
def md5_performance_analysis(input_strings: List[str]) -> Tuple[Dict[str, Union[str, float]], float]:
results = {}
total_time = 0
for string in input_strings:
start_time = time.time()
md5 = hashlib.md5()
... | magicoder | python |
You are tasked with designing a class for managing wireless profiles of network cameras. The class should be capable of creating and updating wireless profiles for network cameras. You need to implement the `NetworkCameraWirelessProfileCreateUpdateRequest` class with the necessary properties and methods to achieve this... | ```csharp
using System.Runtime.Serialization;
[DataContract]
public class NetworkCameraWirelessProfileCreateUpdateRequest
{
[DataMember]
public string SSID { get; set; } // Property to store the SSID of the wireless network
[DataMember]
public string SecurityKey { get; set; } // Property to store th... | magicoder | csharp |
You are given a weighted undirected graph represented as an adjacency matrix and a Python function for implementing the Kruskal's algorithm to find the minimum spanning tree (MST) of the graph. The given code snippet contains a function `Kruskal(heap, source)` which is intended to implement the Kruskal's algorithm usin... | ```python
import heapq as hq
def find(parent, i):
if parent[i] == i:
return i
return find(parent, parent[i])
def union(parent, rank, x, y):
x_root = find(parent, x)
y_root = find(parent, y)
if rank[x_root] < rank[y_root]:
parent[x_root] = y_root
elif rank[x_root] > rank[y_root... | magicoder | python |
You are tasked with implementing a TypeScript decorator for a service that handles GraphQL requests. The decorator should validate and serialize the incoming GraphQL request before passing it to the service method.
Your task is to complete the implementation of the `validateAndSerializeGraphQLRequest` decorator functi... | ```typescript
function validateAndSerializeGraphQLRequest(
target: any,
propertyKey: string,
descriptor: PropertyDescriptor
) {
const originalMethod = descriptor.value;
descriptor.value = function (request: SerializedGraphQLRequest) {
if (!request.query || typeof request.query !== 'string') {
throw... | magicoder | typescript |
You are tasked with creating a Python program to implement a simple substitution cipher. A substitution cipher is a method of encrypting by which each letter in the plaintext is replaced by a letter at a fixed distance down the alphabet. For this problem, you will create a program that takes a word as input and outputs... | ```python
import pandas as pd
# Define the alphabet DataFrame with letters and their corresponding codes
alphabet_data = {'letter': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'],
'code': ['D', 'E', 'F', 'G', 'H', 'I',... | magicoder | python |
You are tasked with implementing a simplified version of a file upload system in a programming language of your choice. The system should consist of a `FileReference` class with methods for uploading a file and handling the cancel event of a file dialog.
The `FileReference` class should have the following methods:
1. ... | ```python
class FileReference:
def upload(self, file, destination_url, data=None):
# Simulate file upload process
print(f"Uploading {file} to {destination_url} with data: {data}")
def openFileDialog_onCancel(self):
# Simulate dispatching cancel event
print("Cancel event dispatch... | magicoder | python |
You are tasked with implementing a function to download a file in parts using asynchronous programming. The function should download the file in multiple parts concurrently and then combine the parts to reconstruct the original file.
You are given a code snippet that initiates an asynchronous download process. The fun... | ```python
import asyncio
import time
async def download_part(client, part_number):
# Simulate downloading part_number of the file
await asyncio.sleep(1) # Simulated download time
async def test_download_by_parts(client):
test_results = {}
t_count = 12
for pcount in range(3, 20):
start_tim... | magicoder | python |
You are tasked with creating a function that validates a comma-separated list of email addresses. The function should ensure that each email address in the list is valid according to a specific validation rule.
You are provided with a code snippet that contains a function `validate_comma_separated_emails(value)` which... | ```python
import re
def validate_email_with_name(email):
"""
Validate the format of an email address.
"""
email_regex = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
if not re.match(email_regex, email):
raise ValidationError('Invalid email format: %s' % email, code='invalid')
```
In ... | magicoder | python |
You are tasked with implementing a phone controller system for a smart home automation application. The system consists of various devices grouped under different families, and each device has a unique name. The code snippet provided is a part of the system's search functionality, which attempts to find the group conta... | To solve this problem, you can create a class structure to represent the smart home automation system and implement the `lookup.getGroupFromNames` function. Here's a possible solution using C++:
```cpp
#include <iostream>
#include <vector>
#include <memory>
class Device {
public:
std::string name;
std::string... | magicoder | cpp |
You are given a snippet of SVG (Scalable Vector Graphics) code representing a path within an SVG image. Your task is to write a program that parses this SVG path data and calculates the total length of the path.
The SVG path data is represented by the "d" attribute within the <path> tag. The path data consists of a se... | ```python
import re
import math
def parse_svg_path(svg_path):
commands = re.findall(r'[A-Za-z]', svg_path)
numbers = list(map(float, re.findall(r'[-+]?\d*\.\d+|[-+]?\d+', svg_path)))
command_index = 0
total_length = 0
prev_x, prev_y = 0, 0
for i in range(len(commands)):
comman... | magicoder | python |
You are tasked with creating a Python class that simulates a simple banking system. The class should have methods for depositing funds, withdrawing funds, and checking the account balance. Additionally, the class should keep track of the account holder's name and account balance.
Create a Python class `BankAccount` wi... | ```python
class BankAccount:
def __init__(self, account_holder):
self._account_holder = account_holder
self._account_balance = 0
def deposit(self, amount):
self._account_balance += amount
def withdraw(self, amount):
if self._account_balance >= amount:
self._acco... | magicoder | python |
You are tasked with creating a Python program to analyze the frequency of occurrence of Bangla alphabets in a given text and then visualize the frequency distribution using a bar chart. To accomplish this, you need to perform the following steps:
1. Read a Bangla text file named "bangla_text.txt" containing the text i... | ```python
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
import re
# Step 1: Read the Bangla text file
with open('bangla_text.txt', 'r', encoding='utf-8') as file:
bangla_text = file.read()
# Step 2: Count the occurrences of each Bangla alphabet
bangla_alphabets = [chr(alpha) for alpha in ra... | magicoder | python |
You are working on a user interface layout for a mobile application. The layout consists of a grid of cells, where each cell can have different dimensions based on its position in the grid. You are given a code snippet that calculates the height and width of each cell based on certain conditions.
The code snippet prov... | ```python
def calculateCellDimensions(itemInSection, normalColumnHeight, featuredColumnWidth, featuredColumnHeight):
cellWidth = normalColumnHeight
cellHeight = normalColumnHeight
if (itemInSection + 1) % 7 == 0 and itemInSection != 0:
cellWidth = featuredColumnWidth
cellHeight = featur... | magicoder | python |
You are tasked with implementing a function to remove a specific folder from a given directory path. The function should work on a POSIX-compliant system and should not rely on any non-standard libraries or features from C++11/14.
Your task is to create a C++ function `removeFolder` that takes two parameters:
1. `cons... | ```cpp
#include <iostream>
#include <string>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
void removeFolder(const std::string& directoryPath, const std::string& folderName) {
std::string fullPath = directoryPath + "/" + folderName;
DIR* dir = opendir(fullPath.c_str());
if (dir) {
c... | magicoder | cpp |
You are tasked with implementing a Python class that calculates the atmospheric inner product for a given set of atmospheric data. The atmospheric inner product is a mathematical operation used in atmospheric science to quantify the similarity between two atmospheric fields. The inner product is defined as the integral... | ```python
class AtmosphericInnerProductCalculator:
def compute_inner_product(self, field1, field2, domain):
x_min, x_max, y_min, y_max = domain
inner_product = 0
for i in range(len(field1)):
for j in range(len(field1[0])):
if x_min <= i < x_max and y_min <= j < y_... | magicoder | python |
You are tasked with implementing a thread-safe data structure called `ThreadSafeBox` in Swift. The `ThreadSafeBox` is a generic class that wraps a value and provides thread-safe operations on that value. The provided code snippet shows an extension of the `ThreadSafeBox` specifically for `Int` values, with methods to i... | ```swift
import Foundation
class ThreadSafeBox<Value> {
private var lock = NSLock()
private var underlying: Value
private let defaultValue: Value
init(value: Value, defaultValue: Value) {
self.underlying = value
self.defaultValue = defaultValue
}
func withLock<T>(_ body: () th... | magicoder | swift |
You are tasked with creating a Python program to compare ground truth and prediction XML files and calculate the overlap between them. The program should also handle the creation of an output directory and the option to save the results in a CSV file.
You are given the following code snippet as a starting point:
```p... | ```python
import os
import xml.etree.ElementTree as ET
import csv
def calculate_overlap(xml_ground_truth, xml_prediction):
# Your overlap calculation logic here
pass
def main():
xml_ground_truth_folder = 'ahte_test_ground_xml/'
xml_prediction_folder = 'evaluation_xml/ahte_jults_identity_neighbour_rota... | magicoder | python |
You are tasked with creating a program that analyzes a given software license text to extract and display the permissions and conditions specified in the license. The license text is provided as a string, and the program should identify and categorize the permissions and conditions based on the keywords present in the ... | ```python
def analyze_license(license_text):
permissions = []
conditions = []
keywords = [
"software", "documentation", "restriction", "rights", "use", "copy", "modify",
"merge", "publish", "distribute", "sublicense", "sell", "permit", "persons", "furnished", "conditions"
]
for wor... | magicoder | python |
You are tasked with implementing a function that generates a list of indices for a given value in a list, excluding specific indices that are provided as exclusion criteria. Your task is to write a Python function `generate_indices` that takes in a list of values and a value to search for, along with a tuple of indices... | ```python
from typing import List, Tuple
def generate_indices(arr: List[int], value: int, exclude: Tuple[int, ...]) -> List[int]:
result = []
for i in range(len(arr)):
if arr[i] == value and i not in exclude:
result.append(i)
return result
```
The `generate_indices` function iterates t... | magicoder | python |
You are tasked with implementing a function to perform element-wise multiplication on two sets of multi-dimensional arrays. The input arrays are represented in a specific format, and the output array should also adhere to this format. Your task is to write a function that can efficiently perform this element-wise multi... | ```cpp
#include <iostream>
#include <vector>
// Function to perform element-wise multiplication on two input arrays
std::vector<std::vector<std::vector<std::vector<float>>>>
elementwise_multiplication(
const std::vector<std::vector<std::vector<std::vector<float>>>>& input1,
const std::vector<std::vector<std::v... | magicoder | cpp |
You are tasked with creating a function that retrieves a list of employee types from a database and returns it in a specific format. The function should be implemented within the `EmpleadosController` class in a Laravel application. The `ListTipoUsuario` function should interact with the database models `TipoUsuario` a... | ```php
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;
use Illuminate\Http\Response;
use App\Models\TipoUsuario;
use App\Models\Empleados;
use App\Models\User;
use Image;
class EmpleadosController extends Controller
{
public function ListTipoUsuario(){
try {
// Fetc... | magicoder | php |
You are tasked with creating a Python function that interacts with a blockchain node to retrieve information about wallet balances at a specific block height. The function will take in a CirrusMinerNode object and return a list of wallet addresses that have a balance over a certain amount at the given block height.
Th... | ```python
from typing import List
from cirrus_miner_node import CirrusMinerNode # Assuming the CirrusMinerNode class is imported from a module
from money import Money # Assuming the Money class is imported from a module
from address import Address # Assuming the Address class is imported from a module
def get_walle... | magicoder | python |
You are tasked with creating a simple command-line tool for a role-playing game (RPG) using Python. The game has a command-line interface where players can input commands to interact with the game world. Your task is to implement a basic command-line interface for the RPG game.
Your command-line tool should support th... | ```python
class RPGGame:
def __init__(self):
self.player_location = "Town Square"
self.player_inventory = ["Sword", "Potion", "Gold"]
def display_help(self):
print("Available commands:")
print("help - Display available commands")
print("look - View current surroundings")... | magicoder | python |
You are tasked with implementing a function that processes a list of assignments and a new node. The function should insert the new node into the list of assignments at the correct position based on the node's priority value. The list of assignments is initially sorted based on priority in ascending order. The new node... | ```python
from typing import List, Tuple
def insert_node(assignments: List[Tuple[str, int]], new_node: Tuple[str, int]) -> List[Tuple[str, int]]:
index = 0
for i, (_, priority) in enumerate(assignments):
if new_node[1] < priority:
index = i
break
else:
index = len(as... | magicoder | python |
You are tasked with creating a script to automate the build process for a software project. The build process involves creating a directory, setting compilation flags, configuring the build system, and building specific targets.
Your script should perform the following steps:
1. Create a directory named "build".
2. Se... | ```bash
#!/bin/bash
# Step 1: Create a directory named "build"
mkdir build
# Step 2: Set the CFLAGS environment variable to "-Wno-missing-braces"
export CFLAGS=-Wno-missing-braces
# Step 3: Use Meson to configure the project in the "build" directory
meson build
# Step 4: Build the project using Ninja, targeting spe... | magicoder | shell |
You are tasked with creating a program to analyze code repositories for duplicate constant strings. Constant strings are defined as string literals that are repeated within the codebase. Your program should take a directory path as input and use the `goconst` tool to identify and return the duplicate constant strings f... | ```python
import subprocess
def get_duplicate_const_strings(directory_path):
try:
# Load the const string duplication info using goconst tool
cyclostats = subprocess.check_output(['./goconst', directory_path]).decode("utf-8")
# Parse the output to extract duplicate constant strings... | magicoder | python |
You are tasked with implementing a custom string comparison method that evaluates sentences containing conditional checks. The method should take a sentence and a check object as input and return a boolean value based on the comparison rules specified in the sentence.
The check object has two properties: `name` (a str... | ```java
public class CustomStringComparison {
public static boolean evaluateSentence(String sentence, Check check) {
if (sentence.startsWith("if check equals '") && sentence.endsWith(check.getName() + "'")) {
return true;
}
if (sentence.startsWith("if check does not equal '") && ... | magicoder | java |
You are tasked with creating a Python class for modeling cellular metabolism. The class should include a method that optimizes the growth rate of the cell while maintaining a specific ATP maintenance level. The code snippet provided is a part of the method that sets the bounds for ATP production and records the growth ... | ```python
from pandas import DataFrame
class CellMetabolismModel:
def __init__(self, model):
self.model = model
def optimize_growth_with_atp_maintenance(self, atp_m, atp_bd):
# Assuming the method to optimize growth rate while maintaining ATP level is implemented elsewhere
# This metho... | magicoder | python |
You are tasked with implementing a custom provider for a web framework. The provider needs to perform setup and configuration for the web framework's droplet. Additionally, the provider should offer an optional `ServerDriver` type to the droplet, with a default implementation of `nil`.
Your task is to create a Swift c... | ```swift
import Vapor
// Define the custom provider class conforming to the Provider protocol
class CustomProvider: Provider {
// Implement the boot method to perform setup and configuration for the droplet
func boot(with droplet: Droplet) {
// Perform setup and configuration specific to the custo... | magicoder | swift |
You are tasked with implementing a Python function that processes a dataset of experimental records and calculates the average time taken for each experiment. The dataset is represented using the `Dataset` class, and each experimental record is represented using the `DatasetRecord` class. The `Dataset` class has a meth... | ```python
class Dataset:
def __init__(self, records):
self.records = records
def calculate_average_time(self):
experiment_times = {}
experiment_counts = {}
for record in self.records:
if record.experiment_name in experiment_times:
experiment_... | magicoder | python |
You are tasked with implementing a function that checks if a given node is in line with a specified configuration. The function should return True if the node is in line with the configuration, and False otherwise. If the node is None, the function should return False.
The function signature is as follows:
```python
d... | ```python
def is_inline(node, config):
if node is None:
return False
x, y = node
x1, y1 = config[0]
x2, y2 = config[1]
return (y - y1) * (x2 - x1) == (y2 - y1) * (x - x1)
```
The solution defines the `is_inline` function that first checks if the node is None and returns False in that case. T... | magicoder | python |
You are tasked with creating a Rust macro that will automatically generate a mapping between two sets of identifiers. The macro should take in two sets of identifiers and generate a mapping between them, allowing for easy translation between the two sets.
Your task is to implement the `generate_mapping` macro, which t... | ```rust
macro_rules! generate_mapping {
(set1: { $($id1:ident),* }, set2: { $($id2:ident),* }) => {
{
fn create_mapping() -> std::collections::HashMap<&'static str, &'static str> {
let mut mapping = std::collections::HashMap::new();
$(
mapping.... | magicoder | rust |
You are tasked with creating a class hierarchy to model different types of ingredients used in a recipe. Each ingredient has a name and a price. Your task is to create a base class `Ingredient` with two properties: `IngredientType` of type string and `Price` of type decimal. Then, derive two classes `SolidIngredient` a... | ```csharp
using System;
public class Ingredient
{
public string IngredientType { get; set; }
public decimal Price { get; set; }
}
public class SolidIngredient : Ingredient
{
public double Weight { get; set; }
}
public class LiquidIngredient : Ingredient
{
public double Volume { get; set; }
}
public ... | magicoder | csharp |
You are tasked with creating a plugin management system for a presentation software. The system should allow users to install, uninstall, and manage various plugins that enhance the functionality of the presentation software. Each plugin can have different features and capabilities, and the system should be able to han... | ```python
class Plugin:
def __init__(self, name, dependencies=None):
self.name = name
self.dependencies = dependencies if dependencies else []
class PluginManager:
def __init__(self):
self.installed_plugins = {}
def install_plugin(self, plugin):
if self._check_dependencies(... | magicoder | python |
You are tasked with creating a utility class for validating different types of input strings. The class should contain methods for validating passwords, URLs, and email addresses. The validation methods should use regular expressions to determine the validity of the input strings.
You need to implement the following m... | ```java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ValidationUtils {
public static boolean isValidPassword(String pass) {
// Password should contain at least 8 characters and include a combination of letters, numbers, and special characters
Pattern pattern = Patte... | magicoder | java |
You are tasked with implementing a function to test the functionality of an AWS cache system. The function `_test_aws_cache` takes in four parameters: `src_data`, `content_type`, `checkout_bucket`, and `replica`. It interacts with AWS S3 to upload data and perform cache-related operations.
Your task is to complete the... | ```python
import tempfile
from enum import Enum
class Replica(Enum):
aws = 1
# Add other replicas as needed
class Config:
@staticmethod
def get_blobstore_handle(replica):
# Implement logic to obtain the blobstore handle for the specified replica
pass
class infra:
@staticmethod
... | magicoder | python |
You are tasked with implementing a function that processes a list of files and filters out specific file types based on their content type. The content type of each file is represented as a string, and the function should remove any files with content type "image/svg+xml" from the list. Additionally, the function shoul... | ```python
from typing import List
def filterFiles(fileTypes: List[str]) -> List[str]:
return [ftype for ftype in fileTypes if ftype and ftype != "image/svg+xml"]
```
The `filterFiles` function uses a list comprehension to iterate through the input `fileTypes` list and filters out any empty strings or the "image/sv... | magicoder | python |
You are tasked with creating a Python function that processes a list of integers and returns the maximum sum of a contiguous subarray within the list. The function should be named `max_subarray_sum` and should take a single parameter, `arr`, which is a list of integers.
For example, given the input `arr = [-2, 1, -3, ... | ```python
def max_subarray_sum(arr):
max_sum = arr[0]
current_sum = arr[0]
for num in arr[1:]:
current_sum = max(num, current_sum + num)
max_sum = max(max_sum, current_sum)
return max_sum
```
The `max_subarray_sum` function initializes `max_sum` and `current_sum` with the first elemen... | magicoder | python |
You are given a C++ code snippet that ends with a comment indicating the closing of a namespace. Your task is to write a program that can identify the namespace being closed by the given comment.
Write a function `findClosingNamespace` that takes a string `code` as input and returns the name of the namespace being clo... | ```cpp
#include <iostream>
#include <string>
std::string findClosingNamespace(const std::string& code) {
size_t pos = code.find("namespace");
if (pos != std::string::npos) {
size_t start = code.find_first_of(" ", pos + 9); // Find the start of the namespace name
size_t end = code.find("\n", st... | magicoder | cpp |
You are given a list of integers. Your task is to implement the function `try_if(lst)` that takes a list `lst` as input and returns a new list containing the result of applying the following logic to each element of the input list:
- If the element is even, add 10 to it.
- If the element is odd, subtract 5 from it.
Fo... | ```python
def try_if(lst):
result = []
for num in lst:
if num % 2 == 0:
result.append(num + 10)
else:
result.append(num - 5)
return result
# Test the function
input_list = [0, 1, 0, 1, 2, 3]
output_list = try_if(input_list)
print(output_list) # Output: [10, -4, 10, ... | magicoder | python |
You are tasked with implementing a function to decode a sequence of likelihood probabilities into a string of characters using the Connectionist Temporal Classification (CTC) decoding method. The CTC decoding method is commonly used in speech recognition and handwriting recognition tasks.
You are given the following f... | ```python
def ctc_decode(probs_seq, vocabulary, method):
if not probs_seq or not vocabulary:
return ""
if method == 'best_path':
return best_path_decode(probs_seq, vocabulary)
elif method == 'beam_search':
return beam_search_decode(probs_seq, vocabulary)
else:
raise Valu... | magicoder | python |
You are tasked with implementing a notification system for a company's external representatives. The code snippet provided is a simplified representation of a notification class in a C# application. Your task is to extend this notification system by creating a new type of notification and implementing the necessary log... | ```csharp
namespace Fusion.Resources.Domain.Notifications
{
public class ExternalCompanyRepActivated : INotification
{
public ExternalCompanyRepActivated(Guid representativeId)
{
RepresentativeId = representativeId;
}
public Guid RepresentativeId { get; }
}
}
```... | magicoder | csharp |
You are tasked with implementing a custom data stream class in C++ that supports reading and writing various data types. The class should handle errors and provide a fluent interface for chaining operations.
Your task is to complete the implementation of the `DataStreamI` class, which represents an input data stream. ... | ```cpp
DataStreamI& DataStreamI::operator>>(int& outVal) {
outVal = 0;
if (!mStream->read(reinterpret_cast<char*>(&outVal), sizeof(int))) {
outVal = 0;
mError = eErrors::readError;
}
return *this;
}
DataStreamI& DataStreamI::operator>>(double& outVal) {
outVal = 0.0;
if (!mStrea... | magicoder | cpp |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.