query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with creating a Python class that simulates a simple recipe book. The class should have the ability to add recipes, retrieve recipes by name, and list all available recipes. Additionally, the class should be able to compare the expected ingredients and their quantities for a given recipe with the actual ...
```python class RecipeBook: def __init__(self): self.recipes = {} def add_recipe(self, name, ingredients): self.recipes[name] = ingredients def get_recipe(self, name): return self.recipes.get(name) def list_recipes(self): return list(self.recipes.keys()) def compa...
magicoder
python
You are tasked with creating a Django model for a social media platform that includes fields for user posts and comments. The model should have fields for the user's post content, the post's creation time, and the comment's creation time. Additionally, the model should automatically update the post's update time whenev...
```python from django.db import models class Post(models.Model): content = models.CharField(max_length=255) creation_time = models.DateTimeField(auto_now_add=True, verbose_name='Creation Time') update_time = models.DateTimeField(auto_now=True, verbose_name='Update Time') class Comment(models.Model): ...
magicoder
python
You are tasked with implementing a NullResultConverter class in C# that adheres to a specific interface. The IConvertsJintEvaluationResult interface is used for converting the result of a Jint evaluation, and the NullResultConverter class should wrap an existing implementation of this interface, providing a null result...
```csharp public class NullResultConverter : IConvertsJintEvaluationResult { private readonly IConvertsJintEvaluationResult _wrapped; public NullResultConverter(IConvertsJintEvaluationResult wrapped) { _wrapped = wrapped; } public object ConvertResult(object result) { if (resul...
magicoder
csharp
You are tasked with implementing a class for performing eQTL (expression quantitative trait loci) analysis. The class, named `eQTLAnalyzer`, has the following attributes and methods: Attributes: - `annot`: a DataFrame containing annotation information, with a column 'pos' representing positions. - `dosages`: a DataFra...
```python import pandas as pd class eQTLAnalyzer: def __init__(self, annot, dosages, gene_name): self.annot = annot self.dosages = dosages ordering = self.annot['pos'].argsort() self.annot = self.annot.iloc[ordering, :] self.dosages = self.dosages.iloc[ordering, :] s...
magicoder
python
You are tasked with implementing a generic function that takes a vector of any type and returns the maximum value in the vector. The function should be able to handle vectors of integers, floats, or any other comparable types. You need to define the function signature and implement the function to achieve this function...
```rust fn find_max_value<T: PartialOrd>(values: Vec<T>) -> Option<T> { if values.is_empty() { return None; } let mut max_value = values[0]; for value in values { if value > max_value { max_value = value; } } Some(max_value) } ```
magicoder
rust
You are tasked with designing a system to manage the sub-systems of an active building model. The building model includes the following sub-systems: HVAC, Lift Control, Lighting, Security, Smart Energy (Solar Panels), and Miscellaneous Functions. Each sub-system has specific requirements and functionalities that need t...
```python class BuildingModel: def __init__(self): self.sub_systems = {} def add_sub_system(self, sub_system_name, sub_system): self.sub_systems[sub_system_name] = sub_system def activate_sub_system(self, sub_system_name): if sub_system_name in self.sub_systems: self.su...
magicoder
python
You are tasked with implementing a user management system that involves enabling and disabling user aliases, as well as changing user passwords. The system provides a `UserManager` class with various methods for managing user accounts. The code snippet provided demonstrates the usage of the `UserManager` class to perfo...
```python class UserManager: def __init__(self, **kwargs): # Initialize the UserManager with any necessary configurations from kwargs self.configurations = kwargs def alias_disable(self, alias: str): # Disable the specified alias for the user # Implementation logic to disable th...
magicoder
python
You are tasked with creating a class that represents a participant in a replay game. The class should have properties for the participant's ID, summoner ID, summoner name, champion ID, and team ID. Your goal is to implement the class with the required properties and ensure that certain constraints are met. Create a C#...
```csharp using System; using FluentNHibernate.Mapping; public class ReplayGameParticipant { public virtual Guid Id { get; set; } public virtual int SummonerId { get; set; } public virtual string SummonerName { get; set; } public virtual int ChampionId { get; set; } public virtual int TeamId { get;...
magicoder
csharp
You are working on a continuous integration (CI) system, and you need to write a script to clean up certain files and directories before a build process. The script should remove specific files and directories from the build directory to ensure a clean environment for the build. You are given the following code snippe...
```bash #!/bin/bash # Check if $TRAVIS_BUILD_DIR is set and not empty if [ -n "$TRAVIS_BUILD_DIR" ]; then # Remove the .travis.yml file if [ -f "$TRAVIS_BUILD_DIR/.travis.yml" ]; then rm -f "$TRAVIS_BUILD_DIR/.travis.yml" fi # Remove all other files and directories in the build directory if [ -d "$TRAVI...
magicoder
shell
You are tasked with implementing a learning rate scheduler for a machine learning model. The learning rate scheduler should reduce the learning rate by a factor of 'gamma' every 'step_size' epochs. Your task is to write a function that takes the initial learning rate, gamma, and step_size as input and returns a learnin...
```python def create_scheduler(initial_lr, gamma, step_size): def scheduler(epoch): return initial_lr * (gamma ** (epoch // step_size)) return scheduler ``` The `create_scheduler` function takes the initial learning rate, gamma, and step_size as input and returns a scheduler function. The scheduler fun...
magicoder
python
You are tasked with creating a Python class that simulates a simple banking system. The class should have methods to initialize an account, deposit funds, withdraw funds, and check the balance. Additionally, the class should have a class method to set up the initial bank balance. Your task is to complete the implement...
```python class BankAccount: bank_balance = 0 # Class variable to store the initial bank balance @classmethod def setUpClass(cls, initial_balance): # Set the initial bank balance cls.bank_balance = initial_balance def __init__(self, account_number, initial_deposit): # Initiali...
magicoder
python
You are tasked with implementing a simplified version of a function reference wrapper in C++. The `function_ref` class is designed to store a reference to a function, allowing it to be called later. Your task is to complete the implementation of the `function_ref` class by providing the necessary member functions to st...
```cpp #include <iostream> #include <utility> template <typename Signature> class function_ref; template <typename R, typename... Args> class function_ref<R(Args...)> { public: function_ref() = delete; template <typename F> function_ref(F&& f) : erased_object(nullptr), erased_function(nullptr) { ...
magicoder
cpp
You are tasked with creating a function that processes and generates HTML code for a form to select resources and their units. The function should take an array of resources and their available units as input and produce the corresponding HTML code. The function should have the following signature: ```php function gen...
```php function generateResourceForm(array $resources): string { $html = ''; foreach ($resources as $name => $resource) { $html .= '<select style="max-width: 75px" name="resources['.$name.'][unit]">'; foreach ($resource['AvailableUnits'] as $key => $val) { $selected = ($resource['Uni...
magicoder
php
You are tasked with implementing a simple key-value store using Java. Your goal is to create a class that allows for the storage and retrieval of objects based on unique keys. The class should be thread-safe and capable of handling concurrent access. You are provided with a partial code snippet for a Java class called...
```java package com.nonelonely.config; import org.springframework.stereotype.Component; import java.util.concurrent.ConcurrentHashMap; @Component public class GlobalContext { private static ConcurrentHashMap<String, Object> applicationContext = new ConcurrentHashMap<>(100); public void setApplicationObj(St...
magicoder
java
You are given a series of assignments to a variable `num` in a Python program. Each assignment updates the value of `num`. Your task is to write a Python function that takes a list of such assignments and returns the final value of `num` after all the assignments have been executed. The input to the function will be a...
```python from typing import List def final_value_of_num(assignments: List[str]) -> int: num = 0 # Initial value of num for assignment in assignments: exec(assignment) # Execute the assignment return num ``` The `final_value_of_num` function initializes `num` to 0 and then iterates through the l...
magicoder
python
You are tasked with creating a program to manage employee attendance records. The program should be able to read a file containing the attendance data and perform various operations on it. The attendance data is stored in a CSV file with the following format: ``` NIP,Tanggal Masuk,Jam Keluar,Keterangan 12345,2022-01-0...
```python import csv from datetime import datetime def read_attendance_data(file_path): with open(file_path, 'r') as file: reader = csv.DictReader(file) return list(reader) def early_departures_count(attendance_data, date): return sum(1 for record in attendance_data if record['Tanggal Masuk'] ...
magicoder
python
You are tasked with creating a Java class that utilizes the Jackson library to serialize a given object into a JSON string. The class should be able to handle various types of objects and produce the corresponding JSON representation. Your task is to implement the `JsonSerializer` class with a method `serializeObject` ...
```java import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.List; import java.util.Map; public class JsonSerializer { private final ObjectMapper objectMapper; public JsonSerializer() { this.objectMapper = new ObjectMapper();...
magicoder
java
You are tasked with implementing a Python class method that calculates the size of a recurrent neural network (RNN) based on certain conditions. The method should return the size of the RNN based on the following rules: 1. If the `_rnn_size` attribute of the class is set, the method should return the value of `_rnn_si...
```python class RNNCalculator: def __init__(self, rnn_size=None, encoder_projection=None, encoders=None): self._rnn_size = rnn_size self._encoder_projection = encoder_projection self.encoders = encoders def calculate_rnn_size(self): if self._rnn_size is not None: ret...
magicoder
python
You are working on a system that monitors an email inbox for messages with a specific subject and processes their contents. The system uses the IMAP protocol to connect to the email server and retrieve unread emails with the subject "OCRE". Once retrieved, the system extracts the text content from the emails and proces...
```python def get_email_contents(email: str, token: str, secret_token: str) -> None: # Example implementation: Extract specific information from email content and process using tokens # This is a placeholder and should be replaced with the actual implementation based on the specific requirements # Here, we ...
magicoder
python
You are given a code snippet that includes a function call `solution(n)` and some expected output values. Your task is to reverse-engineer the function `solution` based on the provided outputs and write a function that replicates its behavior. The function `solution` takes a single integer `n` as input and returns an ...
```python def reverse_engineer_solution(n): if n == 4: return 3 elif n == 10: return 23 elif n == 600: return 83700 else: # Implement the actual logic of the original solution function # based on the provided outputs pass ``` The provided code snippet doe...
magicoder
python
You are tasked with implementing a simple car engine simulation program. The program should model the behavior of a car engine, including starting, stopping, and running. The engine can be in one of three states: off, starting, or running. The engine starts in the "off" state and can transition to the "starting" state ...
```rust use std::thread; use std::time::Duration; struct Engine { state: String, } impl Engine { fn new() -> Engine { Engine { state: String::from("off") } } fn start(&mut self) { self.state = String::from("starting"); } fn update_state(&mut self) { thread::sleep(Dura...
magicoder
rust
You are tasked with implementing a function to parse and extract information from an XML file containing data about medical ultrasound devices. The XML file follows a specific format and contains details about various ultrasound devices. Your task is to write a C++ function that reads the XML file, extracts the relevan...
```cpp #include <iostream> #include <vector> #include <string> #include <tinyxml2.h> struct USDevice { std::string name; std::string manufacturer; int serialNumber; struct Probe { std::string type; std::string frequency; } probe; }; std::vector<USDevice> parseUSDevices(const std::s...
magicoder
cpp
You are tasked with implementing a Python function that calculates the total number of parameters in a convolutional neural network (CNN) model. The CNN model is defined using the PyTorch library, and the provided code snippet shows a part of the model definition. The function should take the model as input and return...
```python import torch.nn as nn def calculate_total_parameters(model): trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad) non_trainable_params = sum(p.numel() for p in model.parameters() if not p.requires_grad) total_params = trainable_params + non_trainable_params return ...
magicoder
python
You are tasked with creating a custom derive macro for a Rust struct that implements a specific trait. The trait requires the struct to have a method that calculates the sum of all its fields. Your task is to implement the custom derive macro that generates the necessary code to fulfill this requirement. You are given...
```rust use quote::quote; use syn::{Data, DeriveInput, Fields, Ident, parse_macro_input}; use proc_macro::TokenStream; #[proc_macro_derive(SumFields)] pub fn sum_fields_derive(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as DeriveInput); let struct_name = &input.ident; let sum...
magicoder
rust
You are tasked with creating a Python class that interacts with an external FemzipAPI for finite element analysis. The FemzipAPI provides methods for importing, exporting, and analyzing finite element models. Your task is to create a Python class that encapsulates the functionality of the FemzipAPI and provides a more ...
```python from .femzip_api import FemzipAPI class FemzipInterface: def __init__(self, api_key): try: self.api = FemzipAPI(api_key) except ConnectionError as e: print(f"Failed to connect to FemzipAPI: {e}") def import_model(self, file_path): try: self...
magicoder
python
You are tasked with writing a program to determine whether a given point lies within a polygon. The polygon is defined by a set of vertices, and the point is represented by its coordinates. The program should take the coordinates of the point and the vertices of the polygon as input and output whether the point lies wi...
```python def area(point_1, point_2, point_3): return abs(point_1[0] * (point_2[1] - point_3[1]) + point_2[0] * (point_3[1] - point_1[1]) + point_3[0] * (point_1[1] - point_2[1])) / 2 def get_coordinate(data): l = data.split(",") return tuple([int(c) for c in l]) def point_in...
magicoder
python
You are tasked with implementing a Java class that manages filtering and clearing of form fields for a data query application. The class, `FormManager`, should provide methods for filtering data based on user input and clearing the form fields when needed. The class should also support event handling for filter actions...
```java import java.util.Date; public class FormManager { private QueryField queryField; private DatePicker fromDatePicker; private DatePicker toDatePicker; public FormManager(QueryField queryField, DatePicker fromDatePicker, DatePicker toDatePicker) { this.queryField = queryField; thi...
magicoder
java
You are tasked with implementing a function to generate file fragments based on a given file extension. The function should take the file extension as input and return a list of file fragments that match the extension. The function signature is: ```python def make_frags(extension: str) -> List[str]: pass ``` For ...
```python from typing import List import os def make_frags(extension: str) -> List[str]: file_fragments = [] fragment_number = 1 while True: fragment_name = f"{fragment_number}.{extension}" if os.path.exists(fragment_name): file_fragments.append(fragment_name) fragme...
magicoder
python
You are tasked with creating a function that will analyze a given code snippet and count the occurrences of specific methods within the code. The code snippet will be provided as a string, and the methods to be counted will also be provided as an array of strings. Your function should return a dictionary where the keys...
```swift func countMethodOccurrences(codeSnippet: String, methodsToCount: [String]) -> [String: Int] { var methodCounts: [String: Int] = [:] for method in methodsToCount { let pattern = "\(method)\\(\\)" let regex = try! NSRegularExpression(pattern: pattern, options: []) let matches = r...
magicoder
swift
You are tasked with implementing a Python decorator that logs the details of variable assignments within a function. The decorator should capture the line number, column number, and the assigned value for each assignment statement within the function. Your task is to create the `__report_assign` decorator and apply it ...
```python def __report_assign(lineno, col, v): def decorator(func): def wrapper(*args, **kwargs): source_lines = inspect.getsourcelines(func)[0] source_lines = source_lines[1:] # Exclude the decorator line for i, line in enumerate(source_lines): if ':=' i...
magicoder
python
You are tasked with writing a program to find the final Fibonacci number based on the first and last letters of a given surname. The final Fibonacci number is obtained by adding the Fibonacci numbers corresponding to the positions of the first and last letters of the surname. To achieve this, you need to follow these ...
```python def fibonacci(n): if n <= 0: return 0 elif n == 1: return 1 else: a, b = 0, 1 for _ in range(2, n + 1): a, b = b, a + b return b def final_fibonacci_number(surname): first_letter_position = ord(surname[0].lower()) - 96 # Convert first lette...
magicoder
python
You are tasked with implementing a function to perform pairwise bilateral filtering on an input image. Bilateral filtering is a non-linear, edge-preserving, and noise-reducing smoothing filter for images. The function `addPairwiseBilateral` takes several parameters to control the filtering process: - `sxy`: The spatia...
```python from PIL import Image, ImageFilter def addPairwiseBilateral(sxy: int, srgb: int, rgbim: Image, compat: int) -> Image: return rgbim.filter(ImageFilter.SMOOTH_MORE) ``` In this solution, the `addPairwiseBilateral` function uses the `filter` method from the Python Imaging Library (PIL) to apply a simple sm...
magicoder
python
You are given a list of integers representing the daily stock prices of a company. Your task is to write a function to calculate the maximum profit that can be obtained by buying and selling the stock at most once. If it is not possible to make any profit, the function should return 0. For example, given the input lis...
```python from typing import List def maxProfit(prices: List[int]) -> int: if not prices: return 0 max_profit = 0 min_price = prices[0] for price in prices: if price < min_price: min_price = price else: max_profit = max(max_profit, price - min_price) ...
magicoder
python
You are tasked with implementing a Python class that manages the scheduling of events. The class should allow for the scheduling of a single event to occur at a specified time, with the option to repeat the event at regular intervals. The class should also support the persistence of scheduled events across different pr...
```python from datetime import datetime, timedelta import pickle class EventScheduler: def __init__( self, should_repeat: bool = False, time_until_repeat: timedelta = None, accurate_repeat: bool = True, persist_across_zone_loads: bool = False ): self.started_at_d...
magicoder
python
You are tasked with creating a Python class that represents a rating system for champions in the popular online game League of Legends. The provided code snippet shows the creation of two specific classes, `NA_Quinn_Top_Heimerdinger` and `NA_Quinn_Top_Illaoi`, which inherit from a base class `Ratings`. Your task is to ...
```python class Ratings: def __init__(self): self.ratings = {} def initialize_rating(self, region, position, champion, initial_rating): if region not in self.ratings: self.ratings[region] = {} if position not in self.ratings[region]: self.ratings[region][position...
magicoder
python
You are tasked with implementing a recursive division algorithm to generate a maze with rooms. The algorithm should take a grid representing the maze and divide it recursively to create rooms and corridors. Each room should be surrounded by walls, and corridors should connect the rooms. The algorithm should stop dividi...
```java public class RecursiveDivisionWithRooms { public void generateMazeWithRooms(MazeGrid maze, int rows, int cols, int minRoomSize) { divideAndConquer(maze, 0, 0, rows - 1, cols - 1, minRoomSize); } private void divideAndConquer(MazeGrid maze, int startRow, int startCol, int endRow, int endCol,...
magicoder
java
You are tasked with creating a RESTful API endpoint for updating a city record in a database. The existing code snippet is from a Laravel controller method responsible for handling the update operation. The `edit` method is used to retrieve the city data based on its ID and return it as a JSON response. Your task is t...
```php public function update(Request $request, $id) { $city = City::find($id); if ($city) { $city->name = $request->input('name'); $city->population = $request->input('population'); $city->save(); return response()->json(["message" => "City updated successfully", "city" => $ci...
magicoder
php
You are tasked with implementing a class that manages a list of employee tasks. The class should provide methods to add, remove, and retrieve tasks, as well as to calculate the total time spent on tasks for a given employee. You are given a partial code snippet for the `EmployeeTaskManager` class, which includes a pri...
```java import java.util.ArrayList; import java.util.List; public class EmployeeTaskManager { private List<EmployeeTask> employeeTaskList = new ArrayList<>(); public Long getId() { return id; } public void addTask(EmployeeTask task) { employeeTaskList.add(task); } public void...
magicoder
java
You are tasked with creating a custom caching mechanism for a PHP application using the PSR-16 Simple Cache interface. The cache should support the ability to store and retrieve data, as well as handle cache expiration. Additionally, you need to implement a class that utilizes the Tebru Gson library to serialize and de...
```php use Psr\SimpleCache\CacheInterface; use Tebru\Gson\Annotation\VirtualProperty; use Tebru\Gson\Gson; use Tebru\Gson\Internal\AccessorMethodProvider; class CustomCache implements CacheInterface { private $cache = []; public function get($key, $default = null) { if (!$this->has($key)) { ...
magicoder
php
You are tasked with simulating the growth of a cellular automaton using a given set of rules. The cellular automaton is represented as a one-dimensional array of cells, where each cell can be in one of two states: alive ('#') or dead ('.'). The growth of the automaton is determined by applying a set of rules to each ge...
```python class Cell: def __init__(self, value, index): self.value = value self.index = index self.next = None def grow(current, rules): next_generation = ['.'] * len(current) for i in range(1, len(current) - 1): pattern = current[i-1:i+2] next_generation[i] = rules....
magicoder
python
You are tasked with creating a Java program that processes movie recommendation data using a collaborative filtering algorithm. The program should read user and item models from specified files, perform matrix predictions, and write the results to an output file. Your program should accept the following command-line a...
```java import java.io.File; import java.io.FileWriter; import java.io.IOException; public class MatrixPredictions { public static void main(String[] args) { if (args.length != 3) { System.err.println("Usage: java MatrixPredictions <userModelFile> <itemModelFile> <outputFile>"); Sys...
magicoder
java
You are tasked with creating a geolocation tracking feature for a React application. Your goal is to implement a custom hook that utilizes the browser's geolocation API to fetch the user's current coordinates. Additionally, you need to handle loading states and error scenarios. Your task is to create a custom React ho...
```javascript import { useState, useEffect } from "react"; const useGeolocation = () => { const [coordinates, setCoordinates] = useState<Coordinates | null>(null); const [error, setError] = useState<string | null>(null); const [isLoading, setIsLoading] = useState<boolean>(true); useEffect(() => { const su...
magicoder
javascript
You are tasked with implementing a class hierarchy for a content management system that models various types of online posts. The provided code snippet is a partial representation of a PHP class `BlogPosting` that extends another class `SocialMediaPosting`. Your task is to complete the class hierarchy by defining the m...
```php /** * A content post. */ class ContentPost { protected $title; protected $content; protected $author; public function __construct($title, $content, $author) { $this->title = $title; $this->content = $content; $this->author = $author; } public function getTitl...
magicoder
php
You are tasked with implementing a custom dataset class for image data manipulation in Python using the PyTorch library. Your goal is to create a class that loads test images and their corresponding labels for machine learning tasks. The dataset class should be able to handle image transformations and target transforma...
```python import torch from torch.utils.data import Dataset def get_test_img(): # Function to load test images and labels # Implement this function based on the specific data source pass class MyTestDataset(Dataset): def __init__(self, transform=None, target_transform=None): # Load test images...
magicoder
python
You are tasked with creating a command-line interface (CLI) tool to manage a distributed job scheduling system. The tool should be able to interact with the system's Raft consensus protocol to list the peers connected to the system. Your task is to implement a function that takes the following inputs: - `command`: A s...
```python import subprocess def executeCommand(command, rpcAddr): fullCommand = f"/dkron/dkron {command} --rpc-addr {rpcAddr}" process = subprocess.Popen(fullCommand, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, error = process.communicate() if error: return error.decode(...
magicoder
python
You are tasked with implementing a function to serialize an HTML tag node into a writer. The HTML tag node is represented by the `HtmlTagNode` struct, which contains the tag name, attributes, and child nodes. The `HtmlTagNode` struct is defined as follows: ```rust struct HtmlTagNode { tag: String, attrs: Vec<(...
```rust use std::io::{self, Write}; struct Context { // Define the context struct as needed } enum HtmlNode { Text(String), Tag(HtmlTagNode), } struct HtmlTagNode { tag: String, attrs: Vec<(String, String)>, children: Vec<HtmlNode>, } impl HtmlTagNode { pub fn write(&self, context: &Cont...
magicoder
rust
You are tasked with implementing a module resolution system for a JavaScript project. The project has a directory structure where each module is represented by a file, and modules can be organized into subdirectories. The module resolution system should be able to resolve and export modules based on their file paths. ...
```javascript function resolveModuleExports(entryFileCode) { const moduleRegex = /export { default as (\w+) } from '(.+?)'/g const resolvedModules = {} let match while ((match = moduleRegex.exec(entryFileCode)) !== null) { const moduleName = match[1] const filePath = match[2] resolvedModules[module...
magicoder
javascript
You are tasked with implementing a function to calculate the total number of elements in a multi-dimensional array. The function should take the array as input and return the total number of elements present in the array, considering all dimensions. You are provided with a code snippet that demonstrates a test case fo...
```python def calculate_total_elements(arr): total_elements = 1 for dim in arr: if isinstance(dim, list): total_elements *= len(dim) return total_elements ``` The `calculate_total_elements` function initializes `total_elements` to 1 and iterates through the dimensions of the input array...
magicoder
python
You are tasked with implementing a battery state-of-charge (SoC) management system for a renewable energy system. The system consists of a battery, grid connection, and photovoltaic (PV) generation. The provided code snippet is a part of the battery SoC management model, specifically focusing on the increase in battery...
```python # Complete the battery SoC management model by adding the increase in battery SoC from PV generation def complete_battery_soc_model(self): minutes_per_hour = 60 # Define the number of minutes in an hour pv_charging_power_limit = self.energy_system.energy_storage.pv_charging_power_limit # Get the PV ...
magicoder
python
You are tasked with implementing a string calculator class in C# that can handle negative numbers and custom delimiters. The string calculator should be able to handle negative numbers by throwing an exception and should also support custom delimiters. Your task is to complete the implementation of the `StringCalculat...
```csharp using System; using System.Collections.Generic; using System.Linq; namespace Katarai.Acceptance.StringCalculator.Tests.SpecificTestNegativeNumbers { public class StringCalculator : IStringCalculator { private static readonly List<string> Delimiters = new List<string> { ",", "\n" }; p...
magicoder
csharp
You are tasked with implementing a function to parse TLVs (Type-Length-Value) into a request list for a WiFi P2P (Peer-to-Peer) service. TLVs are a common method for encoding data in networking protocols, where each TLV consists of a type field, a length field, and a value field. You are given a class `WifiP2pServiceR...
```cpp #include <vector> struct WifiP2pServiceRequest { unsigned char type; std::vector<unsigned char> value; }; class WifiP2pServiceRequestList { public: std::vector<WifiP2pServiceRequest> requestList; void ParseTlvs2ReqList(const std::vector<unsigned char> &tlvs) { size_t index = 0; ...
magicoder
cpp
You are tasked with creating a Python script that parses a given code snippet and extracts specific information from it. The code snippet represents a configuration file for a C++ project, and your script needs to extract the following details: 1. Description: The description of the project. 2. URL: The URL of the pro...
```python import re code_snippet = """ description = "A tiny, URL-friendly, unique string ID generator for C++, implementation of ai's nanoid!" url = "https://github.com/pss146/nanoidxx" homepage = "https://github.com/pss146/nanoidxx" author = "<NAME> <<EMAIL>>" license = "MIT" settings = "os", "compiler", "build_typ...
magicoder
python
You are tasked with implementing a simple dependency injection system for a game engine. The provided code snippet is a simplified representation of a dependency injection setup using the Unity game engine and the Zenject framework. The `PlayerWorldView` class is responsible for displaying the player's world view and d...
```csharp // Dependency Injection Container public class DIContainer { private Dictionary<Type, object> dependencies = new Dictionary<Type, object>(); public void Register<T>(T dependency) { dependencies[typeof(T)] = dependency; } public T Resolve<T>() { if (dependencies.TryGet...
magicoder
csharp
You are tasked with implementing a class for managing posting members in a group. The class, `PostingMember`, is responsible for checking whether a user can post in a given group based on certain conditions. The code snippet provided is a unit test for the `PostingMember` class. Your task is to implement the `PostingMe...
```python class PostingMember: def __init__(self, user, group): self.user = user self.group = group def check(self): # Implement the logic to check whether the user can post in the group # This could involve checking user permissions, group settings, etc. # For the purpo...
magicoder
python
You are tasked with implementing a class that manages a list of test cases for a testing framework. The class should provide methods to add test cases, run all test cases, and report the results. Each test case is represented by a closure that performs a specific test and returns a boolean indicating success or failure...
```swift class TestManager { private var testCases: [() -> Bool] = [] func addTestCase(_ testCase: @escaping () -> Bool) { testCases.append(testCase) } func runAllTests() -> (passed: Int, failed: Int) { var passedCount = 0 var failedCount = 0 for testCase in testCases {...
magicoder
swift
You are tasked with implementing a function that calculates the momentum of an optimizer used in a machine learning framework. The momentum of an optimizer is a crucial parameter that influences the convergence and stability of the training process. The momentum value is calculated based on the optimizer's configuratio...
```python from typing import Union from torch.optim.optimizer import Optimizer def get_optimizer_momentum(optimizer: Optimizer) -> Union[float, None]: if hasattr(optimizer, 'param_groups') and isinstance(optimizer.param_groups, list) and len(optimizer.param_groups) > 0: momentum = optimizer.param_groups[0]...
magicoder
python
You are tasked with implementing a data structure to efficiently store and retrieve currency information. The data structure should support adding currency names and their corresponding plural forms, as well as any associated abbreviations. Additionally, the structure should allow for efficient retrieval of currency in...
```javascript class CurrencyDictionary { constructor() { this.currencyMap = new Map(); } addCurrency(name, pluralForms, abbreviations) { this.currencyMap.set(name, { pluralForms, abbreviations }); const pluralArray = pluralForms.split("|"); pluralArray.forEach((plural) => { this.currencyMap...
magicoder
javascript
You are tasked with creating a Python function that processes a list of parameters, performs a series of calculations, and then parses the results. The function will interact with external modules and handle file operations. Your task is to implement the function `process_and_parse` according to the following specifica...
```python import shutil import os def process_and_parse(param_list, param_keys, mean_params, scale_params, filename, cwd, mndo, binary): # Set params in worker dir data.set_params(param_list, param_keys, mean_params, scale_params, scr=cwd) # Calculate properties properties_list = mndo.calculate_file(f...
magicoder
python
You are tasked with creating a Python package that simulates a simple banking system. The package should include modules for managing accounts, transactions, and customer information. Your task is to implement the necessary classes and functions for the banking package. Your package should have the following structure...
```python # banking_package/accounts/account.py class Account: def __init__(self, account_number, account_type, balance): self.account_number = account_number self.account_type = account_type self.balance = balance def deposit(self, amount): self.balance += amount def withd...
magicoder
python
You are tasked with implementing a type trait to determine whether a given type is an arithmetic type or not. An arithmetic type is defined as a fundamental type that represents numbers and supports arithmetic operations such as addition, subtraction, multiplication, and division. Examples of arithmetic types include i...
```cpp #include <iostream> // Primary template for is_arithmetic trait template <typename T> struct is_arithmetic { static constexpr bool value = false; }; // Specializations for arithmetic types template <> struct is_arithmetic<int> { static constexpr bool value = true; }; template <> struct is_arithmetic<f...
magicoder
cpp
You are given a Python function that takes two parameters: `toneValue` and `p`. The function is designed to perform certain operations based on the values of `toneValue` and `p`, and it returns a tuple of two values. The function contains error checks and raises exceptions if certain conditions are not met. Your task i...
```python from typing import Tuple def process_tone(toneValue: int, p: int) -> Tuple[int, int]: if toneValue >= 0: if p > 9: raise ValueError('pitch value exceeds the maximum limit of 9. Please use a value 9 or below.') return toneValue % 12, p elif toneValue < 0: if p < -1:...
magicoder
python
You are tasked with creating a program that simulates a simple machine learning model training process. The model will be trained using a basic gradient descent algorithm to minimize a cost function. Your task is to implement the gradient descent algorithm and use it to train a linear regression model on a small datase...
```python import numpy as np # Initialize the dataset x = np.array([1, 2, 3, 4, 5]) y = np.array([2, 4, 6, 8, 10]) # Initialize the weights of the linear regression model with random values w0 = np.random.rand() w1 = np.random.rand() # Define the learning rate and maximum iterations learning_rate = 0.01 max_iteratio...
magicoder
python
You are tasked with creating a program that simulates a simple game of rock-paper-scissors. The program should allow a user to input their choice (rock, paper, or scissors), generate a random choice for the computer, determine the winner based on the choices, and display the result. Your program should follow these ru...
```python import random def get_user_choice(): while True: user_choice = input("Enter your choice (rock, paper, or scissors): ").lower() if user_choice in ["rock", "paper", "scissors"]: return user_choice else: print("Invalid choice. Please enter rock, paper, or scis...
magicoder
python
You are tasked with implementing a generic class that represents a simple asynchronous operation. The class should provide a method to start the operation and a property to retrieve the result once the operation is complete. You are given a code snippet that includes an empty class and a read-only property. Your task ...
```csharp using System; using System.Threading.Tasks; public class AsyncOperation<T> { private Func<Task<T>> _operation; private Task<T> _task; public AsyncOperation(Func<Task<T>> operation) { _operation = operation; } public async Task Start() { _task = _operation.Invoke(...
magicoder
csharp
You are tasked with implementing a class hierarchy for image transformations in a photo editing application. The application supports various image transformations, and you need to create a new transformation class called "ModulateTransform" that changes the brightness, saturation, and hue of an image. The "ModulateTr...
```swift // Define the base class for image transformations class Transform { // Properties and methods for image transformations // ... } // Define the ModulateTransform class inheriting from the Transform base class class ModulateTransform: Transform { var brightness: Double var saturation: Double ...
magicoder
swift
You are tasked with creating a Python program that simulates a data processing pipeline using asynchronous programming. The program should utilize asyncio to concurrently execute multiple data transformation tasks based on a given scan mode. The scan mode determines the type of data processing to be performed. Your ta...
```python import asyncio class Transformer: async def run(self, request_meta): # Simulate data transformation process print(f"Running data transformation for {request_meta}...") await asyncio.sleep(1) # Simulate asynchronous data processing print(f"Data transformation completed for...
magicoder
python
You are tasked with creating a program that manages Visual Studio project files. Your program should implement a class that stores the names of two example Visual Studio project files and provides methods to manipulate and retrieve this information. Create a class `VisualStudioProjectManager` with the following specif...
```csharp using System; using System.Collections.Generic; public class VisualStudioProjectManager { private string ExampleVisualStudioProjectFileName01; private string ExampleVisualStudioProjectFileName02; public VisualStudioProjectManager(string fileName01, string fileName02) { ExampleVisualS...
magicoder
csharp
You are tasked with creating a script to automate the code review process for a Java project using Checkstyle and Reviewdog. Checkstyle is a tool used to ensure that Java code adheres to a set of coding standards, and Reviewdog is a code review tool that can be integrated with version control systems. Your script shou...
```bash #!/bin/bash # Run Checkstyle for the Maven project mvn checkstyle:check -Dcheckstyle.failOnViolation=false > checkstyle.errors # Iterate through all checkstyle-result.xml files and run reviewdog for file in $(find . -name 'checkstyle-result.xml') do cat $file | reviewdog -f=checkstyle -diff="git diff inte...
magicoder
shell
You are tasked with implementing a matrix-vector multiplication algorithm using C++ and optimizing its performance using benchmarking. The given code snippet provides a starting point for the matrix-vector multiplication and the benchmarking setup. Your task is to complete the matrix-vector multiplication algorithm an...
```cpp #include <iostream> #include <vector> #include <benchmark/benchmark.h> // Matrix-vector multiplication function std::vector<double> matrixVectorMultiplication(const std::vector<std::vector<double>>& matrix, const std::vector<double>& vector) { int rows = matrix.size(); int cols = matrix[0].size(); s...
magicoder
cpp
You are tasked with creating a function that takes an image, encodes it to base64, and then uses a web view to execute JavaScript code to paste the image onto a web page. Your task is to implement the function `encodeAndPasteImage` in Swift, which takes an `imageData` of type `Data?` as input and returns a `String` rep...
```swift func encodeAndPasteImage(imageData: Data?) -> String { guard let imageData = imageData else { return "" // Return empty string if imageData is nil } let base64String = imageData.base64EncodedString(options: .lineLength64Characters) let javascriptCommand = "pasteImage('\(base64Stri...
magicoder
swift
You are tasked with creating a program that validates whether a given model name starts with a number. The model name is a string that can contain alphanumeric characters and underscores, but it must start with a letter or an underscore. Your program should take a model name as input and determine if it violates the ru...
```python def validate_model_name(model_name): if model_name[0].isdigit(): # Check if the first character is a digit return "Invalid model name" else: return "Valid model name" # Test cases print(validate_model_name("3D_model")) # Output: "Invalid model name" print(validate_model_name("model_...
magicoder
python
You are tasked with implementing a function that processes configuration data and performs a series of operations on a group within the configuration. The function should remove the specified group from the configuration, write the updated configuration to a file, and then return a success message along with a handler ...
```javascript const removeGroupAndWriteConfig = (groupname, config, opts) => { // Step 1: Remove the specified group from the configuration data const updatedConfig = removeGroup(groupname, opts.logger)(config.contents); // Step 2: Write the updated configuration to the file specified by config.path writeConfi...
magicoder
javascript
You are tasked with creating a Python program that interacts with a Twitter API to perform specific actions. The program takes command-line arguments and utilizes the `twoauth` library to access the Twitter API. The code snippet provided initializes the necessary credentials and then enters a loop to list direct messag...
```python import sys import twoauth consumer_key = sys.argv[1] consumer_secret = sys.argv[2] access_token = sys.argv[3] access_token_secret = sys.argv[4] user_id = sys.argv[5] api = twoauth.api(consumer_key, consumer_secret, access_token, access_token_secret) try: dms = api.dm_list(user_id=user_id) # Retrieve d...
magicoder
python
You are tasked with implementing a Weight-Balanced Tree (WBT) data structure in C++. The WBT is a self-balancing binary search tree that maintains a balance condition based on the weights of its nodes. The provided code snippet includes a partial implementation of the WBT, with a `clone` method for node cloning and a `...
```cpp #include <iostream> #include <vector> template <typename T> struct Monoid { T identity; T operator()(const T &a, const T &b) const { return a + b; } }; template <typename T> struct WeightBalancedTree { struct Node { T value; int weight; Node *left, *right; }; Node *root; // Other neces...
magicoder
cpp
You are tasked with implementing a simple cache mechanism for storing and retrieving key-value pairs. The cache should have a maximum capacity and support two operations: `put` to insert a new key-value pair and `get` to retrieve the value associated with a given key. When the cache reaches its maximum capacity, it sho...
```java import java.util.HashMap; import java.util.Map; class LRUCache { private int capacity; private Map<Integer, Node> cache; private Node head; private Node tail; public LRUCache(int capacity) { this.capacity = capacity; cache = new HashMap<>(); head = new Node(); ...
magicoder
java
You are tasked with implementing a simple interface hierarchy in a programming language of your choice. The interface hierarchy consists of three interfaces: `IPbxEvent`, `IRole`, and `IRoom`. Each interface has specific methods that need to be implemented by classes that implement these interfaces. Your task is to cr...
```java // Define the IPbxEvent interface interface IPbxEvent { void onPbxEvent(String event); } // Define the IRole interface interface IRole { void assignRole(String role); } // Define the IRoom interface interface IRoom { void bookRoom(String date); } // Implement the ConferenceRoom class that impleme...
magicoder
java
You are tasked with implementing a Python class for performing linear transformations. The class should be able to apply translation to a given input vector using the provided transformation matrix. Your task is to complete the implementation of the `Translation` class by adding the necessary code to apply the translat...
```python import numpy class LinearTransformation: def __init__(self): pass # Placeholder for the superclass initialization class Translation(LinearTransformation): def __init__(self, b): super(Translation, self).__init__() self.__b = numpy.array(b, dtype=_TYPE) # Initialize the tran...
magicoder
python
You are tasked with creating a character creation system for a role-playing game. The system should allow players to select a race and then display the corresponding stat modifiers for that race. The stat modifiers are applied to the base stats of Strength (Str), Dexterity (Dex), Constitution (Con), Intelligence (Int),...
```python def get_modified_stats(race, stats): modified_stats = dict(zip(["Str", "Dex", "Con", "Int", "Wis", "Cha"], stats)) if race == "human": return modified_stats elif race == "half-orc": modified_stats["Str"] += 2 modified_stats["Int"] -= 2 return modified_stats else...
magicoder
python
You are working on a machine learning project and need to create a custom data loader for your dataset. You have been provided with a code snippet that imports various modules related to data handling and transformation. Your task is to implement a custom data loader using the provided modules and classes. You are giv...
```python import pyblaze.nn.data.extensions from .noise import NoiseDataset from .transform import TransformDataset from .zip import ZipDataLoader class CustomDataLoader(ZipDataLoader): def __init__(self, original_dataset, noise_level, transformation): super().__init__(original_dataset) self.noise_...
magicoder
python
You are tasked with creating a program that compares two JSON files and identifies the differences between them. Your program should read two JSON files, compare their contents, and then output the differences in a human-readable format. The differences should include added, removed, and modified key-value pairs. Your...
```python import difflib import json def json_diff(file1_path, file2_path): with open(file1_path, 'r') as file1, open(file2_path, 'r') as file2: file1_data = json.load(file1) file2_data = json.load(file2) diff = difflib.unified_diff( json.dumps(file1_data, indent=2).splitlines(), ...
magicoder
python
You are tasked with implementing a simple search functionality for a web application. The given code snippet is a part of a Python Flask web application. The `app_env` object is used to configure the application environment, and the `assets` variable is added to the global environment. The `app` object represents the F...
```python from flask import Flask, render_template app = Flask(__name__) app_env.line_statement_prefix = "=" app_env.globals.update(assets=assets) # database = Database() @app.route("/") def index(): return render_template("index.html") @app.route("/search/<query>") def search(query): # Assuming parse_query...
magicoder
python
You are tasked with implementing a function that determines the return type of a given member of a class. The function should take in a member of the class (either a field, property, or method) and return its return type. The member can be represented as an object of type `FieldInfo`, `PropertyInfo`, or `MethodInfo` fr...
```csharp using System; using System.Reflection; public class MemberTypeResolver { public Type GetMemberReturnType(object info) { if (info is FieldInfo) { return ((FieldInfo)info).FieldType; } if (info is PropertyInfo) { return ((PropertyInfo)info...
magicoder
csharp
You are tasked with implementing a custom error handling system for a content management application. The system should be able to handle different types of errors and display them in a user-friendly manner. To achieve this, you need to create a class that can format and print error messages in different colors based o...
```swift class ErrorFormatter { func formatError(message: String, severity: String) { var formattedMessage = "" switch severity { case "error": formattedMessage = "\u{001B}[31m[Error] \(message)" case "warning": formattedMessage = "\u{001B}[33m...
magicoder
swift
You are tasked with implementing a Python class method that loads a UDPipe model based on the provided model directory and model name. The method should handle two different cases for the model name: either a specific filename within the model directory or a language string/prefix, in which case the largest UDPipe mode...
```python import os class UDPipeLoader: def __init__(self): self._modelfile = None def load_udpipe_model(self, model_dir, model_name): if not os.path.isdir(model_dir): raise ValueError(f"Not an existing directory: {model_dir}") self._modelfile = f"{model_dir}/{model_name}"...
magicoder
python
You are tasked with implementing a contract verification system for a blockchain application. The system will verify the correctness of a specific function call and raise an assertion error if the verification fails. You are given the following code snippet as a reference: ```python assert contract.foo(array, idx) ==...
```python class contract: def foo(self, array, idx): if idx < 0 or idx >= len(array): raise IndexError("Index out of bounds") return array[idx] ``` In the solution, the `contract` class is defined with a method `foo` that takes an array `array` and an index `idx` as input. It first chec...
magicoder
python
You are working on a project that involves using Amazon SageMaker, a cloud machine learning platform. To interact with SageMaker, you need to set up a virtual environment and activate it before running any commands. The code snippet provided is a common way to activate the virtual environment for SageMaker using the `s...
```python import subprocess def activate_sagemaker_venv(activation_script_path): try: subprocess.run(f"source {activation_script_path}", shell=True, check=True) print("SageMaker virtual environment activated successfully.") except subprocess.CalledProcessError as e: print(f"Error activa...
magicoder
python
You are tasked with implementing a Python class to model the spread of a disease within a population. The model should support stratification, which involves dividing the population into different groups based on certain characteristics, such as location or age, and tracking the disease spread within each group separat...
```python class Compartment: def __init__(self, name, initial_value): self.name = name self.initial_value = initial_value class TransitionFlow: def __init__(self, name, source_compartment, target_compartment, transition_rate): self.name = name self.source_compartment = source_co...
magicoder
python
You are tasked with simulating the positions of billiard balls on a pool table. The table is a regular hexagon with side length `side_length`, and the balls are placed at specific positions relative to the table. The x and z positions of the balls are calculated using the given code snippet. The variables `ball_diamete...
```python import numpy as np def calculate_ball_positions(side_length, ball_diameter, d, L_table): x_positions = np.concatenate([np.linspace(0, side_length, 5), np.linspace(ball_diameter + d, side_length, 4), np.linspace(2*(ball_diameter + d), sid...
magicoder
python
You are tasked with implementing a class that manages variant values for a product. The class should provide methods to add, update, and retrieve variant values, as well as a method to check if a specific variant combination exists. You are given the following code snippet as a reference for the property that stores t...
```csharp using System; using System.Collections.Generic; public class ProductVariantManager { private Dictionary<string, string> _variantValues; public ProductVariantManager() { _variantValues = new Dictionary<string, string>(); } public void AddVariantValue(string variantName, string va...
magicoder
csharp
You are tasked with implementing a generic data table builder in Java. The builder should be able to construct a data table that can hold any type of data and provide various operations for manipulating and accessing the data. You are given a partial code snippet for the `build` method of the data table builder: ```j...
```java public class EmfDataTableDiv<R> implements IEmfDataTableDiv<R> { private List<R> rows; public EmfDataTableDiv() { this.rows = new ArrayList<>(); } public void addRow(R row) { rows.add(row); } public void removeRow(int index) { if (index >= 0 && index < rows.siz...
magicoder
java
You are tasked with implementing a JavaScript function that simulates the behavior of the provided code snippet. The code snippet demonstrates the invocation of a JavaScript function using a custom `JSCall` object and its associated methods. Your task is to create a function that takes a JavaScript function `func` as a...
```javascript function simulateInvocation(func) { // Define the JSCall object with JSAttribute and JSThis methods const invoked = JSCall( JSAttribute(func, 'call'), [JSThis()] ); // Return the result of the invoked function return invoked; } ``` The `simulateInvocation` function ta...
magicoder
javascript
You are tasked with creating a custom attribute for ASP.NET MVC that will log the execution time of controller actions. The attribute should be applied to controller actions and should log the start and end times of the action, along with the elapsed time in milliseconds. You will need to implement the attribute and ap...
```csharp // ExecutionTimeLogAttribute.cs using System; using System.Diagnostics; using System.Web.Mvc; public class ExecutionTimeLogAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { filterContext.HttpContext.Items["StartTime"] = DateTime...
magicoder
csharp
You are tasked with creating a Python class that generates synthetic data for regression problems. The class, `SyntheticData`, should be able to produce training and testing datasets based on specified probability density functions (PDFs) and a random seed. The class should have the following attributes and functional...
```python import scipy.stats as sst import numpy as np class SyntheticData: def __init__(self, problem='regression', pdf_train=sst.norm(loc=-1, scale=2), pdf_test=sst.norm(loc=1, scale=3), seed=None): self.problem = problem self.pd...
magicoder
python
You are tasked with implementing a reinforcement learning agent using the Deep Q-Network (DQN) algorithm to solve a banana collection task in a Unity environment. The goal is to train the agent to navigate and collect yellow bananas while avoiding blue bananas. The environment is provided through the UnityAgents librar...
```python from drltools.utils import dqn_config, trainer from drltools.agent import DQNAgent from unityagents import UnityEnvironment env = UnityEnvironment(file_name="unity_environments/Banana_mac.app", worker_id=1) config = dqn_config agent_class = DQNAgent n_episodes = 2000 max_t = 1000 solved_score = 13 title = 'D...
magicoder
python
You are tasked with creating a parallel processing function for data manipulation using Python's multiprocessing library. Your function will take a dataframe and a function to apply to the dataframe as input, and then parallelize the application of the function across multiple cores. The goal is to improve the performa...
```python import pandas as pd from multiprocessing import Pool, cpu_count def apply_function(args): df, func = args return df.apply(func) def parallel_process_dataframe(df, func, num_cores=None): if num_cores is None: num_cores = cpu_count() # Automatically detect the available CPU cores wit...
magicoder
python
You are tasked with implementing a class that manages date fields and their locales. Your task is to create a method that sets the locale for the date fields. The method should take a `Locale` object as a parameter and update the locale for the date fields accordingly. You need to ensure that the method is accessible o...
```java import java.util.Locale; public class DateManager { protected void setDateFieldLocale(Locale value) { // Implementation to update the locale for date fields // This method can only be accessed within the class and its subclasses } } ```
magicoder
java
You are given a list of integers representing the frequency of events occurring at different time intervals. Your task is to implement a class `EventCounter` with the following methods: 1. `__init__(self, threshold: int)`: Initializes the EventCounter with a threshold value. 2. `add_event(self, timestamp: int, count: ...
```python class EventCounter: def __init__(self, threshold: int): self.threshold = threshold self.total = [0] * (threshold + 1) def add_event(self, timestamp: int, count: int): self.total[timestamp] += count def get_total_count(self, timestamp: int) -> int: total_count = 0 ...
magicoder
python
You are tasked with creating a function that parses a given HTML file and extracts all the classes used in the "body" tag. The function should return a list of unique class names found in the "body" tag. Write a function called `extractBodyClasses` that takes a string representing the HTML content as input and returns...
```python import re def extractBodyClasses(html_content): body_tag_pattern = re.compile(r'<body\s+class="([^"]*)"') match = body_tag_pattern.search(html_content) if match: classes = match.group(1).split() return list(set(classes)) # Return unique class names else: return [] # ...
magicoder
python
You are tasked with creating a Python function that processes a list of file paths and handles any potential IOError exceptions that may occur during file operations. Your function should take a list of file paths as input and attempt to open and read each file. If an IOError occurs during the file operation, your func...
```python from typing import List def process_files(file_paths: List[str]) -> List[str]: file_contents = [] for file_path in file_paths: try: with open(file_path, 'r') as file: file_contents.append(file.read()) except IOError as io_error: print(f"Error re...
magicoder
python
You are tasked with creating a Python function that calculates a specific mathematical formula. The formula involves factorials, exponentiation, and arithmetic operations. Your task is to implement the `formula` function according to the following specifications: The `formula` function takes five integer parameters: `...
```python def factorial(n): fact = 1 for i in range(1, n + 1): fact *= i return fact def formula(a, b, c, d, e): termino1 = (factorial(a) + factorial(b) + factorial(c)) / factorial(d) termino2 = pow(e, c) / factorial(e) result = termino1 + termino2 return round(result, 2) # Test th...
magicoder
python