query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with implementing a Python class that manages different types of car audio systems. The class should be able to handle various audio configurations, such as mono left, mono right, mono rear, stereo left, and stereo right. Each configuration has specific functionalities and properties.
Your task is to cr... | ```python
class CarAudioSystem:
def __init__(self):
self.mono_left_volume = 0
self.mono_right_volume = 0
self.mono_rear_volume = 0
self.stereo_left_balance = 0
self.stereo_right_balance = 0
def set_mono_left_volume(self, volume):
self.mono_left_volume = volume
... | magicoder | python |
You are tasked with creating a messaging feature for a web application using Python and Flask. The provided code snippet is a part of a Flask application that handles sending messages between users. The `send_message` function is responsible for rendering a message sending form and processing the submitted message.
Yo... | ```python
from flask import Flask, render_template, request, redirect, url_for, flash
from flask_sqlalchemy import SQLAlchemy
from flask_login import login_required, current_user
from models import User, Message # Assuming the models are defined in a separate file
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE... | magicoder | python |
You are tasked with creating a Python class that interacts with a remote Sensory Cloud service to fetch information about supported video models. The provided code snippet is a method within the class that makes a gRPC call to the Sensory Cloud service to retrieve the supported video models. Your task is to complete th... | ```python
import video_pb2 # Assuming the video_pb2 module contains the necessary gRPC request and response message types
from typing import Any
class SensoryCloudClient:
def __init__(self, token_manager: Any, video_models_client: Any):
self._token_manager = token_manager
self._video_models_client... | magicoder | python |
You are working on a cryptographic signature verification system that involves various operations on elliptic curve points. One of the operations involves negating a generator point, multiplying points by scalars, adding points, and doubling a point. Your task is to implement a function to perform these operations usin... | ```rust
fn performOperations(
generator: Point,
h_star: Point,
s_bit: Point,
r: Point,
) -> Point {
let generator_negated = generator.negate(cs.namespace(||"generator negate"), self.params)?;
let mut sig = vk.mul(cs.namespace(||"hstar * vk"), &h_star, self.params)?;
let tmp = generator_negat... | magicoder | rust |
You are tasked with creating a program that simulates the motion of a projectile in a 2D space. The projectile is launched with an initial velocity and angle, and its trajectory is affected by gravity. Your task is to calculate the maximum height reached by the projectile and the total flight time.
You are given the f... | To solve this problem, we can use the given kinematic equations to calculate the maximum height and total flight time of the projectile.
```python
import math
# Given values
mv = 0.4480 # Initial velocity in arbitrary units
angle_degrees = 45 # Launch angle in degrees
g = 9.81 # Acceleration due to gravity in m/s^... | magicoder | python |
You are tasked with implementing a simple command pattern for controlling lights. The provided code snippet shows a `LightDimCommand` class that is used to create a command for dimming a light to a specific level. Your task is to extend this command pattern by creating a `LightOnCommand` class to turn on the light and ... | ```swift
// LightCommand.swift
protocol LightCommand {
func execute()
}
// Light.swift
class Light {
func turnOn() {
print("Light is on")
}
func turnOff() {
print("Light is off")
}
func dimToLevel(_ level: Int) {
print("Light is dimmed to level \(level)")
}... | magicoder | swift |
You are tasked with writing a Bash script to automate the creation of symbolic links for a set of configuration files. The script should take a single argument, which is the path to the directory where the configuration files are located. The script should then create symbolic links for specific files from the given di... | ```bash
#!/bin/bash
# Check if the argument is provided
if [ -z "$1" ]; then
echo "Usage: $0 <path_to_config_files_directory>"
exit 1
fi
config_dir="$1"
# Check if the directory exists
if [ ! -d "$config_dir" ]; then
echo "Error: Directory $config_dir does not exist."
exit 1
fi
# Create symbolic lin... | magicoder | shell |
You are given a list of tuples, each representing a rectangle in a 2D plane. Each tuple contains four integers representing the x and y coordinates of the bottom-left corner of the rectangle, followed by its width and height. Your task is to write a function that calculates the total area covered by all the rectangles ... | ```python
from typing import List, Tuple
def total_area(rectangles: List[Tuple[int, int, int, int]]) -> int:
if not rectangles:
return 0
x_coords = set()
y_coords = set()
for rect in rectangles:
x_coords.add(rect[0])
x_coords.add(rect[0] + rect[2])
y_coords.add(rect[1])... | magicoder | python |
You are tasked with creating a simple form validation function for a web application. The function should take in a form definition object and a data object, and validate whether the data object conforms to the rules specified in the form definition.
The form definition object is represented as an XML-like structure, ... | ```javascript
function validateForm(formDefinition, data) {
const inputs = formDefinition.form.input;
for (const input of inputs) {
const name = input.getAttribute('name');
const occurrences = input.occurrences;
const value = data[name];
if (occurrences) {
const min = parseInt(occurrences.get... | magicoder | javascript |
You are tasked with implementing a program 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 program should include the following features:
- The game should start in a spec... | ```python
class Room:
def __init__(self, name, description, obstacles=None, rewards=None, directions=None):
self.name = name
self.description = description
self.obstacles = obstacles if obstacles else "No obstacles"
self.rewards = rewards if rewards else "No rewards"
self.dir... | magicoder | python |
You are tasked with creating a Python class method that retrieves historical daily close prices for a given date from a data handler. The method should take into account a universe of assets and any additional keyword arguments.
You are provided with the following code snippet as a reference:
```python
def _get_univer... | ```python
import pandas as pd
class YourClass:
def __init__(self, data_handler, universe):
self.data_handler = data_handler
self.universe = universe
def _get_universe_historical_daily_close_df(self, dt, **kwargs) -> pd.DataFrame:
assets = self.universe.get_assets(dt)
historical... | magicoder | python |
You are tasked with implementing a function to determine the type of a given grid. The grid is represented as a 2D array of integers, where each integer represents the height of the corresponding cell. The grid type is defined as follows:
- If all the cells have the same height, the grid is of type "flat".
- If the hei... | ```java
public class GridTypeDeterminer {
public static String determineGridType(int[][] grid) {
boolean flat = true, ascending = true, descending = true;
int prevRowSum = 0;
for (int i = 0; i < grid.length; i++) {
int rowSum = 0;
for (int j = 0; j < grid[i].... | magicoder | java |
You are tasked with creating a Python class that simulates a simple messaging system using Google Protocol Buffers. Your task is to implement the `MessageSystem` class with the following functionalities:
1. `add_message_type(message_type, fields)`: A method to add a new message type to the system. `message_type` is a ... | ```python
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf.descriptor import FieldDescriptor
class MessageSystem:
def __init__(self):
self.message_types = {}
def add_message_type(self, message_type, fields):
self.message... | magicoder | python |
You are working as a DevOps engineer for a company that uses Docker for containerization. Your team is responsible for building and pushing Docker images to a container registry as part of the CI/CD pipeline. You have been given a code snippet that is used to build and push a Docker image for the Calico documentation. ... | ```bash
#!/bin/bash
# Check if the documentation version is provided as an argument
if [ -z "$1" ]; then
echo "Usage: $0 <documentation_version>"
exit 1
fi
documentation_version=$1
calico_io_image="docker.io/wenba100xie/calico-docs:$documentation_version"
# Build the Docker image using the provided Dockerfile
do... | magicoder | shell |
You are tasked with implementing a Python function that adds two positive integers without using the '+' operator. Instead, you should utilize bitwise operations to achieve the addition.
Your task is to create a function `add_without_plus(num1, num2)` that takes in two positive integers `num1` and `num2` as input and ... | ```python
def add_without_plus(num1, num2):
while num2 != 0:
carry = num1 & num2
num1 = num1 ^ num2
num2 = carry << 1
return num1
# Test the function
num1 = 4
num2 = 34
result = add_without_plus(num1, num2)
print(result) # Output: 38
```
The `add_without_plus` function uses bitwise op... | magicoder | python |
You are tasked with implementing a Python function that processes data from CSV files and concatenates the content into a single output. The function should handle encoding, delimiter, and frame retrieval based on user input.
You are given the following code snippet as a starting point:
```python
print(str(e))
encodi... | ```python
from typing import List
def process_csv_files(csv_files: List[str], encoding: str, delimiter: str) -> None:
try:
print(str(e))
encoding, delimiter = ask_details()
frames = get_frames(csv_files, encoding, delimiter)
concat_output(frames)
except Exception as e:
p... | magicoder | python |
You are tasked with creating a Python function to manage the power consumption of smart plugs in a household. The smart plugs are connected to various devices and can be controlled remotely. The `tplink_smartplug_py3` library provides the necessary functionality to interact with these smart plugs. The library includes ... | ```python
import tplink_smartplug_py3 as plug
def manage_smart_plug(ip_address: str, state: bool) -> str:
if state:
plug.control(ip_address, 'on')
return f"Smart plug at {ip_address} turned on"
else:
plug.control(ip_address, 'off')
return f"Smart plug at {ip_address} turned off"... | magicoder | python |
You are working on a computer vision project and need to implement a data batching process for a neural network. The given code snippet is part of the data batching process, where input data is organized into batches for evaluation. The code initializes variables and arrays for batching and processing the input data.
... | ```python
import numpy as np
def populate_batches(i, batch_size_eval, num_valid, mask_length, img_channels, H_crop, W_crop, input_data):
instance_init = i * batch_size_eval
instance_end = min((i + 1) * batch_size_eval, num_valid)
instance_num = instance_end - instance_init
y_batch = [] # List to ... | magicoder | python |
You are tasked with simulating a simple programming language that includes the ability to execute instructions and handle control flow using GOTO and GOSUB commands. The language operates on a set of instructions and maintains a stack of line numbers for GOTO and GOSUB commands. Your task is to implement a program that... | ```cpp
#include <iostream>
#include <queue>
#include <stack>
#include <string>
int main() {
std::queue<std::string> instructions;
std::stack<int> lineJumps;
std::string instruction;
int lineNumber = 10;
while (std::cin >> instruction) {
instructions.push(instruction);
if (instruct... | magicoder | cpp |
You are given a data structure representing a matrix as a linked list of cells. Each cell contains an integer value and a pointer to the cell on its right. The matrix is represented as a linked list of rows, where each row is represented by a linked list of cells. The matrixSum function is intended to calculate the sum... | ```c
int matrixSum(Cell const* M, int n) {
int sum = 0;
const Cell* currentRow = M;
// Iterate through each row
for (int i = 0; i < n; ++i) {
const Cell* currentCell = currentRow;
// Iterate through each cell in the row
while (currentCell) {
sum += currentCell->value;
currentCell = cur... | magicoder | c |
You are tasked with creating a Python script that simulates a simple browser pool management system. The system should be able to handle requests for opening and closing browser instances, and it should maintain a pool of available browsers for efficient usage.
Your task is to implement a class `BrowserPool` with the ... | ```python
import threading
import time
class BrowserPool:
def __init__(self, max_browsers):
self.max_browsers = max_browsers
self.available_browsers = list(range(max_browsers))
self.lock = threading.Lock()
def open_browser(self):
while True:
with self.lock:
... | magicoder | python |
You are tasked with implementing a Python class method that performs a specific operation on a Git repository. Your task is to complete the implementation of the method `search_commits` in the `GitRepository` class. The method should search for commits in the repository starting from a given SHA hash and return a list ... | ```python
import git
class GitRepository:
def __init__(self, tempdir):
self.tempdir = tempdir
self.repo = git.Repo(tempdir)
def search_commits(self, since_sha=None):
"""
Search for commits in the repository starting from a given SHA hash.
Args:
since_sha - ... | magicoder | python |
You are given a list of integers representing the coefficients of a polynomial. Your task is to write a Python function that calculates the greatest common divisor (GCD) of the coefficients using the `math` module and returns the result.
The function signature is:
```python
def find_poly_gcd(coefficients):
# Your ... | ```python
import math
def find_poly_gcd(coefficients):
return math.gcd(*coefficients)
```
The `find_poly_gcd` function takes a list of coefficients as input and uses the `math.gcd` function to calculate the GCD of all the coefficients. The `*coefficients` syntax unpacks the list and passes its elements as separat... | magicoder | python |
You are tasked with implementing a method to calculate the average waiting time for a set of processes in a multi-programming operating system. The average waiting time is defined as the total time a process spends waiting in the ready queue before getting executed, divided by the total number of processes.
You are gi... | ```java
public class AverageWaitingTimeCalculator {
public double calculateAverageWaitingTime(int[] burstTimes) {
int n = burstTimes.length;
int waitingTime = 0;
int totalWaitingTime = 0;
for (int i = 0; i < n; i++) {
totalWaitingTime += waitingTime;
waitingT... | magicoder | java |
You are tasked with creating a program that can analyze a given ASCII art representation of a logo and extract specific information from it. The ASCII art represents a logo, and the goal is to extract the name of the company from the logo.
The ASCII art is represented as a series of lines, where each line contains cha... | ```python
import re
def extract_company_name(logo):
matches = re.findall(r'\|(.+?)\|', logo)
if matches:
return matches[0].strip()
else:
return "Company name not found"
```
The `extract_company_name` function uses the `re.findall` method to search for all occurrences of text enclosed withi... | magicoder | python |
You are tasked with creating a script to automate the reinitialization of containers in an AWS environment. The script should use the AWS CLI to invoke a Lambda function with specific parameters. Your task is to write a Bash script that accomplishes this task.
Your script should perform the following steps:
1. Check i... | ```bash
#!/bin/bash
local="0" # Example value for the variable local
stack_name="example-stack" # Example value for the stack name
aws_profile="example-profile" # Example value for the AWS profile
if [ "$local" == "0" ]; then
temp_file=$(mktemp)
eval aws lambda invoke \
--invocation-type RequestResponse \
... | magicoder | shell |
You are tasked with simulating a simple multi-agent system to model the interaction between agents and their environment. The agents move within a 2D environment and interact with it based on certain rules. Your goal is to implement the movement and interaction logic for the agents within the environment.
You are give... | ```python
import csv
import random
class Agent:
def __init__(self, x, y):
self.x = x
self.y = y
def move(self):
self.x += random.choice([-1, 0, 1])
self.y += random.choice([-1, 0, 1])
class Environment:
def __init__(self, data):
self.data = data
def interact_w... | magicoder | python |
You are tasked with creating a program that converts a given decimal number to its octal representation. The program should take an integer input and output its octal equivalent.
Your task is to implement the function `decimal_to_octal` that takes an integer `n` as input and returns a string representing the octal equ... | ```python
def decimal_to_octal(n):
if n == 0:
return '0'
octal_digits = []
while n > 0:
remainder = n % 8
octal_digits.append(str(remainder))
n = n // 8
octal_digits.reverse()
return ''.join(octal_digits)
```
The `decimal_to_octal` function first checks if the input ... | magicoder | python |
You are tasked with implementing a custom gated recurrent neural network (GRU) cell in TensorFlow for a natural language processing task. The GRU cell will incorporate a Simple Recurrent Neural Network (SCRN) architecture, which involves the use of specific parameters and operations.
The code snippet provided outlines... | ```python
import tensorflow as tf
class SCRNCell:
def __init__(self, vocabulary_size, c_size, h_size):
self._vocabulary_size = vocabulary_size
self._c_size = c_size
self._h_size = h_size
self._U = None # Define the missing parameter initialization for the 'U' matrix
def __call... | magicoder | python |
You are tasked with creating a Python function that processes a YAML file containing experiment configurations. The function should load the YAML file, parse its contents, and return a specific value based on the experiment ID provided in the file.
You are provided with a code snippet that demonstrates the creation of... | ```python
import yaml
def load_workspace(file_path):
with open(file_path, 'r') as file:
data = yaml.safe_load(file)
experiment_id = data.get('experiments', {}).get('chaosiq', {}).get('test', {}).get('dummy.json', {}).get('experiment_id', None)
return experiment_id
```
The `load_workspace` f... | magicoder | python |
You are tasked with creating a Python script that processes a given text file and extracts specific information from it. The text file contains data related to university publications, and the goal is to extract the author's name and the year of publication for each entry. The text file follows a specific format where ... | ```python
def extract_publication_info(file_path):
try:
with open(file_path, 'r') as file:
content = file.read()
entries = content.split('-- ')[1:] # Split the content into individual entries
publication_info = []
for entry in entries:
autho... | magicoder | python |
You are tasked with creating a Python function that checks the distribution of random numbers generated by a given distribution function. The function should take four parameters: `dist_func`, `loc_dtype`, `scale_dtype`, and `dtype`. The `dist_func` parameter represents the distribution function to be tested, while `lo... | ```python
import numpy as np
def check_distribution(dist_func, loc_dtype, scale_dtype, dtype, loc_shape, scale_shape, shape):
loc = np.ones(loc_shape, dtype=loc_dtype)
scale = np.ones(scale_shape, dtype=scale_dtype)
out = dist_func(loc, scale, shape, dtype)
assert shape == out.shape
assert out.dtyp... | magicoder | python |
You are tasked with implementing a function to calculate the cross product of two 3D vectors. The cross product of two vectors, denoted as A × B, results in a vector that is perpendicular to both A and B. The magnitude of the resulting vector is given by the product of the magnitudes of A and B multiplied by the sine o... | ```python
def cross_product(v1, v2, result):
# Calculate the cross product of v1 and v2
cross_result = [v1[1]*v2[2] - v1[2]*v2[1],
v1[2]*v2[0] - v1[0]*v2[2],
v1[0]*v2[1] - v1[1]*v2[0]]
# Compare the calculated cross product with the expected result
return cro... | magicoder | python |
You are tasked with implementing a command-line interface for a version control system. The system supports various commands, each represented by a string in the form "module/action". For example, "config/replace" represents the "replace" action in the "config" module.
Your task is to write a function that takes a lis... | ```python
from typing import List, Dict
def countCommands(commands: List[str]) -> Dict[str, int]:
command_counts = {}
for command in commands:
if command in command_counts:
command_counts[command] += 1
else:
command_counts[command] = 1
return command_counts
# Test t... | magicoder | python |
You are tasked with creating a Python program that evaluates a given mathematical expression and returns the result. The program should handle basic arithmetic operations such as addition, subtraction, multiplication, and division. Additionally, it should also support parentheses for altering the order of operations.
... | ```python
# Prompt the user to input a mathematical expression
expression = input("Enter a mathematical expression: ")
# Evaluate the expression using the eval() function
result = eval(expression)
# Output the result of the evaluated expression
print("Result:", result)
```
The solution utilizes the `input()` functio... | magicoder | python |
You are working on a machine learning project and need to implement a custom loss function for a neural network model. The model has a method that returns a dictionary containing the logits and the predicted classes for a given input. Your task is to implement the loss function that computes scalar loss tensors with re... | ```python
def loss(self, prediction_dict, groundtruth_lists):
"""Compute scalar loss tensors with respect to provided groundtruth.
Args:
prediction_dict: A dictionary holding prediction tensors.
groundtruth_lists: A dict of tensors holding groundtruth
information, with one entry for... | magicoder | python |
You are tasked with implementing a class that represents a complex number and provides methods to perform arithmetic operations on complex numbers. 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 pa... | ```java
public class ComplexNumber {
private double real;
private double imaginary;
public ComplexNumber(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
}
public ComplexNumber add(ComplexNumber other) {
return new ComplexNumber(this.real + oth... | magicoder | java |
You are given a series of code snippets that represent a data retrieval process. The code snippets contain a mix of commands and data, and your task is to interpret the commands and extract the relevant information from the data.
The data is structured as a list of `typeguid` values, each represented as a 32-character... | ```python
def process_code_snippets(code_snippets):
results = []
for snippet in code_snippets:
conditions = snippet.split("read id=")[1:]
for condition in conditions:
condition = condition.strip()
condition_parts = condition.split("(")
condition_type = conditi... | magicoder | python |
You are tasked with implementing a Python class to handle email messages. Your class should include methods to extend headers, check if the message is multipart, and create a single body for non-multipart messages. You are provided with a code snippet that partially implements this functionality. Your task is to comple... | ```python
class EmailMessage:
def __init__(self):
self.headers = []
def extend_headers(self, headers):
self.headers.extend(headers)
def is_multipart(self, message):
# Implement logic to check if the message is multipart
return message.is_multipart()
def create_single_b... | magicoder | python |
You are tasked with implementing a function that determines the screen size of a mobile device based on its height and scale factor. The function should take two parameters: `height` (an integer representing the height of the device's screen in points) and `scale` (a floating-point number representing the scale factor ... | ```swift
enum ScreenSize {
case inch3p5
case inch4
case inch4p7
case inch5p5
}
func getScreenSize(height: Int, scale: Float) -> ScreenSize {
switch height {
case 240, 480: return .inch3p5
case 568: return .inch4
case 667: return scale == 3.0 ? .inch5p5 : .inch4p7
case 736: return .i... | magicoder | swift |
You are tasked with implementing a class that manages a list of chores and their execution. The class should allow adding new chores, executing them, and retrieving the execution object for a specific chore. The execution object should contain information about the chore and its execution status.
Your task is to imple... | ```php
class Chore {
public $id;
public $name;
public $description;
public $executed;
public function __construct($id, $name, $description) {
$this->id = $id;
$this->name = $name;
$this->description = $description;
$this->executed = false;
}
}
class ExecutionObj... | magicoder | php |
You are working on a navigation system for a spacecraft, and you need to implement a Kalman filter to estimate the spacecraft's angular velocity. The spacecraft has sensors that measure its angular velocity, but these measurements are noisy and need to be filtered to obtain a more accurate estimate. You decide to use a... | ```python
import numpy as np
class KalmanFilter:
def __init__(self):
self.correctedOmega = np.array([0, 0, 0], dtype=np.float64)
self.measuredOmega = np.array([0, 0, 0], dtype=np.float64)
self.predictedOmegaError = np.array([0, 0, 0], dtype=np.float64)
self.stateTransitionMatrix = n... | magicoder | python |
You are tasked with creating a Python program to manage and retrieve quotes in a group chat. The program should allow users to save quotes by replying to a message with `#quote` and recall saved quotes by using `#recall`. The program should also display the number of quotes saved for the group.
Your task is to impleme... | ```python
import random
class QuoteManager:
def __init__(self):
self.quotes = {}
def add_quote(self, chat_id, message_id):
if chat_id in self.quotes:
self.quotes[chat_id].append(message_id)
else:
self.quotes[chat_id] = [message_id]
def get_quote_count(self,... | magicoder | python |
You are tasked with implementing a data validation system for a Python application. The system should be able to handle various types of input data and validate them based on predefined rules. The code snippet provided contains a series of test cases for the data validation system, along with the expected exceptions th... | ```python
import ipaddress
import urllib.parse
import uuid
class InputDataNotConvertibleExc(Exception):
pass
class InputDataTypeNotInAllowlistExc(Exception):
pass
class IntegerBlueprint:
def __init__(self, parsing_mode):
self.parsing_mode = parsing_mode
def validate(self, data):
if s... | magicoder | python |
You are tasked with implementing a function that calculates the factorial of a given non-negative integer using recursion. The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. For example, the factorial of 5 (denoted as 5!) is calculated as 5 * 4 * 3 * 2 * 1, which ... | ```rust
fn factorial(n: u64) -> u64 {
if n == 0 || n == 1 {
1
} else {
n * factorial(n - 1)
}
}
fn main() {
// Test the factorial function
println!("Factorial of 5: {}", factorial(5)); // Output: 120
println!("Factorial of 0: {}", factorial(0)); // Output: 1
println!("Factor... | magicoder | rust |
You are tasked with implementing a simple graphics library for drawing basic shapes on a 2D canvas. The library should support drawing circles, rectangles, and triangles. To achieve this, you need to define the necessary constants and functions for the library.
Given the provided code snippet, you are required to comp... | ```c
#include <stdio.h>
#define WND_WIDTH 1000
#define WND_HEIGHT 1000
#define PI 3.1415826535897932384626
void drawCircle(int x, int y, int radius) {
// Implementation for drawing a circle
printf("Drawing circle at (%d, %d) with radius %d\n", x, y, radius);
}
void drawRectangle(int x, int y, int width, int ... | magicoder | c |
You are tasked with implementing a function to calculate the Cartesian product of two given graphs. The Cartesian product of two graphs G1 and G2, denoted as G1 × G2, is a graph such that the set of vertices of G1 × G2 is the Cartesian product of the vertex sets of G1 and G2, and two vertices (u1, v1) and (u2, v2) are ... | ```python
import networkx as nx
def cartesian_product_graph(G1, G2):
cartesian_product = nx.Graph()
for u1 in G1.nodes():
for u2 in G2.nodes():
for v1 in G1.nodes():
for v2 in G2.nodes():
if (u1, v1) in G1.edges() and (u2, v2) in G2.edges():
... | magicoder | python |
You are tasked with implementing a file system utility module in TypeScript. The module should provide various file system operations and authentication mechanisms. The code snippet provided includes an import statement for a file system utility module and enables 'Digest' authentication by importing the 'AuthDigest' m... | ```typescript
// AuthDigest.ts
export class AuthDigest {
static enableDigestAuthentication() {
// Implementation for enabling 'Digest' authentication
console.log("Digest authentication enabled");
}
}
// fsUtil.ts
export class FileSystemUtility {
static readFile(filePath: string): string {
// Implemen... | magicoder | typescript |
You are tasked with implementing a Python class that represents a unit converter. The class should be able to convert values between different units for various physical quantities such as area, density, distance, energy, length, mass, power, and speed. The conversion rates between units for each physical quantity are ... | ```python
class UnitConverter:
def __init__(self):
self.conversion_rates = {
'AREA': {('m^2', 'ft^2'): 10.7639, ('ft^2', 'm^2'): 0.092903},
'DENSITY': {('kg/m^3', 'lb/ft^3'): 0.06242796, ('lb/ft^3', 'kg/m^3'): 16.0185},
'DISTANCE': {('m', 'ft'): 3.28084, ('ft', 'm'): 0.30... | magicoder | python |
You are tasked with writing a function to convert a CIDR (Classless Inter-Domain Routing) notation IP address to its corresponding range of IP addresses. The CIDR notation consists of an IP address followed by a forward slash and a number representing the network prefix length. For example, "192.168.1.0/24" represents ... | ```python
import ipaddress
def cidr_to_ip_range(cidr):
ip_network = ipaddress.ip_network(cidr, strict=False)
ip_range = [str(ip) for ip in ip_network.hosts()]
return ip_range
# Test the function
cidr = "192.168.1.0/24"
print(cidr_to_ip_range(cidr)) # Output: ["192.168.1.1", "192.168.1.2", ..., "192.168.1... | magicoder | python |
You are tasked with implementing a resource management system for a game engine. The system should handle the loading and retrieval of texture resources. The provided code snippet is a part of the resource management logic and involves searching for an existing texture resource and importing it if it doesn't exist.
Yo... | ```cpp
class ResourceTexture {
public:
int ID;
// Other texture resource properties and methods
};
class Resource {
public:
enum class ResType { Texture, /* Other resource types */ };
};
class SceneImporter {
public:
// Other scene importer methods and properties
ResourceTexture* TextureImport(/* ... | magicoder | cpp |
You are tasked with implementing a function to convert a given byte array into a hexadecimal string representation. The function should take a byte array as input and return the hexadecimal string formed by concatenating the hexadecimal representations of individual bytes in the array.
Write a function `ConvertToHex` ... | ```csharp
public class ByteArrayConverter
{
public string ConvertToHex(byte[] inputBytes)
{
string hexString = BitConverter.ToString(inputBytes).Replace("-", "").ToLower();
return hexString;
}
}
```
The `ConvertToHex` function takes a byte array `inputBytes` as input and uses `BitConverter.T... | magicoder | csharp |
You are tasked with implementing a simple cache system in C#. The cache should store results based on the assembly path as the key. You need to create a class that allows adding results to the cache and removing results from the cache based on the assembly path.
You are given a partial code snippet for a cache class w... | ```csharp
using System;
using System.Collections.Generic;
public class AssemblyCache
{
private Dictionary<string, object> cache;
public AssemblyCache()
{
cache = new Dictionary<string, object>();
}
public void AddResult(string assemblyPath, object result)
{
if (string.IsNullOr... | magicoder | csharp |
You are tasked with implementing a function that retrieves invite metadata using a provided invite code. The function should make an asynchronous call to a REST API endpoint and return the metadata for the invite if it exists, or throw an error if the invite does not exist. You are given a code snippet that demonstrate... | ```typescript
import { endpoints } from "../../util/constants.ts";
import { snakelize } from "../../util/utils.ts";
/** Returns an invite for the given code or throws an error if the invite doesn't exist. */
export async function getInvite(inviteCode: string, options?: GetInvite): Promise<InviteMetadata> {
try {
... | magicoder | typescript |
You are tasked with creating a Python package that provides functionality for matching words that can be confused for each other but contain different characters. To achieve this, you need to implement a class called `ConfusablesMatcher` with the following methods:
1. `__init__(self, word_list: List[str])`: A construc... | ```python
from typing import List
import setuptools
class ConfusablesMatcher:
def __init__(self, word_list: List[str]):
self.word_list = [word.lower() for word in word_list]
def match_word(self, input_word: str) -> List[str]:
input_word = input_word.lower()
matching_words = []
... | magicoder | python |
You are tasked with implementing a simple virtual machine (VM) that can execute basic arithmetic operations. The VM is capable of calling functions and performing operations on custom data types. Your goal is to create a function that adds two integers and returns the result.
You are provided with a code snippet that ... | ```javascript
// Define a simple virtual machine (VM) class
class VirtualMachine {
callFunction(funcName, ...args) {
// For simplicity, assume that the function name and arguments are valid
if (funcName === "add") {
return this.add(...args);
}
}
// Implement the "add" function within the VM
a... | magicoder | javascript |
You are tasked with implementing a function to update a quota set by removing specific items from the quota set properties and required fields. The quota set is represented as a nested dictionary, and the items to be removed are specified in the `remove_item_list`. Your task is to write a function that takes the origin... | ```python
import copy
def update_quota_set(original_quota_set: dict, remove_item_list: list) -> dict:
update_quota_set = copy.deepcopy(original_quota_set)
quota_properties = update_quota_set['response_body']['properties']['quota_set']['properties']
quota_required = update_quota_set['response_body']['proper... | magicoder | python |
You are tasked with analyzing and understanding the behavior of the given Python code snippet, which involves asynchronous programming using asyncio and sync_to_async decorator. Your goal is to explain the execution flow and the expected behavior of the code.
The code snippet includes a function `slow_function` decora... | 1. The `sync_to_async` decorator is used to convert a synchronous function (`slow_function`) into an asynchronous one. When the `slow_function` is called within an asynchronous context, it will be executed in a separate thread to prevent blocking the event loop. This allows the asynchronous code to continue running whi... | magicoder | python |
You are working for a software company that is developing a new application which requires a MongoDB database. As part of the development process, you need to set up a MongoDB instance using Docker. The company has provided you with the following command to run a MongoDB container:
```
docker run --name mongobarder -p... | The provided command `docker run --name mongobarder -p 27018:27018 -d -t mongo` is used to run a MongoDB container with specific configurations. Let's break down the components of the command:
- `docker run`: This is the command to run a new container.
- `--name mongobarder`: This option specifies the name of the cont... | magicoder | python |
You are tasked with creating a Rust library for managing peripheral instances for different STM32 microcontroller devices. The library should provide a modular structure to support multiple device variants and their respective peripherals. Each device variant will have its own module containing the peripheral instances... | ```rust
// Define the macro to generate peripheral instances based on the device variant
macro_rules! generate_peripheral_instances {
($variant:ident, $peripheral1:ident, $peripheral2:ident, $peripheral3:ident) => {
#[cfg(feature = $variant)]
pub mod $variant {
pub struct $peripheral1;
... | magicoder | rust |
You are given a list of integers `data`. Your task is to write a function that finds the median of the list. The median is the middle value in a sorted list of numbers. If the list has an odd number of elements, the median is the middle element. If the list has an even number of elements, the median is the average of t... | ```python
def find_median(data):
data.sort()
length = len(data)
if length % 2 == 1:
return data[length // 2]
else:
mid1 = data[length // 2 - 1]
mid2 = data[length // 2]
return (mid1 + mid2) / 2
```
The `find_median` function first sorts the input list `data`. Then, it ch... | magicoder | python |
You are tasked with implementing a program 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. Each room will have specific descriptions and possible actions that the player can tak... | ```python
class Room:
def __init__(self, name, description):
self.name = name
self.description = description
self.exits = {}
self.obstacle = None
def add_exit(self, direction, room):
self.exits[direction] = room
def set_obstacle(self, obstacle):
self.obstacl... | magicoder | python |
You are tasked with implementing a genetic algorithm mutation operator for a given genome represented as a sequence of elements. The mutation operator, called `SwapOrderMutator`, is responsible for swapping the positions of two elements within the genome with a certain probability defined by the `mutation_rate`. The mu... | ```rust
use rand::prelude::*;
#[allow(missing_copy_implementations)]
#[derive(Clone, Debug, PartialEq)]
pub struct SwapOrderMutator {
mutation_rate: f64,
}
impl SwapOrderMutator {
pub fn new(mutation_rate: f64) -> Self {
Self { mutation_rate }
}
pub fn mutate<T>(&self, genome: &mut Vec<T>, rn... | magicoder | rust |
You are tasked with implementing a state machine for a simple tic-tac-toe game. The state machine has a set of states and corresponding transitions triggered by events. The provided code snippet is a part of the state transition logic for the tic-tac-toe game. The state machine is implemented using Swift and utilizes a... | ```swift
enum GameStateEvent {
case letsPlayButtonTapped
case gameDismissed
case game
}
struct GameState {
var oPlayerName: String?
var xPlayerName: String?
// Other game state properties
mutating func handleEvent(_ event: GameStateEvent) {
switch event {
case .letsPlayButt... | magicoder | swift |
You are tasked with implementing a function to convert a given string from UTF-16 encoding to UTF-8 encoding. UTF-16 and UTF-8 are character encoding formats used to represent text in computing. In UTF-16, each character is represented by one or two 16-bit code units, while in UTF-8, each character is represented by on... | ```swift
func utf16ToUtf8(_ utf16String: String) -> String {
var utf8String = ""
var utf16Iterator = utf16String.utf16.makeIterator()
while let utf16Value = utf16Iterator.next() {
if utf16Value < 0x80 {
utf8String.append(Character(UnicodeScalar(utf16Value)!))
} else if utf16... | magicoder | swift |
You are tasked with implementing a file management system for a blackout simulation game called "Blackoutpedia." The game requires the creation of temporary files and directories, as well as handling various events related to map loading and faults. Your task is to design a class that encapsulates the necessary functio... | ```java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class BlackoutpediaFileManager {
private Path destinationFile;
private Path storeDirectory;
public BlackoutpediaFileManager() throws IOException {
destinationFile = Files.c... | magicoder | java |
You are given a binary tree represented by its root node `root`, an integer `v`, and an integer `d`. Your task is to add a row of nodes with value `v` at the given depth `d` in the binary tree. The added nodes should have their original child nodes shifted to the right.
You need to implement the function `addOneRow` t... | ```java
public TreeNode addOneRow(TreeNode root, int v, int d) {
if (d == 1) {
TreeNode newRoot = new TreeNode(v);
newRoot.left = root;
return newRoot;
} else if (root != null && d > 1) {
if (d == 2) {
TreeNode newLeft = new TreeNode(v);
TreeNode newRight ... | magicoder | java |
You are given a Python code snippet that manipulates a bytearray `block` using two functions `w_get` and `w_set`. The `w_get` function fetches a big-endian 32-bit unsigned integer at a given index in the `block`, while the `w_set` function sets a big-endian 32-bit unsigned integer at a given index in the `block` to a s... | ```python
import struct
def reverse_block(block: bytearray) -> None:
# Calculate the number of 32-bit unsigned integers in the block
num_integers = len(block) // 4
# Iterate through half of the block and swap the integers
for i in range(num_integers // 2):
# Fetch the integers from both ends o... | magicoder | python |
You are tasked with implementing a function that calculates the sum of all even Fibonacci numbers up to a given limit. The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. For example, the first few numbers in the Fibonacci sequence are ... | ```python
def even_fibonacci_sum(limit):
a, b = 0, 1
total_sum = 0
while b <= limit:
if b % 2 == 0:
total_sum += b
a, b = b, a + b
return total_sum
```
The `even_fibonacci_sum` function initializes variables `a` and `b` to 0 and 1, respectively. It then iterates through the ... | magicoder | python |
You are tasked with implementing a function `pattern_nineteen(n)` that takes an integer `n` as input and prints a specific pattern based on the value of `n`. The pattern consists of a series of numbers and asterisks arranged in a specific manner. The function should handle invalid input by raising a `ValueError` with a... | ```python
def pattern_nineteen(n):
if not isinstance(n, int) or n <= 0:
raise ValueError('Input should be a positive integer')
for i in range(1, n + 1):
row = ' '.join(str(j) for j in range(1, i + 1)) + ' *' * (n - i)
print(row)
```
The `pattern_nineteen` function first checks if the i... | magicoder | python |
You are tasked with creating a Python function that parses and evaluates a complex mathematical expression using the provided `qtoggleserver` library. The expression will involve variables and arithmetic operations, and the function should return the result of the evaluated expression.
You are given a code snippet tha... | ```python
from qtoggleserver.core.expressions import EmptyExpression, parse_expression
async def parse_and_evaluate_expression(expression, num_mock_port1, num_mock_port2):
num_mock_port1.set_last_read_value(5)
num_mock_port2.set_last_read_value(-4)
context = {
'num_mock_port1': num_mock_port1,
... | magicoder | python |
You are tasked with implementing a Python class that reads lines from multiple files matching a specified glob pattern. Your task is to complete the implementation of the `MultiTail` class, which is responsible for tailing files and yielding lines from them.
The `MultiTail` class has the following attributes and metho... | ```python
import multitail2
class MultiTail:
def __init__(self, spoolglob, progresses=None, shutdown=None):
self.progresses = progresses or {}
self.shutdown_e = shutdown
self.data_reader = multitail2.MultiTail(spoolglob,
skip_to_end=False,
... | magicoder | python |
You are working on a machine learning project and need to preprocess a dataset before feeding it into your model. The dataset consists of two types of input data: XD and XD_STRU, both of which are initially returned as lists by the `parse_data` function. Your task is to convert these lists into NumPy arrays for further... | ```python
import numpy as np
def preprocess_data(XD, XD_STRU, FLAGS):
# Convert lists to NumPy arrays
XD = np.asarray(XD)
XD_STRU = np.asarray(XD_STRU)
# Perform any necessary preprocessing steps
# For example, normalization, feature scaling, or data cleaning
# Additional processing or transf... | magicoder | python |
You are tasked with implementing a function that parses a given object and extracts specific properties from it. The object will contain properties related to a hardware device, and your function should extract and return these properties based on certain criteria.
You are given an object `matches` with the following ... | ```javascript
function extractProperties(matches) {
const extractedProperties = [
matches?.instance || null,
matches?.id || null,
matches?.param0 || null,
matches?.param1 || null,
matches?.param2 || null
];
return extractedProperties;
}
``` | magicoder | javascript |
You are tasked with implementing a custom testing framework for unit testing in Java. Your framework should support the execution of test cases and provide hooks for setup and teardown operations. Specifically, you need to implement the `TestRunner` class that will execute test methods annotated with `@Test` and handle... | ```java
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class TestRunner {
public void run(Class<?> testClass) {
Method[] methods = testClass.getDeclaredMethods();
Object testInstance = null;
for (Method method : methods) {
if (method... | magicoder | java |
You are tasked with creating a program that generates a factory container for Business Logic Layer (BLL) classes in a domain-driven design framework. The program should utilize the provided code snippet as a starting point and extend it to generate a factory container for BLL classes based on a given configuration.
Yo... | ```csharp
using Framework.DomainDriven.Generation;
using Framework.DomainDriven.Generation.Domain;
namespace Framework.DomainDriven.BLLGenerator
{
public class BLLFactoryContainerGeneratorConfiguration<TConfiguration> : GeneratorConfigurationContainer<TConfiguration>, IBLLFactoryContainerGeneratorConfiguration
... | magicoder | csharp |
You are working on a data processing task involving reshaping and scaling arrays. Given a 1D array `tbs` and a 1D array `tas`, your task is to write a function to reshape these arrays into 3D arrays and then scale the values by dividing by 100.0. The reshaping should be such that each array is split into multiple 2D ar... | ```python
import numpy as np
def process_arrays(tbs, tas):
tbs_3d = np.array(tbs).reshape(len(tbs) // 100, 5, 20) / 100.0
tas_3d = np.array(tas).reshape(len(tas) // 100, 5, 20) / 100.0
return tbs_3d, tas_3d
``` | magicoder | python |
You are tasked with implementing a class that manages the persistence of AffinityGroup entities in a database. The provided code snippet shows two methods, `save` and `update`, which are responsible for inserting and updating AffinityGroup entities, respectively.
Your task is to create a Java class, `AffinityGroupMana... | ```java
public class AffinityGroupManager {
private CallsHandler callsHandler;
public AffinityGroupManager(CallsHandler callsHandler) {
this.callsHandler = callsHandler;
}
public void save(AffinityGroup entity) {
callsHandler.executeModification("InsertAffinityGroupWithMembers", create... | magicoder | java |
You are tasked with implementing a 3D geometry library in C++. The library should support operations such as creating 3D vectors, extruding faces, and preventing regression of certain geometric entities. Your task is to implement the `gmod` namespace with the following functionalities:
1. Define a `Vector` class templ... | ```cpp
#include <iostream>
#include <vector>
namespace gmod {
template <int X, int Y, int Z>
struct Vector {
static const int x = X;
static const int y = Y;
static const int z = Z;
Vector<X, Y, Z> operator+(const Vector<X, Y, Z>& other) const {
return Vector<X + oth... | magicoder | cpp |
You are tasked with creating a command-line utility that parses and processes command-line arguments for a program called "RPI". The utility should handle the following command-line options:
- `-p <port>`: Specifies the port number to be used by the program. The port number is an integer within the range 1024 to 65535... | ```python
import re
def parse_command_line_arguments(args):
port_pattern = r'-p (\d{4,5})'
address_pattern = r'-a (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'
port_match = re.search(port_pattern, args)
address_match = re.search(address_pattern, args)
if port_match and address_match:
port = int(p... | magicoder | python |
You are tasked with implementing a Python function that calculates the minimum-norm solution of a least-square problem without constraints. The function should take in the matrix A and the vector b as input and return the minimum-norm solution x.
The minimum-norm solution of a least-square problem is obtained by findi... | ```python
import numpy as np
def min_norm_solution(A, b):
A_pseudo_inv = np.linalg.pinv(A) # Calculate the pseudo-inverse of A
x = np.dot(A_pseudo_inv, b) # Calculate the minimum-norm solution using the pseudo-inverse
return x.tolist() # Convert the solution to a list and return
```
The `min_norm_solut... | magicoder | python |
You are tasked with implementing a Python function that calculates the Laplacian of an image using the second derivatives in the x and y directions. The Laplacian is a measure of the second spatial derivative of an image and is used for edge detection and feature extraction in image processing.
You are given a code sn... | ```python
import numpy as np
import cv2
from typing import Tuple
def calculate_laplacian(image: np.array) -> Tuple[np.array, np.array]:
I_xx = cv2.Laplacian(image, ddepth=cv2.CV_64F, dx=2, dy=0)
I_yy = cv2.Laplacian(image, ddepth=cv2.CV_64F, dx=0, dy=2)
return I_xx, I_yy
```
The `calculate_laplacian` funct... | magicoder | python |
You are working on a particle physics analysis project and need to write a custom filter for selecting events based on certain criteria. In this scenario, you are using the CMS (Compact Muon Solenoid) software framework, and you need to define a specific cut for event selection.
The provided code snippet is a part of ... | ```python
def isHypoValid(hypothesis):
# Implement the logic for hypothesis validity check
# For example, if 'kGenMatch' hypothesis is valid when genMatchSumDR is less than 999
return hypothesis == 'kGenMatch'
def applyCut(isHypoValid, genMatchSumDR):
# Define the cut criteria based on the given contex... | magicoder | python |
You are tasked with creating a reusable component system for a user interface framework. The framework provides a protocol called `Reusable` which represents a reusable component, and another protocol called `NibLoadable` which represents a component that can be loaded from a nib file. Additionally, there is a type ali... | ```swift
public typealias NibReusable = Reusable & NibLoadable
// MARK: - Default implementation
public extension Reusable {
static var reuseIdentifier: String {
return String(describing: self)
}
}
```
In the solution, a default extension for the `Reusable` protocol is provided. It includes a compute... | magicoder | swift |
You are tasked with implementing a reinforcement learning algorithm for training an agent to navigate a grid-based environment. The algorithm uses a buffer to store observations, actions, rewards, values, and log probabilities during the training process. The provided code snippet is a part of the algorithm's update fu... | ```python
import numpy as np
class ReinforcementLearningAlgorithm:
def __init__(self):
self.pointer, self.traj_start = 0, 0
self.adv_buffer = np.array([]) # Placeholder for adv_buffer
self.obs_buffer = np.array([]) # Placeholder for obs_buffer
self.action_buffer = np.array([]) # ... | magicoder | python |
You are tasked with creating a class for managing orders and order details in a database. The class should have methods to add orders and their details to the database. The database connection and insertion functionality are handled by the `$this->db` object, and the methods should return appropriate values based on th... | ```php
class OrderManager {
private $db;
public function __construct($db) {
$this->db = $db;
}
public function addOrder($data) {
$this->db->insert('orders', $data);
$id = $this->db->insert_id();
return (isset($id)) ? $id : FALSE;
}
public function addDetailOrde... | magicoder | php |
You are tasked with creating a function that simulates the behavior of the `createProject` function used in the code snippet. The `createProject` function takes a project name as an argument and creates a directory with that name. Additionally, it creates a file named `polar.config.js` within the newly created director... | ```javascript
const fs = require('fs');
async function createProject(projectName) {
let directoryName = projectName.replace(/[^a-zA-Z0-9]/g, '_'); // Replace special characters with underscores
let counter = 1;
while (fs.existsSync(`./${directoryName}`)) {
directoryName = `${projectName}_${counter}`; // App... | magicoder | javascript |
You are tasked with creating a web form for users to update their profile information. The form includes fields for username, email, and an option to upload a profile picture. The form also has validation rules for each field. The username must be between 6 and 12 characters, the email must be in a valid format, and th... | ```python
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, FileField
from wtforms.validators import DataRequired, Length, Email, ValidationError
from flask_wtf.file import FileAllowed, FileRequired
from models import User # Assuming User model is defined in models.py
class ProfileForm(Fla... | magicoder | python |
You are tasked with implementing a Python decorator that measures the execution time of a function and pauses the execution if it exceeds a certain threshold. The decorator should be able to handle both regular and asynchronous functions.
Your task is to complete the implementation of the `decorator_pause` function, w... | ```python
import asyncio
import time
def decorator_pause(threshold):
"""
Returns a decorator function that measures the execution time of a function and pauses if it exceeds the threshold.
Args:
threshold (float): The threshold time in seconds.
Returns:
function: A decorator function.
"""... | magicoder | python |
You are working on a software project that consists of multiple assemblies. The project has a main assembly and a test assembly. To facilitate testing, you need to make the internal types and members of the main assembly visible to the test assembly. In C#, this can be achieved using the `InternalsVisibleTo` attribute.... | ```csharp
// MainAssembly.cs
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("BaseTest")]
namespace MainAssembly
{
internal class InternalClass
{
public void InternalMethod()
{
Console.WriteLine("Internal method called.");
}
}
}
// BaseTest.cs
usin... | magicoder | csharp |
You are tasked with implementing a postfix expression evaluator using a stack data structure. Postfix notation, also known as Reverse Polish Notation (RPN), is a mathematical notation in which every operator follows all of its operands. For example, the infix expression "3 + 4 * 5" would be written in postfix notation ... | ```python
def evaluate_postfix(expression: str) -> int:
stack = []
operators = {'+': lambda x, y: x + y, '-': lambda x, y: x - y, '*': lambda x, y: x * y, '/': lambda x, y: x // y}
for token in expression.split():
if token in operators:
n2 = stack.pop()
n1 = stack.pop()
... | magicoder | python |
You are tasked with creating a PHP class that manages user access to different sections of a website based on their role and permissions. The class should include methods to check and grant access to specific routes based on the user's role and other conditions.
Your task is to implement the `RouteAccessManager` class... | ```php
class RouteAccessManager {
public function grantAccess($routeName, $userData) {
switch($routeName) {
case 'family-shoutbox':
case 'family-shoutbox-page':
if($userData->getFamilyID() > 0) {
return true; // Grant access
}
... | magicoder | php |
You are tasked with creating a Vue.js component for displaying a breadcrumb navigation bar and integrating a generic list component. The breadcrumb should display a series of steps, each with a text label and a disabled state. The generic list component should be reusable and integrated within the main component. Your ... | ```javascript
// Vue.js component implementation
<template>
<div>
<nav>
<ol>
<li v-for="(step, index) in breadcumb" :key="index">
<span v-if="step.disabled">{{ step.text }}</span>
<span v-else>{{ step.text }}</span>
</li>
</ol>
</nav>
<generic-list :items="l... | magicoder | javascript |
You are tasked with writing a script to process files in a directory hierarchy and perform specific operations based on the file types. The script should be able to handle both absolute and relative paths and should output the results to a specified directory.
You are given the following environment setup code snippet... | ```bash
#!/bin/bash
# Set up environment
export PATH=/local/munk/proorigami-prod/dunnart/trunk:/local/munk/proorigami-prod/ptgraph:${PATH}
PDBROOT=/local/munk/data/pdb/pdb
# Function to convert SVG to PS
convert_svg_to_ps() {
input_svg="$1"
output_ps="$2"
inkscape "$input_svg" -E "$output_ps"
}
# Main sc... | magicoder | shell |
You are tasked with creating a class that represents a CRM (Customer Relationship Management) entity in a Bitrix24 REST API client. Your goal is to implement a method that retrieves a list of CRM entities from the Bitrix24 server. The provided code snippet is the beginning of a namespace for the Bitrix24 REST API clien... | ```csharp
using Bitrix24RestApiClient;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace Bitrix24RestApiClient.Api.Crm
{
public class CrmApiClient
{
private Bitrix24RestApiClient _restApiClient;
public CrmApiClient(Bitrix24RestApiClient restApiClient)
{
_re... | magicoder | csharp |
You are tasked with implementing a custom layout class for embedded content in a web rendering engine. The provided code snippet is a part of a test suite for the layout of embedded content in a web browser. Your task is to complete the implementation of the custom layout class `OverriddenLayoutEmbeddedContent` by addi... | ```cpp
class OverriddenLayoutEmbeddedContent : public LayoutEmbeddedContent {
public:
explicit OverriddenLayoutEmbeddedContent(Element* element) : LayoutEmbeddedContent(element) {}
void performCustomLayout(int width, int height) {
// Custom layout logic goes here
// Example: Adjusting the size and positio... | magicoder | cpp |
You are tasked with implementing a simple menu parsing system for an LCD display. The LCD has a width of 20 characters and 4 lines. The menu parsing system should be able to handle special commands embedded within the menu text, such as displaying custom characters and setting the cursor position.
Your task is to writ... | ```python
class LCD_Menu:
def __init__(self, lcd, message):
self.lcd = lcd
self.message = message
def parse(self):
current_line = 0
current_column = 0
for token in self.message.split('{'):
if '}' in token:
command, arg = token.split('}')[0].s... | magicoder | python |
You are tasked with creating a command-line tool to manage a database using PHP and Symfony's console component. Your goal is to implement a command that drops the database with the given name. The command should accept the database name as an argument and provide an option to force the operation without asking for con... | ```php
// src/Command/DropDatabaseCommand.php
namespace App\Command;
use Doctrine\DBAL\Connection;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Componen... | magicoder | php |
You are tasked with creating a program to process analog and digital sensor readings from a cyber:bot board interfaced with a micro:bit. The cyber:bot board provides analog and digital readings, and the micro:bit processes these readings and outputs the results. The provided code snippet shows example output data from ... | ```python
def process_sensor_readings(da0, da1, ad0, ad1, ad2):
# Digital readings remain unchanged
processed_da0 = da0
processed_da1 = da1
# Adjust analog readings for voltage difference
processed_ad0 = int(ad0 * (3.326 - 3.245) / 3.3)
processed_ad1 = int(ad1 * (3.326 - 3.245) / 3.3)
proce... | magicoder | python |
You are tasked with implementing a custom `Value` class that supports the `IConvertible` interface for various data types. The `Value` class should provide methods for converting values to different data types, and the `IConvertible` interface should be implemented to handle conversions for the supported data types. Yo... | ```csharp
using System;
public class Value : IConvertible
{
private object _value;
public Value(object value)
{
_value = value;
}
public bool ToBoolean(IFormatProvider provider)
{
if (_value is bool)
return (bool)_value;
else if (_value is int)
... | magicoder | csharp |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.