query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are given a 2D matrix representing a grid of cells. Each cell in the grid contains a non-negative integer value. Your task is to write a function to find the maximum sum of a path from the top-left cell to the bottom-right cell, moving only right or down at each step. The value of each cell represents the score gai... | ```python
from typing import List
def maxPathSum(grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
# Initialize the first row and first column with cumulative sums
for i in range(1, m):
grid[i][0] += grid[i-1][0]
for j in range(1, n):
grid[0][j] += grid[0][j-1]
... | magicoder | python |
You are given a class `Node` representing a node in an undirected graph. Each node in the graph contains a value (int) and a list (List[Node]) of its neighbors. You need to implement a function `cloneGraph` to clone the graph. The function should return the reference to the cloned graph.
The class `Node` is defined as... | ```python
class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
if not node:
return None
visited = {}
def dfs(original):
if original in visited:
return visited[original]
clone = Node(original.val, [])
... | magicoder | python |
You are tasked with implementing a data generator class that can utilize either multiprocessing or multithreading based on a specified configuration. The class should be able to handle random seed management for the different processing methods. Your task is to create a method within the class that sets up the data gen... | ```python
import numpy as np
import multiprocessing
import threading
class DataGenerator:
def __init__(self, use_multiprocessing, random_seed=None):
self._use_multiprocessing = use_multiprocessing
self.random_seed = random_seed
def data_generator_task(self):
# Your implementation of da... | magicoder | python |
You are tasked with creating a Python programming problem related to using the Factory Boy library for Django model factories. The problem should test the understanding of creating and using Django model factories to generate test data for a Django application. | ```python
# Problem Description
You are required to create a Django model factory using the Factory Boy library to generate test data for a Django application. The factory should be able to create instances of the Place model, which is a part of the Django application.
Your task is to complete the implementation of th... | magicoder | python |
You are tasked with implementing a simple dependency injection container in Python. A dependency injection container is a design pattern used to manage the dependencies of an application. The container is responsible for creating and managing instances of classes and providing them to other parts of the application tha... | ```python
class DependencyContainer:
_instance = None
@classmethod
def Instance(cls):
if cls._instance is None:
cls._instance = cls()
return cls._instance
def __init__(self):
self._registry = {}
def register(self, class_type, factory_function):
self._re... | magicoder | python |
You are tasked with implementing a simplified version of a web browser class in C++. The provided code snippet is a part of the Browser class, which contains two member functions: `calc_time` and `on_page_loaded`. The `calc_time` function takes an integer parameter `calc_repeat` and appears to be related to rendering t... | ```cpp
#include <iostream>
class View {
public:
void render(bool param1, bool param2, int repeat) {
// Implementation of rendering the view
std::cout << "Rendering view " << repeat << " times with parameters " << param1 << " and " << param2 << std::endl;
}
int wnd() {
// Return win... | magicoder | cpp |
You are tasked with implementing a simplified file management system in C++. The system should support basic file operations such as creating, opening, reading, writing, and closing files. You are provided with a partial code snippet that demonstrates the creation of a file object and the subsequent operations on it.
... | ```cpp
#include <iostream>
#include <fstream>
#include <string>
class AltFile {
private:
std::string filename;
std::fstream fileStream;
bool isOpen;
public:
AltFile(const std::string& filename) : filename(filename), isOpen(false) {}
bool open() {
fileStream.open(filename, std::ios::in | s... | magicoder | cpp |
You are tasked with implementing a function that takes in a list of shapes and data types, and returns a list of tensors with the specified shapes and data types. However, the function should also handle the special case where a shape dimension is set to -1, indicating that the dimension should be inferred based on the... | ```python
import syft
from itertools import zip_longest
import numpy as np
def create_tensors(args_shape, args_dtypes):
"""
Create tensors based on the specified shapes and data types.
Args:
args_shape (list): A list of tuples representing the shapes of the tensors.
args_dtypes (list): A list of d... | magicoder | python |
You are tasked with implementing a Bluetooth service management system for a desktop application. The system involves a `MainApp` class that manages a `BtService` object responsible for handling Bluetooth functionality. The `MainApp` class contains a method `on_quit()` that is called when the application is closed. Wit... | ```cpp
#include <iostream>
#include <QString>
#include <QDebug>
class BtService {
private:
QString adapter_address_;
public:
BtService(const QString& adapter_address) : adapter_address_(adapter_address) {
// Initialization and Bluetooth functionality setup
}
void restart(const QString& new_ad... | magicoder | cpp |
You are tasked with creating a script to automate the deployment process for a web application. The deployment process involves pulling the latest changes from a Git repository, building the application using Gradle, building a Docker image, and then deploying the application using Docker Compose.
Your task is to writ... | ```bash
#!/bin/bash
# Step 1: Pull the latest changes from the Git repository
if ! git pull --ff-only; then
echo "Error: Failed to pull the latest changes from the Git repository"
exit 1
fi
# Step 2: Build the application using Gradle
if ! ./gradlew build; then
echo "Error: Failed to build the application using... | magicoder | shell |
You are tasked with creating a Python function that processes model parameters and generates a configuration for training a machine learning model on a Tensor Processing Unit (TPU). The function should take in various model parameters and save parameters, and construct a training TPU configuration. Additionally, it sho... | ```python
def create_tpu_training_config(model_params, save_params):
DEFAULT_TPU_ZONE = 'us-central1-a'
DEFAULT_NUM_SHARDS = 8
DEFAULT_ITERATIONS_PER_LOOP = 1000
train_m_config = create_train_tpu_config(model_dir=save_params.get('cache_dir', ''),
tpu_name=model_params.get('tpu_n... | magicoder | python |
You are tasked with creating a GraphQL resolver function for a company entity using TypeScript and TypeORM. The company entity has an ID field that is auto-generated. Your task is to implement the resolver function that retrieves a company's ID from the database.
You are provided with the following code snippet as a s... | ```typescript
import { Resolver, Query, Arg } from 'type-graphql';
import { CompanyEntity } from './CompanyEntity';
@Resolver()
export class CompanyResolver {
@Query(() => CompanyEntity)
async companyResolver(@Arg('id') id: number): Promise<{ id: number }> {
const company = await CompanyEntity.findOne(id);
... | magicoder | typescript |
You are given a binary tree where each node contains an integer value. Write a function `max_path_sum` to find the maximum path sum. A path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to... | ```python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def max_path_sum(root: TreeNode) -> int:
max_sum = float('-inf')
def max_gain(node):
nonlocal max_sum
if not node:
return 0
... | magicoder | python |
You are tasked with creating a Python function that generates a random IPv4 or IPv6 address based on certain criteria. The function should take in two boolean parameters, `ipv6` and `ip3`, which indicate whether the address should be IPv6 and whether it should have 3 sections (for IPv4) or 8 sections (for IPv6), respec... | ```python
import random
def generate_random_ip(ipv6: bool, ip3: bool) -> str:
if ipv6:
sections = [format(random.randint(0, 65535), 'x') for _ in range(8)]
return ":".join(sections)
elif ip3:
sections = [str(random.randint(0, 255)) for _ in range(3)]
return ".".join(sections)
... | magicoder | python |
You are tasked with creating a Python function that reads a given file and counts the occurrences of each word within it. The function should ignore case sensitivity and consider only alphanumeric characters as part of a word. Additionally, the function should return the top N most frequently occurring words and their ... | ```python
from typing import List, Tuple
import re
from collections import Counter
def top_n_words(file_path: str, n: int) -> List[Tuple[str, int]]:
with open(file_path, 'r') as file:
content = file.read().lower()
words = re.findall(r'\b\w+\b', content)
word_counts = Counter(words)
... | magicoder | python |
You are tasked with implementing a program to generate QR codes with different mask patterns. A QR code consists of a matrix of black and white modules, and the mask pattern is used to determine the pattern of modules to be applied to the QR code. The mask pattern is represented by an 8-bit binary number, where each bi... | ```swift
func generateQRCode(maskPattern: Int) -> [[Int]] {
var qrCode = Array(repeating: Array(repeating: 0, count: 21), count: 21)
for i in 0..<21 {
for j in 0..<21 {
let condition0 = (i + j) % 2 == 0 ? 1 : 0
let condition1 = i % 2 == 0 ? 1 : 0
let condition2 =... | magicoder | swift |
You are given a list of frequencies `freqs` representing the frequencies of musical notes. Your task is to convert these frequencies into their corresponding note names based on the standard musical scale. The standard musical scale consists of the following notes: "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", ... | ```python
def freq_to_notes(freqs):
note_ranges = {
"C": (16.35, 17.32),
"C#": (17.32, 18.35),
"D": (18.35, 19.45),
"D#": (19.45, 20.60),
"E": (20.60, 21.83),
"F": (21.83, 23.12),
"F#": (23.12, 24.50),
"G": (24.50, 25.96),
"G#": (25.96, 27.50),... | magicoder | python |
You are tasked with creating a Python program that simulates a simple command-line interface for managing a music library. The program should utilize the `argparse` module to handle command-line arguments and subcommands. Your task is to implement the functionality for adding, listing, and removing songs from the music... | ```python
import argparse
def add_song(args):
print(f"Adding song: Title - {args.title}, Artist - {args.artist}, Album - {args.album}")
def list_songs(args):
print("Listing all songs in the music library")
def remove_song(args):
print(f"Removing song: Title - {args.title}")
def main():
parser = argp... | magicoder | python |
You are tasked with implementing a custom loss function for a binary classification problem using TensorFlow and Keras. The custom loss function to be implemented is the binary focal loss, which is designed to address class imbalance and focus on hard examples during training.
The binary focal loss function is defined... | To implement the binary focal loss function in TensorFlow/Keras, you can use the following code:
```python
import tensorflow as tf
from tensorflow.keras import backend as K
def binary_focal_loss(gt, pred, gamma=2.0, alpha=0.25):
"""Implementation of binary focal loss."""
epsilon = K.epsilon()
pt_1 = tf.wh... | magicoder | python |
You are tasked with implementing a deep learning pipeline for image processing using PyTorch and the torchvision library. The pipeline involves loading a custom dataset, applying data augmentation, simulating measurements, and training a neural network model.
Your task is to create a Python function that performs the ... | ```python
import matplotlib as mpl
import torch
import torchvision
from data_management import IPDataset, Jitter, SimulateMeasurements
from networks import IterativeNet, Tiramisu
def deep_learning_pipeline(dataset_path, num_epochs):
# Step 1: Load custom dataset
custom_dataset = IPDataset(dataset_path)
# ... | magicoder | python |
You are tasked with implementing a function to perform a random vertical shift on an input image based on a given mask. The function should take into account a maximum allowable shift proportion, a probability of applying the shift, and handle the re-introduction of elements that roll beyond the last position.
You are... | ```python
import numpy as np
def applyVerticalShift(image, mask, max_shift=0.05, p=0.5):
"""Apply random vertical shift to the input image based on the mask."""
if np.random.rand() < p: # Apply the shift with probability p
max_shift_pixels = int(max_shift * image.shape[0])
shift = np.random.ch... | magicoder | python |
You are tasked with implementing a print queue system using Java's multithreading capabilities. The print queue should allow multiple threads to add print jobs to the queue and ensure that only one job is printed at a time. Each job should be assigned a priority, and the print queue should process jobs based on their p... | ```java
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class PrintQueue {
private final Lock queueLock = new ReentrantLock();
public void printJob(String jobName) {
queueLock.lock();
try {
System.out.println("Printing " + jobName + "...");
... | magicoder | java |
You are tasked with implementing a Python function that processes a list of mode values and returns the frequency of each mode in the list. The mode of a set of data values is the value that appears most frequently. If there are multiple modes, all of them should be returned. If there are no repeated values, the functi... | ```python
def find_modes(data):
mode_count = {}
max_count = 0
modes = []
for value in data:
if value in mode_count:
mode_count[value] += 1
else:
mode_count[value] = 1
if mode_count[value] > max_count:
max_count = mode_count[value]
for ke... | magicoder | python |
You are tasked with implementing a program that can efficiently determine the frequency of each word in a given text. The program should ignore punctuation and consider words regardless of their case (i.e., "Hello" and "hello" should be considered the same word). Additionally, the program should exclude common stop wor... | ```python
from typing import List, Dict
import re
def wordFrequency(text: str, stopWords: List[str]) -> Dict[str, int]:
# Convert text to lowercase and remove punctuation
text = re.sub(r'[^\w\s]', '', text.lower())
# Split the text into words
words = text.split()
# Remove stop words
w... | magicoder | python |
You are tasked with creating a script to automate the process of grabbing an m3u8 playlist file from a specific Python script and its dependencies. The provided code snippet is a part of the automation script and contains the following commands:
1. Print the directory path of the current script.
2. Install the Python p... | ```python
import os
import subprocess
# Print the directory path of the current script
current_dir = os.path.dirname(os.path.realpath(__file__))
print(current_dir)
# Install the Python package "requests" using pip
try:
subprocess.run(['python3', '-m', 'pip', 'install', 'requests'], check=True)
print("requests... | magicoder | python |
You are tasked with creating a validation rule for a PHP model class in a web application. The validation rule should ensure that a specific attribute exists in another model class. You will need to implement the validation rule and test it with sample data.
Your task is to create a PHP validation rule that checks if ... | ```php
// Group.php
class Group extends \yii\db\ActiveRecord
{
// ... other attributes and methods
public function rules()
{
return [
// Other rules...
[['parent_group_id'], 'exist', 'skipOnError' => true, 'targetClass' => Group::className(), 'targetAttribute' => ['parent_gr... | magicoder | php |
You are tasked with creating a Python class that simulates a simple file compression and extraction process. Your task is to implement a method within the `Tar` class that unpacks an archive file using optional compression. The method should calculate the original size of the archive and handle the extraction process b... | ```python
from pathlib import Path
import typing
from ...styles import styles
from ..compression import CompressionT
from . import ArchiveFormat
class Tar(ArchiveFormat):
@staticmethod
def unpack(archPath: Path, extrDir: Path, config: "FetchConfig", compression: typing.Optional[CompressionT] = None) -> None:
... | magicoder | python |
You are tasked with simulating a simplified version of a multiprocessing system for image processing. The provided code snippet is part of a larger program that creates a pool of processes to detect images and then starts the master process and a writer process if the program is set to run in actual mode.
Your task is... | ```python
import multiprocessing
import queue
def detectImage(queue, image_path):
# Simulate image processing task (simplified for demonstration)
processed_result = f"Processed result of {image_path}"
queue.put(processed_result)
def simulateImageProcessing(imagePaths, sizeOfPool, actualRun):
result_qu... | magicoder | python |
You are tasked with creating a Python function that processes a list of strings representing file paths and returns a dictionary containing the count of files with each unique file extension. The file extension is defined as the substring following the last occurrence of the dot (.) in the file name. If a file has no e... | ```python
from typing import List, Dict
def count_file_extensions(file_paths: List[str]) -> Dict[str, int]:
file_extension_count = {}
for file_path in file_paths:
file_name = file_path.split("/")[-1] # Extract the file name from the path
if "." in file_name:
file_extension = file_n... | magicoder | python |
You are tasked with creating a program that processes an audio file and splits it into multiple segments based on periods of silence. Your program should use the `ffmpeg` command-line tool to achieve this.
Your program should take an audio file as input and use the `silencedetect` filter in `ffmpeg` to detect periods ... | ```bash
#!/bin/bash
# Function to process the audio file and generate ffmpeg commands for splitting based on silence
process_audio() {
local audio_file=$1
local silence_threshold="-50dB" # Silence threshold level
local silence_duration="0.3" # Minimum duration of silence to be considered
# Use ff... | magicoder | shell |
You are tasked with creating a program to visualize a 3D grid and several wireframe cubes using a graphics library. The provided code snippet is a part of the program that draws a 3D grid and three wireframe cubes at specific positions and with specific dimensions. Your task is to complete the program by implementing t... | ```python
# Import the necessary graphics library
import graphics_library
# Function to draw a 3D grid
def draw_grid(size, spacing, color1, color2):
for i in range(-size, size+1):
if i % 2 == 0:
graphics_library.draw_line((i*spacing, 0, -size*spacing), (i*spacing, 0, size*spacing), color1)
... | magicoder | python |
You are tasked with implementing a Rust program that processes a collection of module comments and generates a list of comments as strings. Each comment is extracted from a specific span within the code and is represented by the `Comment` struct. Your task is to complete the implementation of the `process_comments` fun... | ```rust
fn process_comments(module: &Module) -> Vec<String> {
module
.extra
.module_comments
.iter()
.map(|span| {
Comment::from((span, module.code.as_str()))
.content
.to_string()
})
.collect()
}
```
The `process_comments`... | magicoder | rust |
You are tasked with implementing a function that processes data and generates a GeoJSON feature collection. The function takes in a list of dictionaries, `valueLinks`, each containing a key 'value' that corresponds to a key in another dictionary `record`. The function also receives a dictionary `mappedGeometries` that ... | ```python
from typing import List, Dict, Any, Tuple
import geojson
def process_data(valueLinks: List[Dict[str, Any]], record: Dict[str, Any], mappedGeometries: Dict[str, Any]) -> Tuple[Dict[str, Any], int]:
assembled = []
linkingDuplicateCount = 0
seen_keys = set()
for link in valueLinks:
... | magicoder | python |
You are tasked with implementing a function to convert a given positive integer into its binary representation. The function should take an integer as input and return a list representing the binary digits of the input number. For example, the integer 13 should be converted to the binary representation [1, 1, 0, 1].
Y... | ```python
import numpy as np
def num2bin(num):
if num == 0:
return [0]
else:
pow_max = int(np.floor(np.log2(num)))
pow_list = [k for k in range(pow_max, -1, -1)] # Generate a list of powers of 2 in descending order
bin_list = []
for power in pow_list:
if nu... | magicoder | python |
You are tasked with implementing a connection pool for a database management system. The connection pool should manage a fixed number of connections and provide a way to acquire and release connections for use by multiple threads.
You are given a partial code snippet for the `ConnectionPool` class, which includes the ... | ```java
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class ConnectionPool {
private final PoolableConnection[] pool;
private final AtomicLong counter;
private f... | magicoder | java |
You are tasked with creating a program that reads a list of numbers from a file and calculates the sum of all the numbers in the list. The file "list.txt" contains a series of integers separated by spaces, with each integer on a new line. Your program should read the file, calculate the sum of the numbers, and then out... | ```python
# Open the file "list.txt" in read mode
with open("list.txt", "r") as file:
# Initialize the sum to 0
total_sum = 0
# Iterate through each line in the file
for line in file:
# Convert the line to an integer and add it to the total sum
total_sum += int(line)
# Output the total s... | magicoder | python |
You are tasked with creating a custom step converter for the Blackfire Player, a tool for testing and profiling web applications. The Blackfire Player uses a domain-specific language to define scenarios for testing web applications. Your task is to implement a custom step converter that can translate a specific type of... | ```php
use Blackfire\Player\Guzzle\StepConverter;
use Blackfire\Player\Step\FollowStep;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
class CustomStepConverter implements StepConverter
{
public function convertStep($step)
{
if ($step instanceof FollowStep) {
$url = $step->getUrl();
... | magicoder | php |
You are tasked with implementing a secure checkout process for an e-commerce platform. The platform uses Spring Boot for its backend services and relies on the RestTemplate for making HTTP requests. The checkout process should be designed to retrieve the user's context and process the order details securely.
You are p... | ```java
RestTemplate restTemplate;
@Autowired
UserContext userContext;
@RequestMapping(value = "", method = RequestMethod.POST)
public ResponseEntity<String> checkout(@RequestBody Order order) {
try {
// Retrieve user context
User currentUser = userContext.getCurrentUser();
// Validate us... | magicoder | java |
You are tasked with creating a Python package that provides a set of mathematical functions. Your package should include a function to calculate the factorial of a given number. Additionally, you need to ensure that the package version is correctly defined and accessible.
Your task is to implement the `factorial` func... | ```python
# math_functions/__init__.py
__version__ = '1.0.0'
# math_functions/factorial/__init__.py
from .calculate_factorial import calculate_factorial
# math_functions/factorial/calculate_factorial.py
def calculate_factorial(n):
if n < 0:
return "Factorial is not defined for negative numbers"
elif n... | magicoder | python |
You are tasked with implementing a Python function that validates the correctness of a given type hint for a policy in a reinforcement learning framework. The type hint is represented as a Union of two types, where one type is a BasePolicy and the other type is an nn.Module. Your function should determine if the type h... | ```python
from typing import Union, Type
from torch import nn
BasePolicy = Type['BasePolicy'] # Assuming BasePolicy is a class type
def validate_policy_type_hint(policy_type_hint: type) -> bool:
if hasattr(policy_type_hint, "__origin__") and policy_type_hint.__origin__ is Union:
return BasePolicy in poli... | magicoder | python |
You are tasked with simulating a remote control interface for a smart TV application. The remote control has directional buttons (up, down, left, right) and a select button. The task is to write a function that takes a sequence of remote control commands and simulates the actions performed on the TV application.
You a... | ```swift
struct RemoteControlCommand {
let button: RemoteButton
let times: Int
}
enum RemoteButton {
case up
case down
case left
case right
case select
}
func simulateRemoteControl(commands: [RemoteControlCommand]) -> String {
var currentState = "Ready"
for command in commands... | magicoder | swift |
You are tasked with implementing a simple task execution framework in Java. The framework consists of a `Task` interface and a `TaskResult` class. The `Task` interface has four methods: `prepare`, `execute`, `clean`, and `getNextTask`. The `prepare` method takes a `Map` as a parameter, the `execute` method returns a `T... | ```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public interface Task {
void prepare(Map<String, String> conf);
TaskResult execute();
void clean();
Task getNextTask();
}
class TaskResult {
private int wor... | magicoder | java |
You are tasked with implementing a dependency resolution algorithm for a package manager. The package manager maintains a list of packages and their dependencies. Each package can have zero or more dependencies, and dependencies can have their own dependencies, forming a dependency tree.
Your task is to write a functi... | ```python
def get_all_dependencies(package_name, packages):
visited = set()
def dfs(package):
if package in visited:
return
visited.add(package)
for dependency in packages.get(package, {}).get('dependencies', []):
dfs(dependency)
dfs(package_name)
return... | magicoder | python |
You are tasked with implementing a Python class that represents a model defined in OpenAPI. The class should have an `__init__` method that accepts any number of positional and keyword arguments and converts them from JavaScript naming convention to Python naming convention. The class should also have private attribute... | ```python
def convert_js_args_to_python_args(func):
def wrapper(*args, **kwargs):
converted_kwargs = {convert_to_python_style(key): value for key, value in kwargs.items()}
return func(*args, **converted_kwargs)
return wrapper
def convert_to_python_style(name):
parts = name.split('_')
re... | magicoder | python |
You are tasked with implementing a method to handle pre-processing of HTTP requests in a Java web application. The method should check for Cross-Origin Resource Sharing (CORS) and handle OPTIONS requests appropriately.
You are given a code snippet of the `preHandle` method from a Java class implementing the `HandlerIn... | ```java
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// === Check CORS
if (RequestMethod.OPTIONS.name().equals(request.getMethod())) {
return true; // Allow preflight request to proceed
} else {
String origin = request.... | magicoder | java |
You are working on a data processing module that involves handling different types of data sources. You have a class `DataProcessor` with a method `process_data` that is responsible for processing the data based on the source type. The method has the following structure:
```python
def process_data(self):
if self.s... | ```python
def process_data(self):
if self.source_type == 'text':
return pd.DataFrame(self.txt_helper, columns=self.columns)
elif self.local:
temp_df = pd.read_csv(self.raw_data_path, sep=self.sep, header=self.header, names=self.names)
return temp_df
elif self.download_type == 'url':
... | magicoder | python |
You are working on a PHP application that interacts with a database to retrieve and process data related to items and their categories. The given code snippet is part of a class that handles database operations. The `read_category` method is responsible for fetching category information from the database table `tb_cate... | ```php
public function read_category(){
$query = $this->db->get('tb_cate');
$result = array();
foreach ($query->result() as $row) {
$result[$row->cate_indx] = $row->cate_name;
}
return $result;
}
public function read_item(){
$query = $this->db->get('tb_item');
$result = array();
foreach ($query-... | magicoder | php |
You are tasked with creating a Python script that reads a configuration file and extracts the target Android architecture based on the command-line argument provided. The script should handle various scenarios, including missing command-line arguments and invalid architecture values.
Your task is to implement the `get... | ```python
import argparse
import configparser
class AndroidArchitectureExtractor:
def __init__(self, spec_file):
self.spec_file = spec_file
def get_android_architecture(self):
parser = argparse.ArgumentParser("Get the target android architecture")
parser.add_argument("--arch", type=str... | magicoder | python |
You are tasked with implementing a game called "Mastermind." In this game, the player must guess a secret code consisting of a sequence of colors. After each guess, the player receives feedback in the form of two numbers: the number of correct colors in the correct positions (correct_position) and the number of correct... | ```python
else: # correct_position < max_count
# Put the old color back
guess[idx] = max_color
# Put the new color back into the queue
q.appendleft(idx_guess)
# Reset invalid colors
invalid_color_idx.clear()
# Move to next index
idx += 1
```
In the provided solution, the logic for handl... | magicoder | python |
You are tasked with implementing a Python class that can convert its attributes to a dictionary format. The class should handle nested objects and lists of objects, converting them to dictionaries as well. Your task is to complete the implementation of the `to_dict` method in the given Python class.
```python
class Ex... | ```python
class ExampleClass:
def __init__(self):
self.swagger_types = {
'attr1': 'str',
'attr2': 'int',
'attr3': 'list[AnotherClass]'
}
self.attr1 = "example"
self.attr2 = 42
self.attr3 = [AnotherClass()]
class AnotherClass:
def __ini... | magicoder | python |
You are working on a project that involves querying a GraphQL API to retrieve information about the schema. You need to write a script to automate this process. The GraphQL API endpoint is "https://serve.onegraph.com/dynamic?app_id=d4b3c1de-6186-474e-bf27-0b97070217a5". You have been provided with a code snippet that i... | Python Solution:
```python
import requests
import json
# Construct the GraphQL query
query = """
{
__InputValue { name description type { ...TypeRef } defaultValue } fragment
TypeRef on __Type { kind name ofType { kind name ofType { kind name ofType
{ kind name ofType { kind name ofType { kind name ofType { kin... | magicoder | python |
You are tasked with creating a benchmarking tool for a grid-based algorithm. The algorithm operates on a grid with a specified number of rows and columns, and it involves a delay parameter that affects its execution time. Your goal is to implement a benchmarking function that measures the performance of two different s... | ```go
package main
import (
"fmt"
"os/exec"
)
func benchmarkSolutions(rows, cols, delay int) {
// Execute solution1 benchmark
cmd1 := exec.Command("go", "test", "-run=NONE", "-bench=.", "-args", fmt.Sprintf("-rows=%d", rows), fmt.Sprintf("-cols=%d", cols), fmt.Sprintf("-delay=%d", delay))
cmd1.Dir = "path_to_sol... | magicoder | go |
You are tasked with implementing a function that updates a user's subscription status based on the provided request body. The function should handle different HTTP methods and user authentication. You are given a partial code snippet as a reference.
You need to create a function `handleUserSubscription` that takes thr... | ```javascript
async function handleUserSubscription(req, user, done) {
if (req.method === 'PUT') {
if (!user) {
return done(403, {
message: 'You must be logged in to do this',
});
}
let updatedUser;
if (req.body.hasOwnProperty('isSubscribed')) {
updatedUser = await updateUse... | magicoder | javascript |
You are tasked with implementing a custom message handler in a Java web service using Apache Axis2. Your goal is to intercept incoming SOAP messages and extract specific information from the message context. The Apache Axis2 library provides classes and interfaces to work with the message context and handle incoming SO... | ```java
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.description.AxisOperation;
import org.apache.axis2.handlers.AbstractHandler;
public class CustomMessageHandler extends AbstractHandler {
@Override
public InvocationResponse inv... | magicoder | java |
You are working on a system that manages patient records in a healthcare application. The system uses a Python-based web framework called Frappe. The code snippet provided is a part of a function that updates patient records based on certain filters and fields. The `filters` dictionary contains filter conditions for th... | ```python
def update_patient_records(filters, fields, as_list):
updated_records = []
# Iterate through patient records
for name, fieldname, customer in get_patient_records():
match_filters = all(
apply_filter(name, fieldname, operator, value)
for fieldname, (operator, value)... | magicoder | python |
You are working on a project that involves setting up and managing software packages using the CMT (Configuration Management Tool) system. Your task is to create a script that automates the setup process for a specific software package called "JsubHelloWorld" with version "v1" in a given directory path.
The setup proc... | ```bash
#!/bin/bash
# Set the CMTROOT environment variable if not already set
if [ -z "${CMTROOT}" ]; then
CMTROOT="/cvmfs/juno.ihep.ac.cn/sl6_amd64_gcc830/Pre-Release/J20v1r1-branch/ExternalLibs/CMT/v1r26"
export CMTROOT
fi
# Source the CMT setup script
source "${CMTROOT}/mgr/setup.sh"
# Generate a temporary fi... | magicoder | shell |
You are tasked with implementing a Gaussian Mixture Model (GMM) using the `sklearn` library in Python. The GMM is a probabilistic model that assumes all the data points are generated from a mixture of several Gaussian distributions with unknown parameters. Your goal is to create a program that uses the GMM to fit a giv... | ```python
from sklearn.mixture import GaussianMixture
import numpy as np
def fit_and_predict_gmm(data, num_components):
gmm = GaussianMixture(n_components=num_components, random_state=0)
gmm.fit(data)
probabilities = gmm.predict_proba(data)
return probabilities
# Example usage
data = [[1.2, 2.3], [3.5... | magicoder | python |
You are tasked with implementing a custom table view cell for displaying comments in a social media app. The cell should be registered with the table view, and the table view's delegate and data source should be set. Additionally, you need to prepare a custom card view to display a pin, set its delegate, and set the de... | ```swift
func setupViews() {
// Register custom table view cell
commentsTableView.register(UINib(nibName: "PinCommentCell", bundle: nil), forCellReuseIdentifier: "PinCommentCell")
// Set table view delegate and data source
commentsTableView.delegate = self
commentsTableView.dataSource = self
... | magicoder | swift |
You are tasked with creating a simple animation system for a 2D game using Python and the Pygame library. The code snippet provided initializes a variable `update_time` with the current time using `pygame.time.get_ticks()` and then proceeds to load images for different player animations.
Your task is to implement a cl... | ```python
import pygame
class PlayerAnimation:
def __init__(self):
self.update_time = pygame.time.get_ticks()
self.animation_images = {}
def load_images(self, animation_types, image_folder):
for animation in animation_types:
image_list = []
for i in range(1, 4):... | magicoder | python |
You are tasked with creating a Bash script that processes a directory structure and performs specific operations on the files within it. The script should take the base path of the directory as a command-line argument and then execute the following tasks:
1. List all the files in the directory and its subdirectories.
2... | ```bash
#!/bin/bash
base_path=$1
# Function to process directory
process_directory() {
local dir_path=$1
local total_size=0
# List all files in the directory and its subdirectories
while IFS= read -r -d '' file; do
if [[ -f $file ]]; then
# If it's a regular file, display its name... | magicoder | shell |
You are tasked with creating a Python function that simulates a simple text-based adventure game. The game will involve navigating through different rooms, encountering obstacles, and making decisions that affect the outcome of the game.
Your task is to implement the `adventure_game` function, which takes no arguments... | ```python
import random
def adventure_game():
rooms = ["lobby", "kitchen", "library", "garden"]
outcomes = {
"kitchen": {
"meal": "You enjoy a delicious meal prepared by the friendly chef. You win!",
"rat": "A mischievous rat steals your supplies. You lose!"
},
"... | magicoder | python |
You are tasked with implementing a function to parse and process a simplified version of a spreadsheet formula. The formula consists of a series of operations and functions that need to be evaluated in a specific order. The operations include addition, subtraction, multiplication, and division, while the functions incl... | ```python
def evaluate_formula(formula: str) -> float:
operations = {'+': lambda x, y: x + y, '-': lambda x, y: x - y, '*': lambda x, y: x * y, '/': lambda x, y: x / y}
functions = {'RefreshAll()': lambda: None, 'quit()': lambda: None}
tokens = formula.split()
result = 0
current_op = '+'
i = 0
... | magicoder | python |
You are tasked with implementing a Python class method that makes a REST API call using an API key. The method should handle various parameters such as the endpoint, action result, optional parameters, data, HTTP method, and SSL verification. Additionally, the method should update the progress and return a status based... | ```python
def _make_rest_call_using_api_key(self, endpoint, action_result, params=None, data=None, method="get", verify=False):
import requests
headers = {
'Authorization': 'Bearer ' + self.api_key # Assuming self.api_key is the API key
}
try:
response = requests.request(method, endpo... | magicoder | python |
You are tasked with analyzing and optimizing the garbage collection (GC) process for a Java web application. The application is run using the following command:
```bash
java -XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:+PrintGCTimeStamps -Xloggc:gc.log -jar target/webcv-0.0.1-SNAPSHOT.jar
```
The flags used in the ... | To solve this problem, you would need to perform the following steps:
1. Analyze GC Logs:
- Start by examining the `gc.log` file generated by the application to understand the GC behavior, including frequency, duration, and impact on the application's performance.
- Look for patterns such as long GC pauses, freq... | magicoder | java |
You are tasked with implementing a Python function that processes a list of rules and returns a modified list based on specific criteria. Each rule is represented as a dictionary with the following keys: 'name', 'condition', and 'action'. The 'name' key holds a string representing the rule's name, the 'condition' key h... | ```python
from typing import List, Dict, Union
def process_rules(rules: List[Dict[str, Union[str, bool]]]) -> List[str]:
modified_rules = []
for rule in rules:
if rule['condition']:
modified_action = rule['action'] + '_' + rule['name']
modified_rules.append(modified_action)
... | magicoder | python |
You are tasked with creating a Python script that automates the installation of required packages for a data analysis project. The script should install the necessary packages using pip, but it should also ensure that the correct version of matplotlib is installed. Your task is to write a Python script that accomplishe... | ```python
import subprocess
import pkg_resources
# Step 1: Install pandas
subprocess.run(['sudo', '-H', 'pip3', 'install', 'pandas'])
# Step 2: Install joblib
subprocess.run(['sudo', '-H', 'pip3', 'install', 'joblib'])
# Step 3: Install scikit-plot
subprocess.run(['sudo', '-H', 'pip3', 'install', 'scikit-plot'])
# ... | magicoder | python |
You are tasked with implementing a command-line processing function in Rust. The function should parse the input command line and execute the corresponding handlers based on the registered commands.
You are provided with the following code snippet as a starting point:
```rust
/// passed as we want to process the cmdl... | ```rust
// Example implementation of the process function
pub fn process(cmdline: &str) {
let parts: Vec<&str> = cmdline.split_whitespace().collect();
if let Some((command, args)) = parts.split_first() {
match command {
"command1" => handle_command1(args),
"command2" => handle_co... | magicoder | rust |
You are tasked with creating a module bundler for a JavaScript project. Your goal is to implement a function that takes in an array of import statements and returns a single string representing the bundled code.
The import statements are in the following format:
```javascript
export { ModuleName } from './ModulePath';... | ```javascript
function bundleModules(importStatements) {
const modules = {};
// Parse import statements and store module names and paths
importStatements.forEach(statement => {
const [_, moduleName, modulePath] = statement.match(/export { (.+) } from '(.+)';/);
modules[moduleName] = modulePath;
});
... | magicoder | javascript |
You are tasked with creating a feature for a web application that allows users to view and delete their profiles using the ag-Grid library for displaying tabular data. The application uses Angular and RxJS for handling asynchronous operations.
Your task is to implement a profile management component that utilizes the ... | ```typescript
// profile-management.component.ts
import { Component, OnDestroy, OnInit } from '@angular/core';
import { ProfileService } from './profile.service';
import { Profile } from './profile.model';
import { GridApi, ColDef } from 'ag-grid';
import { DeleteCellComponent } from '../shared/delete-cell.component';
... | magicoder | typescript |
You are tasked with creating a Python class that simulates a simple event-driven system. The class, named `EventReader`, is responsible for reading input events from a device and notifying a callback function when a new event is detected. Your task is to implement the `EventReader` class with the following specificatio... | ```python
import threading
import evdev
class EventReader:
def __init__(self):
self.thread = None
self.running = False
self.callback = None
def start(self, callback):
self.thread = threading.Thread(target=self.__loop)
self.running = True
self.callback = callback... | magicoder | python |
You are working on a machine learning project and need to split a dataset into training, testing, and validation sets. The dataset is stored in a NumPy array `_FILE`, and before splitting, you need to perform some preprocessing steps. The given code snippet calculates the mean image of the dataset and then subtracts th... | ```python
import numpy as np
def split_dataset(_FILE, train_ratio, test_ratio, val_ratio):
# Shuffle the dataset
np.random.shuffle(_FILE)
total_length = len(_FILE)
train_size = int(total_length * train_ratio)
test_size = int(total_length * test_ratio)
# Split the dataset based on the ... | magicoder | python |
You are tasked with creating a Python module for simulating different types of artificial lungs. The module should include classes for various lung models, each implementing a different control algorithm. Your task is to design and implement the classes for three different lung models: BalloonLung, DelayLung, and Physi... | ```python
from deluca.lung.environments._cnn import CNN
from deluca.lung.environments._lstm import LSTM
from deluca.lung.environments._mlp import MLP
class BalloonLung:
def __init__(self):
self.cnn = CNN()
def set_control_parameters(self, parameters):
self.cnn.set_parameters(parameters)
d... | magicoder | python |
You are tasked with implementing a data management system that handles various data sources. The system is designed to instantiate data sources based on provided configurations and handle exceptions that may occur during the instantiation process. Additionally, the system needs to set a specific data source that define... | ```python
import logging
class DataManagementSystem:
def __init__(self, config):
self.config = config
self.data_sources = {}
self.data_source_which_defines_geospatial_locations = None
self.logger = logging.getLogger(__name__)
def instantiate_data_source(self, data_source_class,... | magicoder | python |
You are tasked with implementing a PointsApi class that manages a collection of 2D points. The PointsApi class should provide methods for adding points, calculating the distance between two points, and finding the closest point to a given point.
Your task is to implement the PointsApi class with the following methods:... | ```java
import java.util.ArrayList;
import java.util.List;
public class PointsApi {
private List<int[]> points;
public PointsApi() {
points = new ArrayList<>();
}
public void addPoint(int x, int y) {
points.add(new int[]{x, y});
}
public double distance(int x1, int y1, int x2... | magicoder | java |
You are tasked with implementing a function that processes data from a simulation and generates a plot using the matplotlib library in Python. The given code snippet is part of a larger program and is responsible for plotting a subset of the simulation data. The `bload` object contains a `P_history` attribute, which is... | ```python
import numpy as np
import matplotlib.pyplot as plt
class BLoad:
def __init__(self, P_history, tau_history):
self.P_history = P_history
self.tau_history = tau_history
def plot_simulation_data(bload, ax, c):
P_history = bload.P_history
new_Ps = np.asarray([P[0] for P in P_history])... | magicoder | python |
You are working on a web application that requires user authentication. The application uses a configuration file named `config` to store various settings and credentials. Additionally, it utilizes a module named `cookie_login` to handle user login using cookies.
Your task is to implement a function that reads the con... | ```python
import config
import cookie_login
def authenticate_with_config(username, password):
# Read the database credentials from the config settings
db_credentials = config.settings['database']
db_username = db_credentials['username']
db_password = db_credentials['password']
# Authenticate the u... | magicoder | python |
You are given a series of commands used in a bioinformatics pipeline to process and manipulate BED and BDG files. Your task is to write a Python script to automate the execution of these commands and perform the same operations on the input files.
The commands are as follows:
1. Convert the "B2_169_5_flt_sft_macs.bed_... | ```python
import subprocess
input_file = "B2_169_5_flt_sft_macs.bed_treat_pileup_sorted.bdg"
output_file_bed = "B2_169_5_flt_sft_macs.bed_treat_pileup_sorted.bed"
output_file_flb_bed = "B2_169_5_flt_sft_macs.bed_treat_pileup_sorted_flb.bed"
output_file_flb_bdg = "B2_169_5_flt_sft_macs.bed_treat_pileup_sorted_flb.bdg"
... | magicoder | python |
You are given a list of integers representing the scores of participants in a competition. The scores are in descending order, and each score is unique. Your task is to find the position of a specific score in the list. If the score is found, print its position (1-indexed); otherwise, print -1.
Write a function `find_... | ```python
def find_score_position(scores, target):
left, right = 0, len(scores) - 1
while left <= right:
mid = (left + right) // 2
if scores[mid] == target:
return mid + 1
elif scores[mid] < target:
right = mid - 1
else:
left = mid + 1
retu... | magicoder | python |
You are tasked with creating a function that performs parallel HTTP requests using cURL in PHP. Your function should take an array of URLs as input and return an array of the corresponding HTTP response bodies. You should utilize the cURL multi functions to efficiently handle multiple requests simultaneously.
Your fun... | ```php
function parallelHttpRequests(array $urls): array {
$urlHandlers = [];
$mh = curl_multi_init();
$urlData = [];
foreach ($urls as $url) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_multi_add_handle($mh, $ch);
$urlHandlers[] = $ch;
... | magicoder | php |
You are tasked with implementing a custom memory management system for a simplified version of a web browser's rendering engine. The system should handle memory allocation and deallocation for various types of objects used in the rendering engine.
Your task is to create a class `MemoryManager` that can allocate and de... | ```cpp
#include <iostream>
#include <unordered_map>
#include <memory>
// Define the supported object types
enum class ObjectType {
V8BindingForCore,
ArrayBufferOrArrayBufferViewOrUSVString,
Blob,
DOMArrayBuffer
};
// Define the MemoryManager class
class MemoryManager {
public:
// Allocate memory f... | magicoder | cpp |
You are working as a data scientist for a law enforcement agency, and you have been tasked with building a data preprocessing pipeline for a machine learning model. The dataset contains various features related to police operations and budget allocation. You need to create a preprocessing pipeline that handles both cat... | The `preprocess_data` function takes the input dataset and applies the defined preprocessing pipeline to transform the data. It first defines the preprocessing steps for categorical and numerical features using `SimpleImputer`, `OneHotEncoder`, and `StandardScaler`. Then, it creates separate pipelines for categorical a... | magicoder | python |
You are tasked with creating a Python function that processes a list of strings and returns a new list containing only the strings that are palindromes. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward, disregarding spaces, punctuation, and capitalization.... | ```python
def is_palindrome(s):
# Helper function to check if a string is a palindrome
s = ''.join(e for e in s if e.isalnum()).lower() # Remove spaces, punctuation, and convert to lowercase
return s == s[::-1] # Check if the string is equal to its reverse
def find_palindromes(input_list):
# Function... | magicoder | python |
You are given the definition of a binary tree node and a function to determine if two nodes in the binary tree are cousins. A cousin of a node is defined as a node that is at the same level in the binary tree but has a different parent. You need to implement the function `isCousins` to determine if two given nodes in t... | ```python
def isCousins(root: TreeNode, x: int, y: int) -> bool:
x_parent, x_depth = None, 0
y_parent, y_depth = None, 0
def dfs(node, parent, depth):
nonlocal x_parent, x_depth, y_parent, y_depth
if not node:
return
if node.val == x:
x_parent, x_depth = pare... | magicoder | python |
You are given a list of integers representing the clockwise (CW) direction of a set of movements. Each integer in the list represents a specific direction (e.g., 0 for north, 1 for east, 2 for south, 3 for west). Your task is to determine if the sum of the clockwise directions is greater than half the length of the lis... | ```python
def check_direction(cw_direction):
if sum(cw_direction) > (len(cw_direction) / 2):
return "error"
else:
return sum(cw_direction)
# Test cases
print(check_direction([0, 1, 2, 3, 0, 1, 2, 3])) # Output: "error"
print(check_direction([0, 1, 2, 3, 0, 1])) # Output: 7
``` | magicoder | python |
You are tasked with implementing a function that processes a given HTML file and extracts information about the table headers. The function should take the HTML content as input and return a list of table headers found in the file.
The HTML content will contain a table with the structure as shown in the code snippet b... | ```python
from bs4 import BeautifulSoup
from typing import List
def extractTableHeaders(htmlContent: str) -> List[str]:
table_headers = []
soup = BeautifulSoup(htmlContent, 'html.parser')
table = soup.find('table', class_='table-bordered')
if table:
headers = table.find_all('th')
table_... | magicoder | python |
You are tasked with implementing a custom JSON serialization method in Java. Your goal is to create a method that takes an object as input and returns a JSON string representation of that object. You should ensure that the method can handle various types of objects and correctly serialize them into valid JSON format.
... | ```java
import java.util.Collection;
import java.util.Map;
import java.util.stream.Collectors;
public class JsonSerialization {
public static String toJsonString(Object object) {
if (object == null) {
return "null";
} else if (object instanceof String) {
return "\"" + escap... | magicoder | java |
You are tasked with creating a script to automate the process of connecting to a PostgreSQL database running in a Docker container. The script should use the `docker exec` command to access the PostgreSQL instance and then launch the `psql` command to connect to a specific database with the given credentials.
Write a ... | ```bash
#!/bin/bash
# Check if the required number of arguments is provided
if [ "$#" -ne 3 ]; then
echo "Usage: $0 <container_name> <database_name> <username>"
exit 1
fi
container_name=$1
database_name=$2
username=$3
# Check if the Docker container is running
if ! docker inspect -f '{{.State.Running}}' "$co... | magicoder | shell |
You are tasked with implementing a generic function that binds a custom executable to a root command in a Swift command-line application. The function should adhere to certain constraints and return a specific type.
Write a Swift function `bind` that takes a type parameter `RootCommand` representing the root command o... | ```swift
// Define the protocol conformances for ConfigFlagCustomizable and ExecutableEntryPoint
protocol ConfigFlagCustomizable { }
protocol ExecutableEntryPoint { }
// Define the InterpretedConfigExecutable class conforming to the given constraints
class InterpretedConfigExecutable<RootCommand, CustomExecutable>: Co... | magicoder | swift |
You are tasked with implementing a class that calculates the time taken to execute a given function. Your task is to create a `GetTime` class that implements the `IStatement` interface. The `IStatement` interface has a single method `execute` that takes a function as a parameter and returns the time taken to execute th... | ```typescript
export class GetTime implements IStatement {
execute(func: () => void): number {
const startTime = performance.now();
func();
const endTime = performance.now();
return endTime - startTime;
}
}
```
In the solution, the `GetTime` class implements the `IStatement` interface and provides ... | magicoder | typescript |
You are tasked with implementing a simplified rule adapter system for decision-making in a business application. The rule adapter system is responsible for converting a given rule into a decision based on certain conditions. Your task is to create a RuleAdapter class that can be used to adapt rules and make decisions b... | ```java
import java.util.function.BiConsumer;
// Define the Rule interface
interface Rule {
void getThen();
}
// Define the SampleRuleWithResult class
class SampleRuleWithResult {
// Define the rule implementation
}
// Define the RuleAdapter class
class RuleAdapter {
private Object result;
private Ru... | magicoder | java |
You are tasked with implementing a custom assertion function for testing a function called `XTRAM`. The `XTRAM` function takes multiple NumPy arrays as input and is expected to raise an `ExpressionError` if certain conditions are not met. Your task is to create the custom assertion function `assert_raises` that will te... | ```python
import numpy as np
class ExpressionError(Exception):
pass
def assert_raises(exception_type, function, *args):
try:
function(*args)
except exception_type:
return True
except Exception as e:
raise AssertionError(f"Expected {exception_type.__name__} but {type(e).__name__... | magicoder | python |
You are tasked with creating a program that simulates a simple banking system. The system should be able to handle basic banking operations such as account creation, deposit, withdrawal, and balance inquiry.
Your task is to implement a class `BankAccount` with the following specifications:
- The class should have a co... | ```python
class BankAccount:
def __init__(self, account_holder):
self._account_holder = account_holder
self._balance = 0
def deposit(self, amount):
self._balance += amount
def withdraw(self, amount):
if self._balance >= amount:
self._balance -= amount
el... | magicoder | python |
You are tasked with creating a function that generates a dropdown select component in React. The function should take in the following props:
- `options`: An array of strings representing the options for the dropdown select.
- `updateValue`: A function that updates the selected value in the parent component.
- `value`:... | ```jsx
import React from 'react';
interface SelectProps {
options: string[];
updateValue: (value: string) => void;
value: string;
index?: number;
}
const Select: React.SFC<SelectProps> = ({ options, updateValue, value, index }) => (
<select value={value} onChange={(e) => updateValue(e.target.value)}>
{o... | magicoder | jsx |
You are tasked with creating a notification scheduling system for a mobile application. The system should allow users to schedule notifications with custom content and time intervals. Your task is to implement a class that manages the scheduling of notifications based on user input.
You are provided with a Swift code ... | ```swift
import UserNotifications
class NotificationScheduler {
let notificationCenter = UNUserNotificationCenter.current()
func scheduleNotification(title: String, body: String, timeInterval: TimeInterval, identifier: String) {
let content = UNMutableNotificationContent()
content.title = titl... | magicoder | swift |
You are working on a System-on-Chip (SoC) design tool that allows users to connect different components and generate Verilog code for the design. The code snippet provided is a part of the tool's functionality. The `SoC` object represents the SoC design, and it has a method `connect` to establish connections between co... | ```python
class SoC:
def __init__(self):
self.connections = []
def connect(self, source, destination):
self.connections.append((source, destination))
def print_verilog(self, include_descendants=False):
verilog_code = "// Verilog code for the SoC design\n"
for source, destin... | magicoder | python |
You are tasked with implementing a Vector3Tween class in C# for a game development framework. The Vector3Tween class is responsible for interpolating between two Vector3 values over a specified duration using a specified easing function. Your task is to complete the implementation of the Vector3Tween class by providing... | ```csharp
public enum EasingEnum {
// Define easing types here
}
public class CUnit {
// Define CUnit class members here
}
public class Vector3 {
// Define Vector3 class members here
}
public class Tween<T> {
// Define base Tween class members here
}
public class Vector3Tween : Tween<Vector3> {
... | magicoder | csharp |
You are tasked with creating a Python function to compute accuracy metrics for a set of methods used to predict rankings. The function takes in the number of methods, gold preferences, predictions, and optional metrics, number of runs, and a specific run index. The function should compute accuracy metrics for each meth... | ```python
import numpy as np
from scipy.stats import kendalltau
import logging
def compute_metrics(nmethods, gold_prefs, predictions, metrics={}, nruns=1, r=0):
# Task C2, C4: Compute accuracy metrics
logging.info('Task C2/C4, accuracy metrics')
if not metrics:
metrics['acc'] = np.zeros((nmethods,... | magicoder | python |
You are tasked with implementing a function that calculates the standard deviation of a set of numbers. The standard deviation is a measure of the amount of variation or dispersion of a set of values. It is calculated as the square root of the average of the squared differences between each value and the mean of the se... | ```c
#include <stdio.h>
#include <math.h>
double average(double a, double b) {
return (a + b) / 2.0;
}
double standardDeviation(double* values, int size) {
double sum = 0.0;
double mean, variance, stddev = 0.0;
for (int i = 0; i < size; i++) {
sum += values[i];
}
mean = sum / size;
... | magicoder | c |
You are tasked with creating a program to compare two instances of a custom data structure representing a packet block. The packet block contains various properties such as BlockType, NameResolutionRecords, and Options. Your task is to implement a method that compares two instances of the packet block and asserts that ... | ```csharp
public class PacketBlock
{
public string BlockType { get; set; }
public List<string> NameResolutionRecords { get; set; }
public PacketBlockOptions Options { get; set; }
}
public class PacketBlockOptions
{
public string Comment { get; set; }
public string DnsName { get; set; }
}
public cl... | magicoder | csharp |
You are tasked with implementing a custom module loader for a JavaScript application. The module loader should be able to handle the export and import of modules using the CommonJS module system.
Your task is to create a function that takes a module name as input and returns the list of exported items from that module... | ```javascript
const fs = require('fs');
const path = require('path');
class NoSuchModuleError extends Error {
constructor(moduleName) {
super(`Module '${moduleName}' does not exist`);
this.name = 'NoSuchModuleError';
}
}
class NoSuchExportError extends Error {
constructor(moduleName) {
super(`Module... | magicoder | javascript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.