query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with implementing a collision detection algorithm for a 2D object represented by a rectangle. The object has a position, width, height, and heading (angle of rotation). The collision detection is based on checking for intersection with another object's circumcircle, which is the circle that circumscribes... | ```python
from math import hypot
class RectangleObject:
def __init__(self, position, width, height, heading):
self.position = position
self.width = width
self.height = height
self.heading = heading
self.hw = hw = width / 2
self.hh = hh = height / 2
self.radiu... | magicoder | python |
You are tasked with implementing a function to calculate the area of polygons represented by a list of vertices. The vertices are given as coordinates in 2D space. Each polygon is represented as a list of vertices, where the first and last vertices are connected to form a closed shape. The vertices are provided in the ... | ```python
from typing import List
def calculate_polygon_area(polygons: List[List[List[float]]]) -> List[float]:
areas = []
for polygon in polygons:
n = len(polygon)
area = 0.0
for i in range(n):
j = (i + 1) % n
area += polygon[i][0] * polygon[j][1]
ar... | magicoder | python |
You are tasked with implementing a program to solve the one-particle Schrödinger equation for a potential specified in a function. The specific example provided is for the harmonic oscillator in 3D. The program should take into account the boundary, orbital momentum, and number of integration points. The code snippet a... | ```python
import numpy as np
import matplotlib.pyplot as plt
def potential(r):
# Define the potential function here
# Example: harmonic oscillator potential
return 0.5 * r**2
def solve_schroedinger(Dim=400, RMax=10.0, RMin=0.0, lOrbital=0):
# Define the radial coordinate
r = np.linspace(RMin, RMax... | magicoder | python |
You are tasked with creating a simple iOS app that allows users to search for movies using the OMDb API and display the search results. You will need to implement a view controller that includes a search bar for users to input their search query and a table view to display the search results. The app should use RxSwift... | ```swift
import UIKit
import RxCocoa
import RxSwift
class ViewController: UIViewController {
private let disposeBag = DisposeBag()
private let searchBar = UISearchBar()
private let tableView = UITableView()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
... | magicoder | swift |
You are tasked with creating a function that interacts with the Slack API to remove a reaction from a message. The provided code snippet is a part of an asynchronous function that sends a request to the Slack API using the reqwest crate in Rust. Your task is to implement the missing function `remove_reaction` that take... | ```rust
use reqwest;
async fn remove_reaction(
client: &reqwest::Client,
token: &str,
channel: &str,
timestamp: &str,
reaction: &str,
) -> Result<(), reqwest::Error> {
let mut params = vec![
("token", token),
("channel", channel),
("timestamp", timestamp),
("name... | magicoder | rust |
You are tasked with implementing a function that simulates a basic text editor's undo feature. The text editor supports two operations: appending a string to the current text and undoing the last operation. You need to implement the `TextEditor` class with the following methods:
- `append(text: String)`: Appends the gi... | ```swift
class TextEditor {
private var text: String
private var history: [String]
init() {
text = ""
history = []
}
func append(text: String) {
history.append(self.text)
self.text += text
}
func undo() {
if let lastText = history.popLast() {
... | magicoder | swift |
You are tasked with implementing a function to filter out "good" words from a list of words. A "good" word is defined as a word that contains at least one vowel and one consonant. Your task is to write a Python function `good_words(words)` that takes a list of lowercase words as input and returns a list of "good" words... | ```python
def good_words(words):
def has_vowel_and_consonant(word):
vowels = {'a', 'e', 'i', 'o', 'u'}
has_vowel = any(char in vowels for char in word)
has_consonant = any(char not in vowels for char in word)
return has_vowel and has_consonant
return [word for word in words if h... | magicoder | python |
You are tasked with implementing a Python class that simulates a simple stack data structure. The class should have the following functionalities:
1. `push(item)`: Add an item to the top of the stack.
2. `pop()`: Remove and return the item at the top of the stack. If the stack is empty, return None.
3. `peek()`: Return... | ```python
class Stack:
def __init__(self):
self.state = list()
def push(self, item):
# Add item to the top of the stack
self.state.append(item)
def pop(self):
# Remove and return the item at the top of the stack
if not self.is_empty():
return self.state.... | magicoder | python |
You are working on a project that involves processing and analyzing large datasets using TensorFlow. As part of this project, you need to create a custom data pipeline using TensorFlow's dataset operations. Your task is to write a Python function that takes in a list of input datasets and generates a new dataset contai... | ```python
import tensorflow as tf
from itertools import product
def generate_combinations_dataset(input_datasets):
# Convert input datasets to TensorFlow datasets
tf_datasets = [tf.data.Dataset.from_tensor_slices(ds) for ds in input_datasets]
# Create a Cartesian product of the input datasets
combined... | magicoder | python |
You are tasked with implementing a custom UITableViewCell subclass for a mobile application that manages cryptocurrency transactions. The provided code snippet is a starting point for the custom cell, but it lacks the necessary functionality to display transaction details. Your task is to extend the `TxUnlockTokenCell`... | ```swift
import UIKit
class TxUnlockTokenCell: UITableViewCell {
// Properties to store transaction information
var tokenNameLabel: UILabel!
var amountLabel: UILabel!
var statusLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
setupUI()
}
// Method to con... | magicoder | swift |
You are tasked with implementing a Python class that interacts with a remote HTTP service to sign data using the PKCS#1 standard. The provided code snippet is a partial implementation of a `RemotePkcs1Signer` class, which is responsible for making HTTP requests to a signing service to sign data using a specified algori... | ```python
import requests
class RemotePkcs1Signer(object):
""" Client-side Signer subclass, that calls the Signing Service over HTTP to sign things """
# standard headers for request
headers = {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
def __init__(self, ... | magicoder | python |
You are tasked with implementing a function to calculate the sum of a list of floating-point numbers with high precision. The function should use the `hi`/`lo` summation method to maintain exactness in the partial sums.
Your task is to implement the `hi_lo_sum` function, which takes a list of floating-point numbers as... | ```rust
use std::mem;
fn hi_lo_sum(numbers: &[f64]) -> f64 {
let mut partials: Vec<f64> = Vec::new();
for &x in numbers {
let mut i: usize = 0;
while i < partials.len() {
let y: f64 = partials[i];
if x.abs() < y.abs() {
mem::swap(&mut x, &mut partials[i])... | magicoder | rust |
You are tasked with creating a program that utilizes TensorFlow Hub to perform image classification on a dataset of flower images. Your goal is to build a deep learning model using a pre-trained image feature vector module from TensorFlow Hub and train it to classify different types of flowers. The dataset consists of ... | ```python
import tensorflow as tf
import tensorflow_hub as hub
import numpy as np
import os
from sklearn.model_selection import train_test_split
from tensorflow.keras.preprocessing.image import ImageDataGenerator
# Load the flower image dataset
data_dir = 'path_to_flower_dataset_directory'
batch_size = 32
img_height =... | magicoder | python |
You are tasked with implementing a data structure to store and retrieve information about different sizes of Nexus devices. The data structure should allow for efficient retrieval of the sizes based on the device model. You are given a code snippet that initializes a variable `nexus_name` with the value "nexus_sizes". ... | ```rust
use std::collections::HashMap;
struct NexusSizes {
sizes: HashMap<String, Vec<String>>,
}
impl NexusSizes {
fn new() -> NexusSizes {
NexusSizes {
sizes: HashMap::new(),
}
}
fn add_size(&mut self, model: &str, size: &str) {
self.sizes.entry(model.to_string()... | magicoder | rust |
You are tasked with implementing a simple game AI for a medieval battle simulation. The AI will need to make decisions based on the current state of the battle and the available actions. The actions available to the AI are represented as a Swift enum with associated comments describing the behavior of each action:
```... | ```swift
func makeDecision(currentState: [String: Any]) -> BattleAction {
// Example implementation: always charge into battle
return .charge
}
```
The provided solution is a simple placeholder that always returns the `charge` action, regardless of the actual state of the battle. In a real-world scenario, the ... | magicoder | swift |
You are tasked with implementing a simple stopwatch functionality in a graphical user interface (GUI) application using C++ and the Qt framework. The provided code snippet is a part of a Qt application's main window class (`MainWindow`) and shows two slots (`on_actionStart_triggered` and `on_actionStop_triggered`) that... | ```cpp
#include <QMainWindow>
#include <QAction>
#include <QTimer>
#include <QTime>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr) : QMainWindow(parent)
{
// Other initialization code
// ...
// Create and connect actions
QAct... | magicoder | cpp |
You are tasked with implementing a script runner interface for executing Groovy scripts within a Java application. The interface, `ScriptRunner`, is responsible for defining the contract for running Groovy scripts and passing input parameters to the scripts. Your goal is to create a concrete implementation of this inte... | ```java
package com.tufin.health.check.groovy;
import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import java.util.Map;
public class GroovyScriptRunner implements ScriptRunner {
@Override
public Object runScript(String script, Map<String, Object> params) {
try {
Binding binding ... | magicoder | java |
You are tasked with implementing a Python class that processes search results from the availability endpoint of a shipping module. The class, `VesselAvailabilityResult`, is a subclass of `Result` and provides methods to convert the search results into a list of `Availability` objects and a pandas DataFrame.
The `Avail... | ```python
import pandas as pd
class VesselAvailabilityResult(Result):
"""
Container class holding search results returned from the availability endpoint.
Please note: a subscription to the Freight module is required to access Vessel Availability.
This class has two methods, `to_list()`, and `to_df()`... | magicoder | python |
You are tasked with implementing a simple transaction management system for a hypothetical database using Java. The system should allow for the execution of multiple database operations within a single transaction and provide the ability to commit or rollback the transaction.
You are provided with a partial Java class... | ```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class NutzJdbcTransaction {
private Connection connection;
private boolean inTransaction;
public NutzJdbcTransaction() {
connection = null;
inTransaction = fal... | magicoder | java |
You are tasked with implementing a thread-safe cache for storing recent revisions of a single repository. The cache should be able to efficiently store and retrieve revision information and should be resilient to concurrent access from multiple threads. You are provided with a partial implementation of the `RepositoryR... | ```java
import java.io.File;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
public final class RepositoryRevisionCache {
private final ServerPluginConfig myConfig;
private final File myRepositoryDir;
private final RevisionCacheType myType;
private final RecentEntr... | magicoder | java |
You are tasked with designing a RESTful API for a user management system. The API should support operations for retrieving user information, changing user passwords, and uploading user profile pictures. The API is built using the Flask-RESTful library in Python. The code snippet provided below demonstrates the registra... | ```python
from flask import Flask
from flask_restful import Api, Resource, reqparse
app = Flask(__name__)
api = Api(app)
# Sample user data
users = {
1: {'id': 1, 'name': 'John Doe', 'email': 'john@example.com'},
2: {'id': 2, 'name': 'Jane Smith', 'email': 'jane@example.com'}
}
class UserInfo(Resource):
... | magicoder | python |
You are tasked with creating a Java method that processes different types of file attachments based on their field definitions. The method should take into account various attachment types and their corresponding field definitions to handle the processing accordingly.
You are provided with a code snippet that includes... | ```java
public void processAttachment(UploadFieldType attachmentType, FieldDefinition fieldDef) {
switch (attachmentType) {
case ATTACHMENT_BLOB:
// Process attachment as a binary large object
// Use fieldDef to determine specific processing logic
break;
case ATTA... | magicoder | java |
You are tasked with creating a Python program that utilizes multithreading and network requests to fetch and process data from a remote API. The program should be designed to handle asynchronous tasks and use PyQt5 for GUI implementation.
Your task is to create a program that fetches data from a remote API, processes ... | ```python
import json
import requests
from functools import partial
from threading import Thread
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QVBoxLayout, QWidget
from PyQt5.QtCore import pyqtSignal, QObject
from core import Utils, Command
class DataProcessor(QObject):
data_processed = pyqtSigna... | magicoder | python |
You are tasked with implementing an image processing pipeline in Swift. The pipeline should be able to apply a series of operations to an input image and produce the processed image as output. The operations to be applied include scaling and adjusting the alpha value of the image.
You are provided with a code snippet ... | ```swift
import UIKit
protocol ImageOperation {
func apply(to image: UIImage) -> UIImage
}
class ImageProcessor {
let image: UIImage
let operations: [ImageOperation]
init(image: UIImage, operations: [ImageOperation]) {
self.image = image
self.operations = operations
}
func ru... | magicoder | swift |
You are tasked with implementing a simplified version of a concurrent programming construct using Rust's asynchronous programming features. Your goal is to create a custom asynchronous channel that allows sending and receiving messages between different asynchronous tasks.
You are provided with a partial implementatio... | ```rust
use futures::task::{Poll, Async};
struct AsyncChannel<T> {
// Assume the existence of a field `0` of type `Lock` representing the internal state of the channel
}
impl<T> AsyncChannel<T> {
fn poll(&mut self) -> Poll<Option<T>, ()> {
let mut channel = match self.0.poll_lock() {
Async... | magicoder | rust |
You are tasked with implementing a class that represents a bit string unary operator for flipping 0s to 1s with a specific distribution. The class should be able to handle the m-over-n flip operation, where m bits are flipped out of every n consecutive bits. Your task is to implement the method that applies this unary ... | ```java
/**
* Applies the m-over-n flip unary operator to the given bit string.
* @param bitString
* the input bit string
* @return the bit string after applying the unary operator
*/
public String apply(final String bitString) {
int m = mN / 10; // Extract m from mN
int n = mN % 10; // Extract n from... | magicoder | java |
You are tasked with implementing a custom dataset sampler for a machine learning project. The sampler will be used to create batches of data from the MNIST dataset for both training and testing purposes. The sampler should support replacement of samples within each batch.
You are provided with a code snippet that init... | ```python
import torch
from torch.utils.data import Dataset, DataLoader
from torchvision import datasets, transforms
import random
class SamplerDatasetWithReplacement(Dataset):
def __init__(self, dataset, batch_size):
self.dataset = dataset
self.batch_size = batch_size
def __len__(self):
... | magicoder | python |
You are tasked with creating a Python function that generates an HTML table from a given SQLite database table. The function should take the table name as input and return the HTML representation of the table.
The function should perform the following steps:
1. Connect to the SQLite database using the provided connect... | ```python
import sqlite3
def generate_html_table(conn, table) -> str:
output = "<table><tr>"
# Retrieve column names of the specified table
c = conn.cursor()
for tn in c.execute(f"PRAGMA table_info('{table}')"):
output += f"<th>{tn[1]}</th>"
output += "</tr>"
# Retrieve all ro... | magicoder | python |
You are tasked with creating a password validation system. The system should check whether a given password meets certain criteria based on its length, character repetition, and ascending order of characters.
You are given a class `Solution` with a method `is_password_part_1` that takes in three parameters:
- `n`: an ... | ```python
def get_repeat_info(n: int):
# Assume this function is implemented to return is_asc and hashmap as described in the problem.
pass
```
The `is_password_part_1` method first calls the `get_repeat_info` function to obtain the ascending order flag and character count hashmap. It then calculates the minim... | magicoder | python |
You are tasked with implementing a sorting algorithm for a list of objects based on specific fields and orders. The input will consist of an array of objects, each containing various fields. Additionally, you will receive two strings: `sortField` representing the field by which the objects should be sorted, and `sortOr... | ```javascript
function customSort(objects, sortField, sortOrder) {
return objects.slice().sort((a, b) => {
if (sortOrder === "asc") {
if (a[sortField] < b[sortField]) return -1;
if (a[sortField] > b[sortField]) return 1;
return 0;
} else if (sortOrder === "desc") {
if (a[sortField] > b... | magicoder | javascript |
You are tasked with implementing a custom matcher for testing log messages in a Java application. The `describeTo` method is part of the Hamcrest library, which is commonly used for writing matcher objects in unit tests. Your goal is to create a custom matcher that verifies whether a log message does not contain unexpe... | ```java
import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;
public class LogErrorMatcher extends TypeSafeMatcher<String> {
@Override
protected boolean matchesSafely(String logMessage) {
if (logMessage.startsWith("ERROR: ")) {
String errorMessage = logMessage.substring(7); ... | magicoder | java |
You are tasked with implementing a class for managing platform-specific handles in a multi-process environment. The class, `PlatformChannelPair`, is responsible for passing a client handle to a child process and ensuring its validity. The code snippet provided includes two member functions of the `PlatformChannelPair` ... | ```cpp
#include <iostream>
#include <utility>
#include <cassert>
// Define a platform-specific handle type
using PlatformHandle = /* platform-specific handle type */;
// Define a scoped handle wrapper for managing the platform handle
class ScopedInternalPlatformHandle {
public:
explicit ScopedInternalPlatformHand... | magicoder | cpp |
You are tasked with creating a Python class that simulates a simple login manager for a website using the `pywikibot` library. Your task is to implement the `LoginManager` class with the following requirements:
- The `LoginManager` class should have a constructor that takes in three parameters: `code`, `fam`, and `use... | ```python
import pywikibot
from pywikibot.data.api import LoginManager
class LoginManager:
def __init__(self, code, fam, user):
self.site = pywikibot.Site(code=code, fam=fam, user=user)
def login(self, username, password):
try:
login_manager = LoginManager(site=self.site, user=user... | magicoder | python |
You are tasked with implementing a method that returns the default value for a given type in C#. The default value is the value that is assigned to a variable if no explicit value is specified. For example, the default value for an integer type is 0, for a string type is null, and so on.
Write a method `GetDefaultValu... | ```csharp
using System;
public static class TypeExtensions
{
public static object GetDefaultValue(this Type t)
{
if (t.IsValueType)
{
return Activator.CreateInstance(t);
}
else if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>))
{
... | magicoder | csharp |
You are tasked with creating a Python function that handles the introspection of other functions. Introspection is the ability of a program to examine the type or properties of an object at runtime. Your function should take in a list of functions and introspect each one, logging any exceptions that occur during the pr... | ```python
import logging
def introspect_functions(functions):
log = logging.getLogger(__name__)
for fun in functions:
try:
# Introspect the function
# ...
log.info('Introspecting {0}: No exceptions'.format(fun.__name__))
except Exception as exc:
l... | magicoder | python |
You are tasked with implementing a class for managing equivalent characters in a text processing system. The class, `EquivalentChar`, is initialized with parameters `base_file`, `create_num`, `change_rate`, and `seed`. The `base_file` parameter specifies the path to a file containing equivalent character mappings. The ... | ```python
import random
class EquivalentChar:
def __init__(self, base_file, create_num=5, change_rate=0.05, seed=1):
self.base_file = base_file
self.create_num = create_num
self.change_rate = change_rate
self.seed = seed
self.base_file_mapobj = {}
random.seed(seed)
... | magicoder | python |
You are tasked with implementing a tweet scheduler function that takes a client object and a timestamp as input and returns an array of tweets that are ready to be published at the given timestamp. The client object contains an array of tweets, each with a timestamp in milliseconds. The function should identify the twe... | ```javascript
function publishTweets(client, timestampMs) {
const tweetsToPublish = [];
const tweetQueue = [];
client.lastId = client.tweets[0].id;
for (let idx = 0; idx < client.tweets.length; idx++) {
const tweet = client.tweets[idx];
if (tweet.timestamp_ms <= timestampMs) {
tweetsToPublish.push... | magicoder | javascript |
You are working on a recommendation system that utilizes TensorFlow for building a neural network model. The code snippet provided is a part of the model implementation. The snippet involves the usage of TensorFlow's functions for calculating the sigmoid and maximum of certain tensor operations. Your task is to underst... | The `recommendation_score` function takes the input tensors `dot_user_pos`, `p_item_bias`, `dot_user_neg`, and `n_item_bias`, and performs the specified operations to calculate the recommendation score. The differences between `dot_user_pos` and `dot_user_neg`, and between `p_item_bias` and `n_item_bias` are calculated... | magicoder | python |
You are tasked with creating a Django REST framework view that modifies the status of an order. The status modification should be implemented as a custom action within the view. Your task is to complete the implementation of the `status` method within the given Django REST framework view.
The `status` method should ac... | ```python
# Sample Order Model
class Order(models.Model):
status = models.CharField(max_length=20)
# Sample Order Serializer
class OrderSerializer(serializers.ModelSerializer):
class Meta:
model = Order
fields = '__all__'
# Sample Django REST Framework View
class OrderViewSet(viewsets.ModelVie... | magicoder | python |
You are tasked with implementing a thread-local object pool in C#. An object pool is a collection of reusable objects that can be shared across multiple threads. The goal of this problem is to create a thread-local object pool that allows each thread to have its own set of objects, managed independently from other thre... | ```csharp
using System;
using System.Collections.Generic;
using System.Threading;
public interface IObjectPoolPolicy<T>
{
T CreateObject();
void ResetObject(T obj);
bool ValidateObject(T obj);
}
public class TLSObjectPool<T>
{
private readonly IObjectPoolPolicy<T> _policy;
private readonly int _ma... | magicoder | csharp |
You are working on a task management system that involves adding tasks to a database, performing cleanup operations, and verifying the state of the database after the cleanup. The code snippet provided is a part of the test suite for this system. The `db.session.add_all()` method is used to add multiple objects to the ... | ```python
def cleanup_failed_tasks():
# Retrieve all failed tasks from the database
failed_tasks = Task.query.filter_by(status='failed').all()
# Perform cleanup operations for each failed task
for task in failed_tasks:
# Perform cleanup specific to each task, e.g., deleting associated files... | magicoder | python |
You are tasked with designing a modular neural network architecture for image classification using Python. The architecture should consist of three main components: network utilities, network bodies, and network heads. The network utilities module contains various utility functions for network operations, the network b... | ```python
# network_utils.py
class NetworkUtils:
def preprocess_image(self, image):
# Perform preprocessing operations such as normalization, resizing, etc.
pass
# network_bodies.py
class NetworkBodies:
def create_resnet(self):
# Create ResNet architecture
pass
def create_v... | magicoder | python |
You are tasked with implementing a custom module resolution algorithm for a JavaScript project. The project uses a custom module system that extends the standard Node.js module resolution process. The provided code snippet is a simplified representation of the module resolution logic.
The code snippet includes import ... | ```javascript
function resolveCustomModulePath(modulePath, customModules) {
if (customModules.hasOwnProperty(modulePath)) {
return customModules[modulePath];
}
// Custom module resolution logic
const moduleSegments = modulePath.split('/');
for (let i = moduleSegments.length; i > 0; i--) {
const parti... | magicoder | javascript |
You are tasked with implementing a TypeScript class that manages field properties for a form builder application. The class should provide methods for adding various field properties and retrieving specific information about the fields.
Your task is to create a TypeScript class called `FieldManager` with the following... | ```typescript
class FieldManager {
private fieldProps: Record<string, object> = {};
addFieldProps(props: object): void {
this.fieldProps = { ...this.fieldProps, ...props };
}
addReadOnly(fieldName: string): void {
this.fieldProps[fieldName] = { ...this.fieldProps[fieldName], readOnly: true };
}
a... | magicoder | typescript |
You are tasked with creating a Python function that parses a given setup.py file and extracts specific information from it. The setup.py file is used in Python projects to define the project's metadata and dependencies. Your function should extract the following information from the setup.py file:
1. URL of the project... | ```python
import re
def parse_setup_file(file_path):
with open(file_path, 'r') as file:
setup_content = file.read()
url_match = re.search(r"url='(.*?)'", setup_content)
author_match = re.search(r"author='(.*?)'", setup_content)
email_match = re.search(r"author_email='(.*?)'", setup_content)
... | magicoder | python |
You are tasked with creating a Python script that automates the process of checking and installing Python packages. Your script should be able to handle both local and global installations and should provide feedback on the success or failure of the installation process.
Write a Python function called `install_package... | ```python
import subprocess
def install_package(package_name, global_install):
if global_install:
install_command = f"pip install -q {package_name}"
else:
install_command = f"pip install -q -e . {package_name}"
try:
subprocess.run(install_command, shell=True, check=True)
im... | magicoder | python |
You are tasked with implementing a global exception handling mechanism for a web application. The application is built using Java and Spring Boot framework. The global exception handling mechanism should intercept any unhandled exceptions that occur during the execution of the application and provide a consistent way t... | ```java
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import o... | magicoder | java |
You are tasked with implementing a simple routing system for a web application. The routing system should be able to handle different types of routes and map them to corresponding controller methods. The routes are defined using a fluent interface, and the controller methods are specified using a string in the format "... | ```python
class Router:
def __init__(self):
self.routes = {}
def route(self, path, controller_method):
self.routes[path] = controller_method
def handle_request(self, request_path):
if request_path in self.routes:
controller_method = self.routes[request_path]
... | magicoder | python |
You are tasked with implementing a method to add a new build form to a sparse grid data structure. The grid is represented by a two-dimensional sparse array, where each cell may contain a build form object. The grid is implemented using the `DefaultBuildGridImpl` class, which is backed by a `Map` of `Map`s. Each row in... | ```java
public void addBuildForm(int row, int height, BuildForm buildForm) {
// Get the map for the specified row, or create a new map if it doesn't exist
Map<Integer, BuildForm> rowMap = data.get(row);
if (rowMap == null) {
rowMap = new HashMap<>();
data.put(row, rowMap);
}
// Add ... | magicoder | java |
You are given a string containing only lowercase English letters. Your task is to write a function that compresses the string by replacing consecutive identical characters with a single instance of the character followed by the number of times it appears consecutively. If the compressed string is not shorter than the o... | ```python
def compressString(inputString):
compressed = ""
count = 1
for i in range(1, len(inputString)):
if inputString[i] == inputString[i - 1]:
count += 1
else:
compressed += inputString[i - 1] + str(count)
count = 1
compressed += inputString[-1] + ... | magicoder | python |
You are tasked with creating a custom validation rule for a Laravel application. The application has a `Category` model and a `CategoryController` that handles the retrieval of all categories. The `Category` model is responsible for interacting with the database table storing category data. The `CategoryController` has... | ```php
// Define the custom validation rule in the AppServiceProvider or any service provider
use Illuminate\Support\ServiceProvider;
use Validator;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
Validator::extend('uniqueCategoryName', function ($attribute, $value, $paramet... | magicoder | php |
You are tasked with creating a simple program that utilizes the SFML library to display a window and draw a shape. Your program should create a window, handle user input, and draw a shape within the window using SFML's graphics module.
Your program should perform the following tasks:
1. Create an SFML window with a sp... | ```cpp
#include <SFML/Graphics.hpp>
int main()
{
// Create an SFML window with a specified size and title
sf::RenderWindow window(sf::VideoMode(800, 600), "SFML Shape Drawing");
// Main loop to handle user input and draw a shape
while (window.isOpen())
{
sf::Event event;
while (win... | magicoder | cpp |
You are tasked with creating a program that analyzes a given text file to count the occurrences of each unique word. Your program should read the text file, tokenize the words, and then output the count of each unique word in the file. For the purpose of this problem, a word is defined as a sequence of alphanumeric cha... | ```python
import re
def count_word_occurrences(file_path: str) -> dict:
word_count = {}
with open(file_path, 'r') as file:
for line in file:
words = re.findall(r'\b\w+\b', line.lower())
for word in words:
word_count[word] = word_count.get(word, 0) + 1
return ... | magicoder | python |
You are tasked with implementing a Java class that represents a simple data structure for storing and retrieving information about returned entities. The class should include a method for setting the result value and a method for getting the result value.
Your task is to create a Java class named `ReturnedEntity` with... | ```java
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* A class representing a returned entity.
*/
public class ReturnedEntity {
/**
* The Result.
*/
@JsonProperty
private String result;
/**
* Sets the result value.
*
* @param result the result value to be set
... | magicoder | java |
You are tasked with implementing a priority queue for processing tickets in a customer support system. Each ticket has a "from" field indicating the origin of the ticket. The priority queue should process tickets based on their "from" field in lexicographical order. If two tickets have the same "from" field, they shoul... | ```java
import java.util.PriorityQueue;
public class TicketSystem {
private PriorityQueue<Ticket> tickets;
public TicketSystem() {
tickets = new PriorityQueue<>();
}
public void addTicket(Ticket ticket) {
tickets.add(ticket);
}
public Ticket processNextTicket() {
retu... | magicoder | java |
You are given a list of integers representing the scores of a game. Your task is to write a function that calculates the average score of the game, excluding the highest and lowest scores.
Write a function `calculate_average_score(scores)` that takes in a list of integers `scores` (2 <= len(scores) <= 100) and returns... | ```python
def calculate_average_score(scores):
if len(scores) < 3:
return "Not enough scores to calculate average"
scores.sort()
scores = scores[1:-1] # Exclude the highest and lowest scores
average_score = sum(scores) / len(scores)
return round(average_score, 2)
```
The `calculate_ave... | magicoder | python |
You are tasked with creating a PHP class that manages user authentication and password reset functionality for a web application. Your class should include methods for user login, logout, and password reset. Additionally, you need to ensure that the class is properly namespaced and follows best practices for organizing... | ```php
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Auth\ResetPasswordController;
class UserAuthController extends Controller
{
// Method for user login
public function login(Request $request)
{
// Implementa... | magicoder | php |
You are tasked with implementing a Python function that creates a data loader for a machine learning experiment and sets up a tensorboard writer for visualization. The function takes in the base directory path, a quantile value, and a set of pseudo labels. It then creates a directory based on the quantile value within ... | ```python
import os
from typing import List
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
def setup_experiment(exp_base_dir: str, quantile: float, pseudo_labels: List[str]) -> DataLoader:
exp_dir = exp_base_dir + str(quantile) + '/'
if not os.path.exists(exp_dir):
... | magicoder | python |
You are tasked with implementing a function that calculates the size of a single-line attributed string in a given bounding box. The function should take an attributed string and a CGSize as input, and modify the CGSize to reflect the size of the attributed string when rendered on a single line within the specified bou... | ```swift
extension NSAttributedString {
func sizeOneLine(cgSize: inout CGSize) {
let size = CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
let boundingBox = self.boundingRect(with: size, options: [.usesLineFragmentOrigin, .usesFontLeading], cont... | magicoder | swift |
You are tasked with creating a program that validates whether a given date in the format "dd/mm/yyyy" is a valid date or not. A valid date should adhere to the Gregorian calendar rules, including the appropriate number of days for each month and accounting for leap years.
Your program should take a date input in the f... | ```python
def is_valid_date(date_str):
try:
day, month, year = map(int, date_str.split('/'))
if year < 1:
return "Invalid date"
if month < 1 or month > 12:
return "Invalid date"
if month in [4, 6, 9, 11] and day > 30:
return "Invalid date"
... | magicoder | python |
You are tasked with implementing a module resolution system for a JavaScript project. The system should be able to resolve and import modules from different files within the project directory. The code snippet provided is an example of a module export statement in JavaScript, where the `export * from "./Project"` state... | ```javascript
const path = require('path');
function resolveModule(currentFile, modulePath) {
if (modulePath.startsWith('/')) {
// Absolute path, resolve relative to project root directory
return path.resolve(__dirname, '..', modulePath.substring(1));
} else if (modulePath.startsWith('./') || modulePath.st... | magicoder | javascript |
You are working on anomaly detection for a manufacturing company that produces electronic components. The company has collected data on various features of the components, such as voltage, current, and frequency, and wants to detect any anomalies in the production process. You decide to use Python and the PyOD library,... | ```python
import numpy as np
from mat4py import loadmat
from pyod.models.vae import VAE
from pyod.models.pca import PCA
from pyod.models.knn import KNN
# Step 1: Load the dataset from "component_data.mat"
data = loadmat('component_data.mat')
# Step 2: Preprocess the data
# Assuming the dataset contains a key 'X' for ... | magicoder | python |
You are working on a data processing pipeline for a particle physics experiment. The pipeline is configured using a Python-based configuration language called CMS (Compact Muon Solenoid) and is used to process data from the experiment's detectors. The code snippet provided is a part of the configuration file for the pi... | ```python
import re
def parse_configuration(config_snippet: str) -> dict:
result = {}
# Extracting first run number
first_run_match = re.search(r'myFirstRunLSEvt\[(\d+)\]', config_snippet)
if first_run_match:
result['first_run'] = int(first_run_match.group(1))
else:
result['first_r... | magicoder | python |
You are tasked with implementing a Swift function that generates a YAML representation of a build tool's configuration. The function should take the tool's name, a description, inputs, and outputs as input and produce the YAML representation as output.
You are provided with a code snippet that demonstrates how the `ap... | ```swift
func generateYAMLConfig(toolName: String, description: String, inputs: [String], outputs: [String]) -> String {
var yamlRepresentation = "tool: \(toolName)\n"
yamlRepresentation += "description: \(description)\n"
yamlRepresentation += "inputs:\n"
for input in inputs {
yamlRepresentation... | magicoder | swift |
You are given a number `n`. Your task is to write a Java method `primeFactorization` that takes an integer `n` as input and prints its prime factorization in the form of `p^kX`, where `p` is a prime factor and `k` is its power. The prime factors should be printed in ascending order of their values.
For example, if `n ... | ```java
public static void primeFactorization(int n) {
for (int i = 2; i * i <= n; i++) {
int count = 0;
while (n % i == 0) {
n /= i;
count++;
}
if (count > 0) {
System.out.print(i + "^" + count + "X");
}
}
if (n != 1) {
Sys... | magicoder | java |
You are tasked with creating a script to generate configuration files for sidecar injection in Istio. The script should take in optional parameters for log levels, Istio version, and the Istio proxy init image. The generated configuration file should be specific to Istio version 0.7.1 and should be saved in a designate... | ```bash
#!/bin/bash
NGX_LOG_LEVEL=${2:-debug}
AGENT_LOG_LEVEL=${3:-1}
NGINMESH_VERSION=${4:-0.7.1}
ISTIO_PROXY_INIT=docker.io/istio/proxy_init:0.7.1
SCRIPTDIR=/path/to/directory # Replace with the actual directory path
echo "Generating sidecar config"
NGINMESH_CONFIG_NAME=nginmesh-sidecar-injector-configmap.yaml
GEN_... | magicoder | shell |
You are tasked with creating a TypeScript class that interacts with an API to fetch data about members of parliament. The API provides a method `pegarTodosDeputados` which takes in parameters and returns an observable of type `RespostaModel<DeputadoModel[]>`. Your task is to implement the TypeScript class with the meth... | ```typescript
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
// Define the model for the response
interface RespostaModel<T> {
// Define the structure of the response model
}
// Define the model for the Deputado (Member of Parliament)
interface DeputadoModel {
// Define the ... | magicoder | typescript |
You are tasked with implementing a source code loader for a programming language that supports importing modules. The loader should be able to handle circular dependencies and detect errors in the imported code. The code snippet provided is a part of the loader implementation and contains a list of source code paths an... | To solve this problem, you can implement a source code loader class with methods to add sources, handle imports, detect circular dependencies, and build a source location table. Here's a high-level solution using Python:
```python
class SourceCodeLoader:
def __init__(self):
self.sources = {} # Dictionary ... | magicoder | python |
You are working on a data processing application that involves manipulating and analyzing various variables. Your task is to implement a function that takes a list of variable names and their corresponding values, and then calculates the sum of the values for the variables that are multiples of a given number.
You are... | ```python
def calculate_sum_of_multiples(variables, multiple):
sum_of_multiples = 0
for var_name, value in variables.items():
if int(var_name[3:]) % multiple == 0: # Extract the number from the variable name and check if it's a multiple
sum_of_multiples += value
return sum_of_multiples
... | magicoder | python |
You are tasked with creating a class that represents settings for a new application in a cloud environment. The class should inherit from a base class and implement specific functionality related to the settings for the new application.
Your task is to implement the `NewApplicationSettings` class, which should inherit... | ```csharp
using System;
namespace Cake.Apprenda.Tests.ACS.NewApplication
{
public class NewApplicationSettingsTests : CloudShellSettingsTestsBase<NewApplicationSettings>
{
// Implement the NewApplicationSettings class
public class NewApplicationSettings
{
// Properties repre... | magicoder | csharp |
You are tasked with creating a Python function that processes data from a CSV file and calculates the mean value of a specific column. The CSV file contains data related to the time taken for a process, and the function needs to calculate the mean time for a specific process type.
You are given a CSV file named "resul... | ```python
import csv
def calculate_mean_time(file_name, process_type):
total_time = 0
count = 0
with open(file_name, 'r') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
if row['process_type'] == process_type:
total_time += float(row['time_taken'... | magicoder | python |
You are tasked with implementing a custom exception class and handling it within a Java program. Your task is to create a custom exception called `UnknownReaderTypeException` that extends the `IllegalArgumentException` class. This exception should be thrown when attempting to create a `Reader` object with an unknown ty... | ```java
// Custom exception class
class UnknownReaderTypeException extends IllegalArgumentException {
public UnknownReaderTypeException(String unknownType) {
super(String.format("Unable to create a Reader: Unknown Reader type in Source specification: %s", unknownType));
}
}
// Reader class
class Reader... | magicoder | java |
You are tasked with creating a program that simulates a simplified version of a command-line utility for executing commands and handling errors. Your program should take a command as input and execute it, while also handling potential errors that may occur during the execution.
Your program should follow these rules:
... | ```bash
#!/bin/bash
handle_error() {
local exit_status=$1
if [ $exit_status -ne 0 ]; then
echo "Error: Command execution failed with exit status $exit_status"
fi
}
# Read the command from user input
read -p "Enter the command to execute: " user_command
# Execute the command and handle errors
outp... | magicoder | shell |
You are tasked with simulating a simple animation of a moving object on the console screen. The code snippet provided is a part of a C program that uses the Windows API to change the text color and create a moving object effect. Your task is to complete the program by implementing the missing parts and ensuring that th... | ```c
#include <stdio.h>
#include <windows.h>
int main() {
int color = 0;
HANDLE hConsole;
hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
//color handle
system("title zly yyds!!!");
int x = 0; // Initial position of the object
int d1 = 1; // Speed of the object's movement
int N = 80; // Wi... | magicoder | c |
You are tasked with implementing a simplified event handling system in Java. The system should be able to manage a list of events and execute them based on their readiness.
You are provided with a partial code snippet for the `run` method of an `EventScheduler` class. The `run` method is responsible for continuously c... | ```java
import java.util.ArrayList;
import java.util.List;
interface Event {
boolean ready();
void action();
}
class EventScheduler {
private List<Event> eventList;
public EventScheduler() {
this.eventList = new ArrayList<>();
}
public void addEvent(Event event) {
eventList.a... | magicoder | java |
You are working on a medical imaging project and need to analyze grayscale images of tissue samples. The images are represented as 2D arrays, where each element represents the intensity value of a pixel. Your task is to implement a function that calculates the intensity histogram of a given grayscale image and identifi... | ```python
import numpy as np
def peak_intensity_value(image):
# Flatten the 2D image array into a 1D array
flattened_image = image.flatten()
# Calculate the intensity histogram using numpy's histogram function
hist, bin_edges = np.histogram(flattened_image, bins=range(256))
# Find the int... | magicoder | python |
You are tasked with creating a function that will validate the structure of a given HTML document. The function should check if the document contains a specific structure, and return a boolean value based on the validation result.
The function signature is as follows:
```javascript
function validateHTMLStructure(htmlS... | ```javascript
function validateHTMLStructure(htmlString) {
const parser = new DOMParser();
const doc = parser.parseFromString(htmlString, 'text/html');
const listItemsWithAnchors = doc.querySelectorAll('ul li a');
return listItemsWithAnchors.length > 0;
}
```
The solution defines the `validateHTMLStructu... | magicoder | javascript |
You are tasked with implementing a callback system for a particle simulation software. The software, named WARPX, provides five callback functions that can be assigned to Python functions. These callback functions are used at different stages of the simulation to execute user-defined Python code. The callback functions... | ```python
class CallbackManager:
def __init__(self):
self.callbacks = {
'particlescraper': None,
'particleloader': None,
'beforestep': None,
'afterstep': None,
'afterrestart': None
}
def register_callback(self, stage, callback_func):
... | magicoder | python |
You are tasked with implementing a Python class that simulates a simple banking system. The class should be able to create bank accounts, deposit funds, withdraw funds, and provide the account balance. Additionally, the class should be able to transfer funds between two accounts.
Your task is to complete the implement... | ```python
# Test the BankingSystem class
import unittest
class TestBankingSystem(unittest.TestCase):
def test_create_account(self):
bank = BankingSystem()
bank.create_account("12345", 100.0)
self.assertEqual(bank.get_balance("12345"), 100.0)
def test_deposit(self):
bank = Banki... | magicoder | python |
You are tasked with creating a utility function to convert a given height in pixels to a corresponding height in a device-independent pixel (dp) unit. The function should take the height in pixels as input and return the equivalent height in dp. The conversion formula from pixels to dp is as follows:
dp = px / (dpi / 1... | ```javascript
function convertPixelsToDp(px, dpi) {
return Math.round(px / (dpi / 160));
}
// Test cases
console.log(convertPixelsToDp(60, 320)); // Output: 20
console.log(convertPixelsToDp(100, 480)); // Output: 33
``` | magicoder | javascript |
You are working on a distributed computing system that processes data in parallel across multiple nodes. Your task is to implement a class that manages the distribution of data across these nodes. The class has the following attributes and methods:
Attributes:
- `total_number_of_windows`: An integer representing the t... | ```python
class DistributedDataProcessor:
def __init__(self, total_number_of_windows, shard_size, window, length, batch_size, max_num_of_pulses_in_a_wind):
self.total_number_of_windows = total_number_of_windows
# Adjust shard size to ensure equal distribution
if self.total_number_of_windows ... | magicoder | python |
You are tasked with implementing a Python class that simulates a simple banking system. The class should be able to create accounts, deposit funds, withdraw funds, and provide an account summary.
Create a Python class called `BankAccount` with the following methods:
1. `__init__(self, name, balance)`: Initializes the ... | ```python
class BankAccount:
def __init__(self, name, balance):
self.name = name
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if self.balance >= amount:
self.balance -= amount
else:
prin... | magicoder | python |
You are tasked with implementing a Python function that parses a given list of tuples representing asynchronous function signatures and returns a dictionary containing the function names as keys and their corresponding return types as values. Each tuple in the input list consists of the function name (as a string), the... | ```python
from typing import List, Tuple, Dict, Union, Optional, Awaitable
def parse_async_function_signatures(async_functions: List[Tuple[str, List[type], Optional[str]]]) -> Dict[str, Union[type, Awaitable[type]]]:
parsed_signatures = {}
for function_name, param_types, return_type in async_functions:
... | magicoder | python |
You are tasked with implementing a function to convert a given GUID (Globally Unique Identifier) string into its corresponding binary representation. A GUID is a 128-bit value typically represented as a sequence of 32 hexadecimal digits grouped into five parts in the form of 8-4-4-4-12 for a total of 36 characters (32 ... | ```python
def guidToBinary(guid_str):
hex_str = guid_str.replace("-", "") # Remove hyphens from the GUID string
hex_bytes = bytes.fromhex(hex_str) # Convert the hexadecimal string to bytes
return hex_bytes
```
The `guidToBinary` function first removes the hyphens from the input GUID string using the `rep... | magicoder | python |
You are tasked with implementing a program that calculates the factorial of a given non-negative integer using the `java.math.BigDecimal` class. The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. For example, the factorial of 5 (denoted as 5!) is 5 * 4 * 3 * 2 * 1... | ```java
import java.math.BigDecimal;
public class FactorialCalculator {
public static BigDecimal calculateFactorial(int n) {
if (n < 0) {
throw new IllegalArgumentException("Input must be a non-negative integer");
}
BigDecimal result = BigDecimal.ONE;
for (int i = 1; i <... | magicoder | java |
You are tasked with creating a Python script to process a dataset and generate BERT embeddings for different text types using the BERT model. The dataset is related to pharmaceuticals and is stored in a specific format. Your script should take into account the dataset path, file names, text types, and other relevant pa... | ```python
import subprocess
def generate_bert_embeddings(dataset, data_path, data_files, text_types):
bert_embeddings = {}
for text_type in text_types:
command = f"python3 src/get_bert_emb.py --entities_tsv {data_path}/entities.tsv --texts_dict {data_path}/texts.dict --text_type {text_type}"
su... | magicoder | python |
You are tasked with creating a Python function that takes a list of integers as input and returns the maximum sum of a contiguous subarray within the input list. A contiguous subarray is a subarray in which the elements are adjacent in the original list. For example, in the list [1, -2, 3, 4, -1, 2, 1, -5, 4], the cont... | ```python
from typing import List
def max_subarray_sum(arr: List[int]) -> int:
max_sum = float('-inf')
current_sum = 0
for num in arr:
current_sum = max(num, current_sum + num)
max_sum = max(max_sum, current_sum)
return max_sum
```
The `max_subarray_sum` function initializes ... | magicoder | python |
You are tasked with implementing a ContactAttributes class in Swift that manages contact information. The class should have properties for email, phone number, and content description, and should provide methods to set and retrieve these properties. Additionally, the class should support setting keywords for the contac... | ```swift
class ContactAttributes {
var email: String = ""
var phone: String?
var supportsPhoneCall: Int = 0
var contentDescription: String = ""
func setEmail(_ email: String) {
self.email = email
}
func setPhone(_ phone: String?) {
self.phone = phone
}
... | magicoder | swift |
You are tasked with implementing a simplified version of a 3D game engine in C++. The engine will have a class `D3DEngineImpl` that needs to be defined and implemented. The `D3DEngineImpl` class will serve as the core component of the 3D engine and will be responsible for managing the rendering pipeline, handling input... | ```cpp
#include <iostream>
namespace sjb {
class D3DEngineImpl {
public:
D3DEngineImpl() {
// Initialize 3D engine resources and components
// ...
std::cout << "D3D Engine Initialized" << std::endl;
}
// Other member functions for managing the 3D eng... | magicoder | cpp |
You are tasked with implementing a custom neural network layer for a natural language processing (NLP) model. The layer will include token and positional embeddings, as well as a series of stacked transformer layers. The token embeddings will be initialized with a normal distribution, and the positional embeddings will... | ```python
import torch.nn as nn
from apex.normalization import FusedLayerNorm
class CustomNLPModelLayer(nn.Module):
def __init__(self, num_tokens, seq_len, dim, sparse_attn, depth, use_layer_norm):
super(CustomNLPModelLayer, self).__init__()
self.seq_len = seq_len
self.token_emb = nn.Embe... | magicoder | python |
You are given a code snippet that defines a data structure for mapping superkey positions to subkey positions and vice versa. The code snippet includes declarations for `key_to_subkey`, `subkey_to_key`, and `removed_positions`. Your task is to implement a function that efficiently updates these data structures based on... | ```cpp
#include <vector>
#include <string>
#include <tuple>
#include <algorithm>
#include <bitset>
using key_pos_t = int;
using subkey_mask_t = std::bitset<64>; // Assuming a maximum of 64 positions
std::tuple<std::vector<key_pos_t>, std::vector<key_pos_t>, subkey_mask_t> updateMappings(
const std::vector<key_pos... | magicoder | cpp |
You are tasked with implementing a file download manager in C++ using the Qt framework. The given code snippet is a part of the download manager's functionality. The code sets up a network request to download a file in chunks using the HTTP Range header. Your task is to complete the implementation of the file download ... | ```cpp
void handleDataChunk(QNetworkReply *reply) {
if (reply->error() != QNetworkReply::NoError) {
qDebug() << "Error: " << reply->errorString();
return;
}
QString fileName = "downloaded_file"; // Set the desired file name
QFile file(fileName);
if (!file.open(QIODevice::WriteOnly |... | magicoder | cpp |
You are tasked with creating a Python function that can validate the correctness of a given mathematical expression. The expression will consist of integers, arithmetic operators (+, -, *, /), and parentheses. Your function should return True if the expression is valid and False if it is not.
Your task is to implement... | ```python
def validate_expression(expression: str) -> bool:
stack = []
opening_brackets = "({["
closing_brackets = ")}]"
bracket_pairs = {')': '(', '}': '{', ']': '['}
for char in expression:
if char in opening_brackets:
stack.append(char)
elif char in closing_brackets:
... | magicoder | python |
You are tasked with creating a program that utilizes the Boost C++ library to perform pattern matching using regular expressions. Your program should take a user input string and a regular expression pattern, and then output all the matches found in the input string based on the provided pattern.
Your program should i... | ```cpp
#include <iostream>
#include <boost/xpressive/xpressive.hpp>
int main() {
std::string inputString, regexPattern;
// Prompt user for input string and regular expression pattern
std::cout << "Enter the input string: ";
std::getline(std::cin, inputString);
std::cout << "Enter the regu... | magicoder | cpp |
You are tasked with creating a Django view that retrieves historical data for a specific content type and device. The view should handle GET requests and return a status code of 200 if the data is successfully retrieved. You are given a code snippet that creates a device object using the `mommy.make` method and then ma... | ```python
from django.http import JsonResponse, HttpResponseNotFound
from django.shortcuts import get_object_or_404
from .models import HistoricalData, ContentType, Device
def history_view(request, content_type_pk, device_pk):
content_type = get_object_or_404(ContentType, pk=content_type_pk)
device = get_objec... | magicoder | python |
You are tasked with implementing a class for a GUI application in C++. The class, `gui_application`, is a subclass of `core_application` and has several member variables and a constructor. Your goal is to complete the implementation of the `gui_application` class by adding member functions to handle GUI-related functio... | ```cpp
#include <iostream>
class gui_application {
public:
gui_application(int32 argc, char* argv[], json const& argj, allocator_type alloc)
: core_application{ argc, argv, argj, alloc }
, m_window{ alloc }
, m_render_device{}
, m_imgui{}
, m_dockspace{ "##MainDockspace", tr... | magicoder | cpp |
You are tasked with creating a program that simulates a simple logging system similar to the one used by systemd. The program should accept log messages and log levels as input and then output the messages based on the specified log level.
Your program should accept the following log levels:
- "emerg" (emergency)
- "a... | ```python
import sys
log_levels = ["emerg", "alert", "crit", "err", "warning", "notice", "info", "debug"]
def log_simulator(log_level):
if log_level not in log_levels:
print("Invalid log level")
return
while True:
message = input("Input log message: ")
if message.lower() == "e... | magicoder | python |
You are tasked with implementing a service interface for a recording application that provides methods to retrieve recording application details by their IDs. The interface `RecordingApplicationDetailService` contains two methods: `getByIds` and `getByIdsIncludeAllRelations`. Your task is to implement these methods in ... | ```java
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
public class RecordingApplicationDetailServiceImpl implements RecordingApplicationDetailService {
// Assume RecordingApplicationDetail class is defined elsewhere
// Implementing the getByIds method
@Override
public M... | magicoder | java |
You are tasked with implementing a function that constructs a network request based on the provided parameters. The function should handle different HTTP methods, path templates, request bodies, and content types. Your goal is to create a robust implementation that accurately constructs the network request based on the... | ```swift
func constructNetworkRequest(baseURL: String, method: String, pathTemplate: String, body: Any, contentTypes: [String]) -> URLRequest? {
guard let url = URL(string: baseURL + pathTemplate) else { return nil }
var request = URLRequest(url: url)
request.httpMethod = method
// Serialize r... | magicoder | swift |
You are tasked with implementing a function that checks whether a given HTML string contains a valid structure of opening and closing tags. The function should return true if the HTML is well-formed, and false otherwise.
The HTML tags are represented in the string using the following format:
- An opening tag starts wi... | ```python
def is_well_formed_html(html: str) -> bool:
stack = []
i = 0
while i < len(html):
if html[i] == '<':
if html[i+1] == '/':
if not stack or stack[-1] != html[i+2:i+html[i:].index('>')+2]:
return False
stack.pop()
... | magicoder | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.