query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with implementing a function that checks whether a given string representing a beast and a string representing a dish satisfy a specific condition. The condition is that the first character of the beast's name must be the same as the first character of the dish's name, and the last character of the beast...
```python def feast(beast, dish): return beast[0] == dish[0] and beast[-1] == dish[-1] ``` The `feast` function compares the first character of the `beast` string with the first character of the `dish` string using `beast[0] == dish[0]`, and also compares the last character of the `beast` string with the last char...
magicoder
python
You are tasked with creating a Python function that generates a Certificate Authority (CA) key pair and certificate. The function should take in a directory path and return a named tuple containing the key and certificate file paths. Your function should adhere to the following requirements: - Use the `cryptography` l...
```python import os import tempfile import collections from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.hazmat.primitives import serialization from cryptography import x509 from cryptography.x509.oid import NameOID from cryptography.haz...
magicoder
python
You are tasked with creating a script to monitor the CPU temperature of a Raspberry Pi and log the temperature readings to a CSV file. The script should read the CPU temperature every 20 seconds and append the temperature value (in degrees Celsius) to a CSV file in the format "timestamp,temperature". The temperature sh...
```bash #!/bin/bash while true do cpu_temp=$(< /sys/class/thermal/thermal_zone1/temp) # Read CPU temperature in millidegrees Celsius cpu_temp=$(($cpu_temp / 1000)) # Convert temperature to degrees Celsius timestamp=$(date +"%Y-%m-%d %H:%M:%S") # Get current timestamp in "YYYY-MM-DD HH:MM:SS" format ...
magicoder
shell
You are tasked with creating a custom migration operation for a Django application. The goal is to implement a new migration operation that will add a new field to a model and populate it with data based on a specific transformation logic. You need to create a custom migration operation named `PopulateFieldFromFunctio...
```python from django.db import migrations, models def populate_custom_field(apps, schema_editor): Chapter = apps.get_model('yourapp', 'Chapter') for chapter in Chapter.objects.all(): chapter.custom_field = transform_name(chapter.name) chapter.save() class PopulateFieldFromFunction(migrations....
magicoder
python
You are tasked with implementing a custom data structure called `FrequencyStack` that supports the following operations: 1. `push(int x)`: Add an integer `x` to the stack. 2. `pop()`: Remove and return the most frequent element in the stack. If there is a tie, return the element that was pushed most recently. You nee...
```java import java.util.*; class FrequencyStack { Map<Integer, Integer> freqMap; Map<Integer, Stack<Integer>> groupMap; int maxFreq; public FrequencyStack() { freqMap = new HashMap<>(); groupMap = new HashMap<>(); maxFreq = 0; } public void push(int x) { int f...
magicoder
java
You are working on a project that involves manipulating tensors in a distributed computing environment. As part of this project, you need to implement a function that performs a specific operation on a tensor and then tiles the resulting tensor. The tiling process involves partitioning the tensor into smaller chunks an...
```python def tiles(t: Tensor) -> Tensor: # Assuming t is a tensor object with chunks attribute representing the chunks of the tensor for chunk in t.chunks: chunk.op = TensorTriu() # Set the operation of each chunk to TensorTriu return t ``` In the solution, the `tiles` function iterates through e...
magicoder
python
You are tasked with creating a blog application using Django, a popular web framework for Python. Your task is to implement the necessary models and methods for the blog application. You need to create two models: `Blog` and `Comment`. The `Blog` model should have the following fields: - `author` (a foreign key to the...
```python from django.db import models from django.urls import reverse from django.contrib.auth.models import User class Blog(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) content = models.TextField() created_at = models.DateTimeField...
magicoder
python
You are tasked with implementing a Python function that processes a list of strings and returns a new list containing only the strings that are palindromes. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization)...
```python def find_palindromes(strings): """ Returns a list of palindromes from the input list of strings. Args: strings: A list of strings. Returns: A list of strings that are palindromes. """ palindromes = [] for string in strings: # Remove spaces and convert to lowercase...
magicoder
python
You are tasked with creating a program to manage the outline color and dimensions of various graphical elements in a user interface. The program should utilize the provided code snippet as a reference for implementing the necessary functionality. Your task is to implement a struct `Element` with the following methods:...
```rust // Define the PlayingValue struct struct PlayingValue { playing_state: PlayingState, } // Define the PlayingState enum enum PlayingState { // Define the possible states } // Define the NotationTheme struct struct NotationTheme { colors: ThemeColors, } // Define the ThemeColors struct struct Theme...
magicoder
rust
You are tasked with implementing a clustering algorithm for a scheduling system. The algorithm should be designed as a class that inherits from the provided `Algorithm` abstract base class and implements the `__call__` method. The `__call__` method takes three parameters: `cluster`, `clock`, and `plan`. The `cluster` p...
```python from abc import ABC, abstractmethod class Algorithm(ABC): @abstractmethod def __call__(self, cluster, clock, plan): pass class CustomClusteringAlgorithm(Algorithm): def __call__(self, cluster, clock, plan): # Custom clustering logic implementation based on the given parameters ...
magicoder
python
You are working on a project that involves building a RESTful API for a farming management system. The project uses Python and Django, and the code snippet provided is a part of the project's source code. Your task is to create a custom permission class for the API views to restrict access to resources based on ownersh...
```python from rest_framework import permissions, serializers from api.models import Harvester, User class IsOwner(permissions.BasePermission): def has_object_permission(self, request, view, obj): # Check if the requesting user is the owner of the object return obj.owner == request.user class Harv...
magicoder
python
You are tasked with implementing a delayed painting mechanism for a text editor component. The code snippet provided is a part of a larger codebase for a text editor application using the wxPython library. The snippet shows a class method that sets up the delayed painting functionality and binds it to the text editor c...
```python import wx class DelayedTextEditor: def __init__(self, parent, color, margins): self.sci = parent self.pen = wx.Pen(color) self.margins = margins self.delayed_paint_call = None self.sci.Bind(wx.stc.EVT_STC_PAINTED, self.on_painted_delayed) def on_painted_delay...
magicoder
python
You are tasked with implementing a custom class that manages database operations for a web application. The class, named `DatabaseManager`, is responsible for interacting with a database and providing various functionalities for data retrieval and manipulation. The class contains a method for retrieving data from the d...
```csharp public class DatabaseManager { // Constructor and other members are not shown for brevity // Complete method for retrieving data from the database based on ID public string RetrieveDataById(int id) { // Placeholder implementation for retrieving data based on ID // Replace this...
magicoder
csharp
You are tasked with implementing a function that converts a given time delta into a human-readable format based on a specified granularity. The function should take the time delta, granularity, and return the time delta in a human-readable format. You are given the following code snippet as a starting point: ```pytho...
```python from datetime import timedelta def format_time_delta(delta, granularity): if granularity == 'seconds': return f"{delta.seconds} seconds" elif granularity == 'minutes': minutes, seconds = divmod(delta.seconds, 60) if minutes == 1 and seconds == 0: return "1 minute" ...
magicoder
python
You are tasked with creating a program that manages a mapping between StyleGAN2 model configurations and their corresponding download links. The program should allow users to add new configurations and their download links, retrieve the download link for a given configuration, and remove configurations from the mapping...
```python class StyleGAN2Manager: def __init__(self): self.configurations = {} def add_configuration(self, config_name, download_link): self.configurations[config_name] = download_link def get_download_link(self, config_name): return self.configurations.get(config_name) def re...
magicoder
python
You are tasked with implementing a custom data structure to manage the display order of subcommands in a command-line application. The data structure should allow for efficient reordering of subcommands and retrieval of their display order. You need to create a struct called `DisplayOrder` that represents the display ...
```swift struct DisplayOrder { private var subcommands: [String] = [] mutating func addSubcommand(subcommand: String, at index: Int) { if index >= 0 && index <= subcommands.count { subcommands.insert(subcommand, at: index) } else { subcommands.append(subcommand) ...
magicoder
swift
You are tasked with creating a program that processes a given text file and extracts specific information from it. The text file contains license information for various software packages, and your program needs to extract the name of the software, the type of license it is distributed under, and any additional permiss...
```python import re def extract_license_info(file_path): with open(file_path, 'r') as file: content = file.read() entries = re.findall(r'# distributed under the (.*?) is distributed on an "(.*?)" BASIS,\n(.*?)# See the License for the specific language governing permissions and\nlimitations under the ...
magicoder
python
You are tasked with creating a Python class that simulates a simple banking system. The class should have methods for depositing funds, withdrawing funds, and checking the account balance. Additionally, the class should have a constructor to initialize the account balance. Your task is to complete the implementation o...
```python class BankAccount: def __init__(self, initial_balance): self.balance = initial_balance def deposit(self, amount): self.balance += amount def withdraw(self, amount): if amount > self.balance: return "Insufficient funds" else: self.balance -=...
magicoder
python
You are tasked with implementing a Singleton pattern using metaclasses in Python. The Singleton pattern ensures that a class has only one instance and provides a global point of access to that instance. Your task is to complete the implementation of the `MetaSingleton` metaclass, which will be used to create a Singlet...
```python class MetaSingleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super().__call__(*args, **kwargs) return cls._instances[cls] class Singleton(metaclass=MetaSingleton): def __init__(self, data): ...
magicoder
python
You are tasked with implementing an application that utilizes a stack to convert expressions from the traditional infix notation to the reverse Polish notation (postfix notation). In infix notation, operators are placed between their operands, such as `3 + 4 * 2`. In postfix notation, the operators follow their operand...
```python class Stack: def __init__(self): self.items = [] def push(self, item): self.items.append(item) def pop(self): if not self.is_empty(): return self.items.pop() else: raise IndexError("Pop from an empty stack") def is_empty(self): ...
magicoder
python
You are tasked with implementing a function to calculate the number of possible solutions to reach a target score in a game. The game involves adding or subtracting a fixed set of scores to reach the target score. The function should take the initial score and the target score as input and return the number of possible...
```python def count_solutions(initial_score, target_score): if target_score == 0: return 1 # There is only one way to reach a target score of 0, i.e., by not adding or subtracting anything if initial_score > target_score: return 0 # If the initial score is greater than the target score, no sol...
magicoder
python
You are given a string `expr` containing a boolean expression in the form of a string. The expression consists of only the boolean values `true` and `false`, and the logical operators `and`, `or`, and `not`. The expression is fully parenthesized and follows the standard rules of boolean logic. Your task is to write a ...
```python def evaluate_boolean_expression(expr: str) -> bool: stack = [] operators = set(['and', 'or', 'not']) def apply_operator(op, operands): if op == 'and': return operands[0] and operands[1] elif op == 'or': return operands[0] or operands[1] elif op == '...
magicoder
python
You are tasked with creating a script to automate the download and extraction of multiple compressed files from a remote server. The script should be able to handle the download and extraction of an arbitrary number of files, each with a unique URL and file name. Write a Python function `download_and_extract_files` th...
```python import os import requests import tarfile from typing import List, Tuple def download_and_extract_files(file_info: List[Tuple[str, str]]) -> None: for url, filename in file_info: # Download the file response = requests.get(url) with open(filename, 'wb') as file: file.wr...
magicoder
python
You are tasked with creating a middleware for a web server in Rust. The middleware should log the request and response bodies, greet the user with "Hi" at the start and end of the request, and handle a specific route "/login" with a custom response. Your task is to implement the middleware and the route handler using t...
```rust use actix_web::{web, App, HttpServer, HttpResponse, HttpRequest, Responder, middleware, dev::ServiceRequest, dev::ServiceResponse, Error}; use futures::future::{ok, Ready}; use std::pin::Pin; use std::task::{Context, Poll}; // Define the middleware struct Logging; impl<S, B> middleware::Transform<S, ServiceRe...
magicoder
rust
You are tasked with implementing a builder pattern for creating instances of a classified ad in a classified ads system. The system is designed using C# and utilizes the builder pattern to construct instances of the `RPClassifiedAd` class. The `RPClassifiedAd` class has a generic type parameter `int` for the identifier...
```csharp namespace TT.Tests.Builders.RPClassifiedAds { public class RPClassifiedAdBuilder : Builder<RPClassifiedAd, int> { private string title; private string description; private decimal price; private string category; public RPClassifiedAdBuilder() { ...
magicoder
csharp
You are tasked with implementing a system for managing user roles in a healthcare application. The system should allow for the creation, updating, and retrieval of user roles. Each role has a unique identifier and a name. You need to design a class that represents a user role and provides methods for updating the role ...
```java // Role class for managing user roles public class Role { private String roleId; private String roleName; // Constructor to initialize the role public Role(String roleId, String roleName) { this.roleId = roleId; this.roleName = roleName; } // Method to update the role n...
magicoder
java
You are tasked with implementing a simple observer pattern in Swift. The observer pattern is a behavioral design pattern that defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. In this problem, you will create a simple imple...
```swift import Combine class Subject { private var observers = [AnyCancellable]() func subscribe(_ observer: Observer) { let subscription = observer.receiveNotification() observers.append(subscription) } func unsubscribe(_ observer: Observer) { if let index = observers.firstI...
magicoder
swift
You are tasked with implementing a class hierarchy for geometric shapes in a C++ program. The base class `Shape` has virtual functions for calculating area and perimeter, which are overridden by derived classes such as `Polygon` and `Circle`. The provided code snippet shows part of the implementation for the `Polygon` ...
```cpp #include <cmath> #include <vector> class Shape { public: virtual double getArea() const = 0; virtual double getPerimeter() const = 0; virtual ~Shape() {} }; class Point2D { double x, y; public: Point2D(double x, double y) : x(x), y(y) {} double getX() const { return x; } double getY...
magicoder
cpp
You are tasked with implementing a custom UUID generator in Rust. The `TypeUuid` trait is provided as a starting point, and your goal is to create a struct that implements this trait and generates UUIDs based on specific requirements. Your task is to create a struct called `CustomUuidGenerator` that implements the `Ty...
```rust use uuid::Uuid; pub struct CustomUuidGenerator { prefix: String, counter: u32, } impl TypeUuid for CustomUuidGenerator { fn uuid(&self) -> Uuid { let uuid_string = format!("{}_{}", self.prefix, self.counter.to_string()); Uuid::new_v5(&Uuid::NAMESPACE_OID, uuid_string.as_bytes()) ...
magicoder
rust
You are tasked with implementing a method to draw a polygon on a canvas using a given set of vertices. The canvas is represented as a two-dimensional grid, and the vertices of the polygon are given as coordinates. Your task is to write a function that takes the canvas and the vertices of the polygon as input and draws ...
```java public void drawPolygon(int[][] vertices) { int n = vertices.length; for (int i = 0; i < n; i++) { int x1 = vertices[i][0]; int y1 = vertices[i][1]; int x2 = vertices[(i + 1) % n][0]; int y2 = vertices[(i + 1) % n][1]; drawLine(x1, y1, x2, y2); } } private vo...
magicoder
java
You are tasked with implementing a function that checks if a given exception chain includes a specific sub-exception type. The function should take in the top-level exception and the sub-exception type to be checked for, and return True if the sub-exception type is found anywhere in the exception chain, and False other...
```python from typing import Any, Type def check_exception_chain(err: Exception, object_type: Type) -> bool: if isinstance(err, object_type): return True elif err.__cause__ is not None: return check_exception_chain(err.__cause__, object_type) elif err.__context__ is not None: return...
magicoder
python
You are tasked with implementing a function that converts a string into a URL-readable fragment. The function should replace any non-alphanumeric characters with a hyphen (-) and remove any leading or trailing whitespace. The function should also handle any Unicode characters present in the input string. You are given...
```swift func urlReadableFragment(_ input: String) -> String { let allowedCharacterSet = CharacterSet.alphanumerics let trimmedInput = input.trimmingCharacters(in: .whitespaces) let urlFragment = trimmedInput .folding(options: .diacriticInsensitive, locale: .current) .components(separatedBy:...
magicoder
swift
You are tasked with implementing a class method for a facial recognition system. The method, `fit_values`, is responsible for determining the eye location from pre-defined landmark arrays, eliminating the need for re-computing the average landmarks on a target image or image directory. Your task is to complete the impl...
```python import numpy as np class FacialRecognitionSystem: def __init__(self): # Initialize any required variables or configurations here pass def fit_values(self, target_landmarks, target_width, target_height): """Calculate the eye location from pre-defined landmark arrays. ...
magicoder
python
You are tasked with implementing a subclass in a Java program that manages electronic invoicing. The superclass `FileSdI` represents a file related to the Italian electronic invoicing system, and the subclass `NotificaScarto` is responsible for handling notifications of rejected invoices. Your task is to complete the ...
```java // FileSdI.java public class FileSdI { // Common attributes and methods related to electronic invoicing // ... } // NotificaScarto.java public class NotificaScarto extends FileSdI { private String rejectedInvoiceId; private String rejectionReason; public NotificaScarto(String rejectedInvoi...
magicoder
java
You are working on a project that involves simulating electromagnetic fields in a geophysical context. You are using the `emg3d` library, which provides tools for electromagnetic simulations. In this scenario, you need to create a simulation instance and perform quality control (QC) on it. The `emg3d` library provides...
```python # Complete the initialization of the simulation instance and perform QC # Import the necessary modules import emg3d # Define the survey and model instances (assuming they are already defined) survey = ... model = ... # Initialize the simulation instance simulation = emg3d.simulations.Simulation( name="...
magicoder
python
You are tasked with implementing a DateTime class that can parse and validate date and time strings. The class should be able to handle various date and time formats and raise specific exceptions for invalid inputs. Your task is to implement the DateTime class with the following requirements: 1. The DateTime class sho...
```cpp #include <iostream> #include <regex> #include <stdexcept> class DateParsingException : public std::exception { public: const char* what() const noexcept override { return "Date parsing exception"; } }; class DateValidationException : public std::exception { public: const char* what() const ...
magicoder
cpp
You are tasked with implementing a function that processes a list of patient records and returns a filtered list based on certain criteria. Each patient record is represented as a dictionary with the following keys: "name", "age", "gender", and "diagnosis". The function should filter the patient records based on the fo...
```python def filter_patients(patients): filtered_patients = [] for patient in patients: if patient["age"] >= 18 and not (patient["gender"] == "male" and patient["diagnosis"] == "flu") and not (patient["gender"] == "female" and patient["diagnosis"] == "migraine"): filtered_patients.append(pa...
magicoder
python
You are tasked with implementing a function to parse a given Rust code snippet and extract the type name from it. The code snippet will consist of a type alias declaration in Rust syntax. Your task is to write a function that takes the code snippet as input and returns the extracted type name. Write a function `extrac...
```rust fn extract_type_name(code_snippet: &str) -> Option<&str> { let type_alias_keyword = "type"; let assignment_operator = "="; let trimmed_code = code_snippet.trim(); let parts: Vec<&str> = trimmed_code.split_whitespace().collect(); if let Some(type_index) = parts.iter().position(|&x| x == typ...
magicoder
rust
You are tasked with implementing a gate control system for a virtual environment. The system consists of gates that can be in one of three states: `.open`, `.closed`, or `.unknown`. Each gate can also have one of two operators: `.and` or `.or`. The gate control system is represented by the following Swift code snippet:...
```swift // Gate struct enum GateState { case open, closed, unknown } enum GateOperator { case and, or } enum LeftSide { case left } struct Gate { var state: GateState var `operator`: GateOperator var left: GateState subscript(side: LeftSide) -> GateState { return left } } /...
magicoder
swift
You are tasked with implementing a glucose data storage system for a health monitoring application. The system is responsible for creating and storing glucose data objects, as well as handling errors and updating the glucose data store. Below is a simplified version of the code snippet that demonstrates the process of ...
```swift class GlucoseDataStorage { private let cacheStore: GlucoseCacheStore private let log: Logger private let delegate: GlucoseStoreDelegate private let provenanceIdentifier: String init(cacheStore: GlucoseCacheStore, log: Logger, delegate: GlucoseStoreDelegate, provenanceIdentifier: String) { ...
magicoder
swift
You are tasked with creating a performance testing framework for a software application. The framework should be able to measure the memory allocation of specific operations and ensure that the allocated memory stays within certain bounds. Your task is to implement a class that can run performance tests and memory asse...
```csharp using System; using System.Reflection; using System.Diagnostics; public class PerformanceTester { public void RunPerformanceTests(object testClassInstance) { Type testClassType = testClassInstance.GetType(); MethodInfo[] methods = testClassType.GetMethods(); foreach (MethodIn...
magicoder
csharp
You are tasked with creating a Python class that simulates the behavior of a simplified version of the LSM303D, a 3D accelerometer and 3D magnetometer module. The class should provide methods for setting up the device, reading accelerometer and magnetometer data, and calibrating the magnetometer. Additionally, you need...
```python import pytest from unittest import mock class LSM303DSimulator: def __init__(self): self.acceleration = (0, 0, 0) self.magnetic_field = (0, 0, 0) def setup(self): raise RuntimeError("Failed to set up LSM303D") def read_acceleration(self): return self.acceleration...
magicoder
python
You are tasked with implementing a Python function that processes a list of integers and returns the count of unique numbers in the list. Additionally, you need to handle potential errors and exceptions that may occur during the execution of the function. You are provided with a partially completed Python function as ...
```python def count_unique_numbers(numbers): """ Count the number of unique integers in the given list. Args: numbers: A list of integers. Returns: An integer representing the count of unique numbers in the list. """ try: unique_numbers = set(numbers) # Convert the list to a s...
magicoder
python
You are tasked with creating a Java class that implements a specific algorithm for generating combinations of elements from a given list. The algorithm should efficiently generate all possible combinations of a specified length from the input list. To achieve this, you need to design a method that takes a list of eleme...
```java import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class CombinationGenerator { public List<List<Integer>> generateCombinations(List<Integer> inputList, int combinationLength) { List<List<Integer>> result = new ArrayList<>(); if (inputList == null || inputLis...
magicoder
java
You are tasked with implementing a TypeScript type utility that creates opaque types. An opaque type is a type that is represented by a unique underlying type, but is not directly interchangeable with it. This provides type safety by preventing accidental mixing of different types that are conceptually distinct. Your ...
```typescript export type Opaque<T, K extends string> = T & { __typename: K }; // Example usage type UserID = Opaque<number, 'ID'>; const id: UserID = 123; const typeName: 'ID' = id.__typename; // Valid access to the __typename property const num: number = id; // Error: Type 'UserID' is not assignable to type 'number'...
magicoder
typescript
You are tasked with implementing a class that manages API connections in a blockchain node. The class, `ApiAcceptor`, is responsible for accepting incoming API connections and handling various parameters related to the blockchain network. Your goal is to complete the implementation of the `ApiAcceptor` constructor by i...
```cpp namespace concord { namespace api { ApiAcceptor::ApiAcceptor( io_service &io_service, tcp::endpoint endpoint, KVBClientPool &clientPool, StatusAggregator &sag, uint64_t gasLimit, uint64_t chainID, bool ethEnabled, const concord::config::ConcordConfiguration &nodeConfig) : acceptor_(io_service, e...
magicoder
cpp
You are tasked with creating a Python function that processes a list of database connection objects and returns a dictionary containing server information for each connection. The server information should include the server name, server type, and server version. The function should have the following signature: ```p...
```python from typing import List, Dict import ibm_db def get_server_info(connections: List[ibm_db.Connection]) -> Dict[str, Dict[str, str]]: server_info = {} for conn in connections: server = ibm_db.server_info(conn) server_name = server['DBMS_NAME'] server_type = server['DBMS_TYPE'] ...
magicoder
python
You are given a 2D grid representing a map with cells, where each cell contains an integer value. The goal is to implement a depth-first search (DFS) algorithm to traverse the map and visit each cell exactly once, following a specific set of movement rules. The map is represented as a 2D array `map[][]`, where `map[x]...
```java int dfs(int x, int y, int k) { if (x < 0 || x >= n || y < 0 || y >= m || visit[x][y]) { return 0; } int d = map[x][y]; int nx = x + dx[d]; int ny = y + dy[d]; return visit[x][y] = dfs(nx, ny, k) + 1; } ``` In the `dfs` function, we first check if the current coordinates are out o...
magicoder
java
You are tasked with implementing a simple object pool using a mutex for thread safety. An object pool is a collection of reusable objects that can be acquired and released by multiple threads. The pool manages the lifecycle of the objects, ensuring that they are properly initialized and cleaned up. Your task is to imp...
```rust use std::sync::{Arc, Mutex, MutexGuard}; struct PoolError; struct MutexObjectPool<T> { objects: Vec<T>, initializer: Arc<dyn Fn() -> T>, cleaner: Arc<dyn Fn(T)>, mutex: Mutex<()>, } impl<T> MutexObjectPool<T> { fn new(initializer: impl Fn() -> T + 'static, cleaner: impl Fn(T) + 'static) -...
magicoder
rust
You are tasked with creating a Bash script that pings a Google Cloud Storage (GCS) host to check its availability. The script should take the GCS host as a command-line argument and then send a specified number of pings to the host with a defined deadline and sleep time in between pings. Your task is to complete the B...
```bash #!/bin/bash if [ "$1" = "" ] || [ $# -gt 1 ]; then echo "Usage: $(basename "$0") gcs_host" exit -1 fi GCS_IP="$1" PING_DEADLINE=1 # Ping deadline in seconds PING_COUNT=1 # How many pings to send SLEEP_TIME=1 # How long to sleep in between pings ping -c $PING_COUNT -W $PING_DEADLINE -i $SLEEP_TIME ...
magicoder
shell
You are tasked with implementing a blockchain-based voting system using Java. The system will handle the creation of voting channels, distribution of ballots, and execution of voting operations. You are provided with a set of classes and interfaces from the `devote.blockchain` package, as well as some testing utilities...
```java import devote.blockchain.api.ChannelGeneratorAccountOperation; import devote.blockchain.api.DistributionAndBallotAccountOperation; import devote.blockchain.operations.VotingBlockchainOperations; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import ...
magicoder
java
You are tasked with creating a Python function that simulates a user's interaction with a web browser. Your function should perform a series of actions using the Selenium library to automate a web browser session. The goal is to create a function that logs a user out of a web application by clicking on the logout butto...
```python from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC def logout_user(browser): print("\nThank you...
magicoder
python
You are tasked with implementing a Python class for probability density function (PDF) calculation. The class should have a method to compute the PDF of a given input using the Gaussian distribution formula. The provided code snippet is a part of the class that calculates the PDF and its negative logarithm. Your task i...
```python import numpy as np import theano.tensor as T class GaussianPDFCalculator: def __init__(self, mu, sigma, X): self.mu = mu self.sigma = sigma self.X = X self.pdf_ = None def _make(self, value, name): # Implementation specific to the class, not relevant to the pr...
magicoder
python
You are tasked with creating a script to automate the setup of a development environment using Vagrant for a 64-bit architecture. Your script should perform the following tasks: 1. Create a directory `~/.ssh` with permissions set to 700. 2. Download the public key from a specific URL and save it as `~/.ssh/authorized_...
```bash #!/bin/sh set -ex # Create ~/.ssh directory with permissions 700 mkdir -p -m700 ~/.ssh # Download and set permissions for authorized_keys curl -o ~/.ssh/authorized_keys https://raw.github.com/mitchellh/vagrant/master/keys/vagrant.pub chmod 600 ~/.ssh/authorized_keys # Install virtualbox-guest-utils without c...
magicoder
shell
You are tasked with creating a plugin system for a game engine. The game engine uses the Rust programming language and the Bevy game engine library. The provided code snippet is a part of the configuration for the game engine, where various resources, plugins, startup systems, and regular systems are being added. Your...
```rust use bevy::prelude::*; // Define a trait for the plugin trait PluginTrait { fn startup(&self, commands: &mut Commands); fn update(&self, commands: &mut Commands); } // Implement the PluginTrait for a custom plugin struct CustomPlugin; impl PluginTrait for CustomPlugin { fn startup(&self, commands:...
magicoder
rust
You are tasked with implementing a function that calculates the total number of unique paths to reach the bottom-right corner of a grid from the top-left corner. You can only move either down or to the right at any point in time. The grid is represented by a 2D array where 1 indicates an obstacle and 0 indicates an emp...
```java public int uniquePaths(int[][] grid) { int m = grid.length; int n = grid[0].length; if (grid[0][0] == 1 || grid[m-1][n-1] == 1) { return 0; // No path if start or end is blocked } int[][] dp = new int[m][n]; dp[0][0] = 1; // Fill the first row for (int i = ...
magicoder
java
You are tasked with implementing a custom modal presentation style for a view controller in an iOS app. The `destination` view controller needs to be presented using a custom modal presentation style, and the `perform` method needs to be overridden to achieve this. The `modalPresentationStyle` property of the `destinat...
```swift class CustomPresentationViewController: UIViewController { // ... other methods and properties override func perform() { destination.modalPresentationStyle = .custom super.perform() } } ``` In the solution, the `perform` method is overridden in the `CustomPresentationViewControlle...
magicoder
swift
You are tasked with implementing a function to decode a string encoded using a specific format. The encoding format involves using a combination of letters and numbers to represent a repeating pattern within the string. The format is as follows: - A number represents the number of times the subsequent substring should ...
```python def decodeString(s: str) -> str: stack = [] curr_num = 0 curr_str = '' for c in s: if c.isdigit(): curr_num = curr_num * 10 + int(c) elif c.isalpha(): curr_str += c elif c == '[': stack.append(curr_str) stack.append(c...
magicoder
python
You are tasked with creating a Python class that manages SSH configurations for a system. The class should be able to parse an SSH configuration file and provide methods for retrieving and updating configuration parameters. Create a Python class `SSHConfigManager` with the following requirements: - The class should ha...
```python from .parameter_definition import ParameterDefinition class SSHConfigManager: def __init__(self, file_path): self.config_params = {} self.file_path = file_path def parse_config_file(self): with open(self.file_path, 'r') as file: lines = file.readlines() ...
magicoder
python
You are tasked with designing a program to manage software builds for different architectures and firmware versions. The program needs to filter and join various data structures to retrieve the relevant information for a given architecture and build version. You are given the following data structures: 1. `Build` with...
```python from typing import List class BuildInfo: def __init__(self, architectures: List[str], firmware: int): self.architectures = architectures self.firmware = firmware def retrieve_build_info(architecture_code: str, build_version: int) -> List[BuildInfo]: # Perform the required filtering a...
magicoder
python
You are working on a project that involves estimating a transformation model from input-output data pairs. The goal is to implement a function that performs a robust estimation of the transformation model using the RANSAC algorithm. The RANSAC algorithm is used to estimate the parameters of a mathematical model from a ...
```python import numpy as np from skimage.measure import ransac def estimate_transformation(input_data, output_data, simple=True): if simple: model, _ = tf.estimate(input_data, output_data) return model else: model, inliers = ransac((input_data, output_data), transform, min_samples=3, r...
magicoder
python
You are tasked with implementing a class that manages a collection of fill arcs in a 2D space. The class provides methods to add, set, and retrieve fill arcs. Each fill arc is defined by an origin point, a beginning point, and an angle. You need to implement the following methods in the `FillArcManager` class: - `GetN...
```cpp #include <iostream> #include <vector> // Define the Point structure struct Point { double x; double y; }; // Define the FillArcManager class class FillArcManager { private: std::vector<Point> origoPoints; std::vector<Point> beginPoints; std::vector<double> angles; public: // Returns th...
magicoder
cpp
You are tasked with implementing a TypeScript class that manages user data for an MQTT (Message Queuing Telemetry Transport) system. The provided code snippet includes TypeScript interfaces and a class definition that you will use as a basis for your implementation. Your task is to create a class called `MqttUserModel...
```typescript // Define the Model class for reference class Model<T, U> { // Placeholder for actual implementation } // Implement the MqttUserModel class class MqttUserModel extends Model<IMqttUser, IMqttCreation> { private users: IMqttUser[] = []; // Placeholder for user data storage createUser(user: IMqttCrea...
magicoder
typescript
You are tasked with implementing a binary search tree (BST) in Python. A binary search tree is a data structure that allows for efficient insertion, deletion, and search operations. Each node in a BST has at most two child nodes, referred to as the left child and the right child. Additionally, the value of each node in...
```python class Node: def __init__(self, key, value): self.key = key self.value = value self.left = None self.right = None class BinarySearchTree: def __init__(self): self.root = None def insert(self, key, value): if self.root is None: self.root ...
magicoder
python
You are tasked with implementing a simple inventory management system for a small retail store. The system should allow the store to add new items, update existing items, and display the current inventory. You are given a partial implementation of the `Item` class, which represents an item in the store's inventory. Yo...
```python class Item: def __init__(self, name, price, quantity): self.name = name self.price = price self.quantity = quantity def update_price(self, new_price): self.price = new_price def update_quantity(self, quantity_change): self.quantity += quantity_change ...
magicoder
python
You are tasked with creating a Java program that simulates a simple banking system. The program should allow users to create accounts, deposit and withdraw funds, and check their balance. Additionally, the program should handle exceptions such as insufficient funds and invalid account operations. Your task is to imple...
```java package Chris.Chapter13.Exception; // Custom exception for insufficient funds class InsufficientFundsException extends Exception { public InsufficientFundsException(String message) { super(message); } } // BankAccount class class BankAccount { private static int accountCounter = 1000; // S...
magicoder
java
You are tasked with implementing a custom sorting algorithm for a list of skills. Each skill is represented as a dictionary with the following structure: ```python { 'name': 'Python', 'level': 'Intermediate' } ``` The skills need to be sorted based on their names in ascending order. However, the sorting should ...
```python def custom_skill_sort(skills): def custom_sort_key(skill): return skill['name'].lower(), {'Beginner': 0, 'Intermediate': 1, 'Advanced': 2}[skill['level']] return sorted(skills, key=custom_sort_key) ``` The `custom_skill_sort` function defines a custom sorting key using a lambda function `cust...
magicoder
python
You are working on a simulation software for modeling fluid flow in pipes. The code snippet provided is a part of a script that manipulates the mesh of a pipe wall to create boundary layer cells for accurate fluid flow simulation. The code uses a custom `pipe_wall` object to perform various operations on the mesh. You...
```python class PipeWallMesh: def __init__(self, mesh): self.mesh = mesh def chop_axial(self, start_size): # Implement axial chopping logic based on start size pass # Placeholder for implementation def chop_tangential(self, start_size): # Implement tangential chopping logi...
magicoder
python
You are tasked with creating a Rust function that renders a 3D scene using the WebGPU graphics API. The function takes in a render target, a command encoder, and a scene as input parameters. Your goal is to implement the rendering logic within the function to produce the final rendered output. The function signature i...
```rust fn render_scene( render_target: &wgpu::TextureView, encoder: &mut wgpu::CommandEncoder, scene: &Scene, ) { // Assume the existence of a `pipeline` and `bind_group` representing the rendering pipeline and bind group for the scene // Begin a render pass on the command encoder let mut rend...
magicoder
rust
You are tasked with creating a script that automates the deployment of Docker containers. Your script should accept command-line arguments and set environment variables for the container to use. The script should also pull the container image with a specified version and run it with the provided arguments. Your script...
```bash #!/bin/bash # Check if all required arguments are provided if [ $# -lt 3 ]; then echo "Usage: $0 COMMAND IMAGE VERSION [ADDITIONAL_ARGS...]" exit 1 fi # Assign input arguments to variables COMMAND=$1 IMAGE=$2 VERSION=$3 shift 3 # Shift the arguments to access additional arguments later # Set environment...
magicoder
shell
You are working with a dataset containing information about locations and interest points. The `location_df` DataFrame contains columns for "fid" (location identifier), "latitude", and "longitude". The `interest_points_df` DataFrame contains columns for "lat" (latitude) and "lon" (longitude) of various interest points....
```python def calculate_distances(location_df, interest_points_df): results = [] for i in location_df.index: for j in interest_points_df.index: results.append([ location_df.loc[i, "fid"], distance(location_df.loc[i, "latitude"], location_df.loc[i, "longitude"]...
magicoder
python
You are tasked with implementing a user authentication system in a web application using Django. The code snippet provided is a part of the view function that handles user authentication. The `User` model represents the user data in the application, and `request.user.id` contains the ID of the currently authenticated u...
```python from django.http import HttpResponseServerError from django.shortcuts import get_object_or_404 from django.contrib.auth.models import User def user_authentication_view(request): try: user = get_object_or_404(User, id=request.user.id) # Further processing with the retrieved user object ...
magicoder
python
You are tasked with creating a Python function that converts a given string from Shift-JIS encoding to EUC-JP encoding. Shift-JIS (SJIS) and EUC-JP are character encoding schemes used for Japanese text. Write a function `sjis_to_euc` that takes a string encoded in Shift-JIS and returns the equivalent string encoded in...
```python import codecs def sjis_to_euc(input_string): sjis_bytes = input_string.encode('sjis') # Encode the input string to Shift-JIS bytes euc_bytes = codecs.decode(sjis_bytes, 'euc_jp', 'ignore') # Decode the Shift-JIS bytes to EUC-JP bytes return euc_bytes.decode('euc_jp') # Decode the EUC-JP bytes ...
magicoder
python
You are tasked with implementing a dynamic loader class in C++ that can load and execute shared libraries at runtime. The dynamic loader should be able to load a shared library, retrieve a function from it, and execute that function. You are provided with a code snippet for the DynamicLoader class, and you need to comp...
```cpp #include <iostream> #include <dlfcn.h> // for Unix-based systems #include <windows.h> // for Windows systems class DynamicLoader { private: void* libraryHandle; public: DynamicLoader() : libraryHandle(nullptr) {} bool loadLibrary(const std::string& libraryPath) { #ifdef _WIN32 ...
magicoder
cpp
You are tasked with implementing a subclass of a CapsuleGeometry class in a 3D graphics library. The CapsuleGeometry class represents a 3D capsule shape, which is a cylinder with hemispherical ends. The provided code snippet shows the beginning of the CapsuleGeometry class, including the definition of the Axis enum and...
```swift class CapsuleGeometry: Geometry { public enum Axis { case x case y case z } public init(size: (radius: Float, height: Float), axis: Axis = .y) { super.init() // Your implementation here } func calculateVolume() -> Float { let radius ...
magicoder
swift
You are tasked with implementing a function to compare two dictionaries representing order books in a financial trading system. The dictionaries contain price levels as keys and order quantities as values. Your goal is to identify the differences between the two order books in terms of both bid (buy) and ask (sell) ord...
To solve this problem, you can implement the `DictDiff` function and then use it to compare the ask and bid order books. Here's a possible implementation: ```python def DictDiff(book1, book2): diff = {} for key in book1: if key not in book2: diff[key] = book1[key] elif book1[key] !=...
magicoder
python
You are given a set of equations in the form of Psi[i] = F, where i is a positive integer and F is a function of variables X and E. The initial condition is Psi[1] = 1. Your task is to implement a function that calculates the value of Psi[n] for a given positive integer n, X, and E. Write a function `calculatePsi(n, X...
```python def calculatePsi(n, X, E): if n == 1: return 1 else: return f(X, E) * calculatePsi(n-1, X, E) ``` In the solution, the `calculatePsi` function recursively calculates the value of Psi[n] based on the given equation Psi[1]=1 and the function F=f(X,E). If n is 1, the function returns 1 a...
magicoder
python
You are tasked with creating a Python script that can parse and manipulate environment variables. Your script should be able to extract specific information from the environment variables and perform operations based on the extracted data. Write a Python function called `extract_and_manipulate_env_vars` that takes in ...
```python import re def extract_and_manipulate_env_vars(env_vars, keyword): extracted_values = [] for env_var in env_vars: match = re.match(r'export\s+{}\s*=\s*"([^"]+)"'.format(keyword), env_var) if match: extracted_values.append(match.group(1)) if keyword == "PWD": lo...
magicoder
python
You are tasked with simulating a simplified model of a representative democracy with a party system. The government operates on a monthly basis, implementing income tax, universal basic income (UBI), and changes in parliamentary composition. The government consists of multiple parties, each with a certain number of se...
```python class Gov_rep(object): def __init__(self, parties, initial_composition, tax_rate, ubi_amount, term_duration): ''' Initialize the government with the given parties, initial parliamentary composition, tax rate, UBI amount, and term duration. Args: parties (dict): A dictionar...
magicoder
python
You are tasked with implementing a Python class that simulates a host management system. The class should be able to perform actions such as rebooting, shutting down, and powering up the host. The class should also keep track of the current state of the host (e.g., whether it is on or off) and provide methods to retrie...
```python class HostManager: def __init__(self): self.state = "off" def reboot(self): if self.state == "off": self.state = "on" else: self.state = "on" # Assuming rebooting means powering on if off, and restarting if already on def shutdown(self): i...
magicoder
python
You are tasked with implementing a configuration update function for a Python project. The function takes in several parameters and is responsible for updating the project's configuration settings based on the provided inputs. Your task is to complete the implementation of the `update_config` function, ensuring that th...
```python def update_config(project_root, buckconfig_local, to_set, py2, py3, py2_settings, py3_settings, current_platform): if py2: to_set['python#py2'] = py2_settings to_set['python#py2-%s' % current_platform] = py2_settings if py3: to_set['python#py3'] = py3_settings to_set['...
magicoder
python
You are tasked with creating a Bash script that processes command-line arguments to perform specific actions based on the number of arguments provided. Your script should handle three cases: 1. If no arguments are provided, the script should display an error message. 2. If exactly one argument is provided, the script s...
```bash #!/bin/bash if [ $# -eq 0 ]; then echo "Error: No arguments provided." elif [ $# -eq 1 ]; then echo "Processing single argument: $1" else index=1 for arg in "$@"; do echo "Argument $index: $arg" ((index++)) done fi ``` The provided Bash script `argument_processor.sh` checks the number of com...
magicoder
shell
You are tasked with implementing a function that compares two objects for equality. The function should compare the properties and values of the objects and return true if they are equal, and false otherwise. You are given the following code snippet as a starting point: ```javascript expect(result).toEqual(formDefin...
```javascript function toEqual(obj1, obj2) { if (typeof obj1 !== 'object' || typeof obj2 !== 'object') { return obj1 === obj2; } if (Array.isArray(obj1) !== Array.isArray(obj2)) { return false; } if (Array.isArray(obj1) && Array.isArray(obj2)) { if (obj1.length !== obj2.length) { return fa...
magicoder
javascript
You are tasked with implementing a load balancing algorithm for a distributed system. The system consists of multiple servers, and the load balancing algorithm aims to evenly distribute incoming requests among these servers to optimize performance and resource utilization. You are provided with a partial interface for ...
```java import java.util.HashMap; import java.util.List; public class LoadBalancer implements LoadBalance { // Implementing the findList method to distribute load based on criteria @Override public List<LoadBalance> findList(HashMap<String, Object> map) { // Add logic to analyze the provided crite...
magicoder
java
You are tasked with implementing a method to find the "hubs" in a given graph. In graph theory, a hub is a node that is highly connected to other nodes in the graph. The number of connections a hub has is known as its degree. Your task is to write a Python function `getHubs` that takes a graph represented as an adjacen...
```python from typing import List def getHubs(graph: dict) -> List[str]: max_degree = 0 hubs = [] for node, neighbors in graph.items(): degree = len(neighbors) if degree > max_degree: max_degree = degree hubs = [node] elif degree == max_degree: ...
magicoder
python
You are tasked with creating a program that simulates the behavior of a simple system. The system consists of a variable `x_val` that is manipulated based on certain conditions and then written to a file. The code snippet provided is a part of the program that performs these operations. The variable `x_val` is initiall...
```python # Assume the missing parts of the program are as follows: # Define the condition based on which x_val is manipulated condition = True # Replace with the actual condition # Open the file for writing with open('output.txt', 'w') as b_file: for i in range(1, 11): # Assuming i ranges from 1 to 10 ...
magicoder
python
You are tasked with implementing a class method for a reinforcement learning environment. The method is responsible for processing the collected observations, actions, and rewards, and returning specific aggregated data. The method takes no input parameters and is part of a class with the following attributes: - `env`...
```python import numpy as np class ReinforcementLearningEnvironment: def __init__(self, env): self.env = env self.obs = [] self.actions = [] self.rewards = [] def process_data(self): acc_rewards = [] last_episode_idx = 0 for _ in range(len(self.rewards)...
magicoder
python
You are tasked with implementing a function that can parse a given directory and return a list of all Python test files present in that directory. The function should be able to handle nested directories as well. You are not allowed to use any external libraries or modules for this task. Write a Python function called...
```python import os def find_test_files(directory): test_files = [] for root, dirs, files in os.walk(directory): for file in files: if file.startswith("test_") and file.endswith(".py"): test_files.append(os.path.relpath(os.path.join(root, file), directory)) return test_f...
magicoder
python
You are working on a project that involves mapping torch operations to references. The goal is to automate the process of mapping torch operations to their corresponding references and to throw an assertion error if the mapping doesn't exist. You need to implement a function that achieves this mapping and handles the a...
```python def map_torch_operations(): mapping = {} # Mapping torch operations to references mapping['torch._refs'] = 'refs' mapping['torch._refs.nn'] = 'nn' mapping['torch._refs.nn.functional'] = 'nn.functional' mapping['torch._refs.special'] = 'special' mapping['torch._prims'] = 'prims...
magicoder
python
You are tasked with implementing a custom list widget in a GUI application. The list widget contains items that can be hidden, and the user can navigate through the list using the up and down arrow keys. When the user presses the down arrow key, the next visible item in the list should be selected and scrolled into vie...
To handle the up arrow key press event and scroll the previous visible item into view, you can use the following code: ```python elif event.key() == Qt.Key_Up: currentRow = self.listWidget.row(self.topItem) previousRow = currentRow - 1 while previousRow >= 0 and self.listWidget.item(previousRow).isHidden()...
magicoder
python
You are tasked with creating a Python function that tokenizes a given string based on a set of predefined keywords. The function should identify and extract these keywords from the input string and return a list of tokens. Each token should consist of the keyword itself, along with its position in the input string. Yo...
```python def tokenize_string(input_string, keywords): tokens = [] for keyword in keywords: start = 0 while True: start = input_string.find(keyword, start) if start == -1: break tokens.append((keyword, start)) start += len(keyword) ...
magicoder
python
You are working on a project that involves loading and building OpenCL programs for GPU execution. The given code snippet is part of a function that loads the source code for a program named "Concat" and sets build options based on the number of output channels (outC). The function also creates build options based on t...
```cpp #include <string> #include <vector> #include <iostream> std::string constructBuildOptions(const std::string& source, int outC, const std::string& registry_data_type) { std::string build_options; if (outC <= 4) { build_options += " -DOUTCTMPSIZE=4"; } else if (outC <= 128) { build_options += " -DO...
magicoder
cpp
You are tasked with implementing a flyweight design pattern to optimize memory usage in a system that manages employee objects. The flyweight pattern is used to minimize memory usage or computational expenses by sharing as much data as possible with similar objects. In this problem, you will create an `EmployeeFactory`...
```java // Employee class representing the intrinsic state of an employee public class Employee { private int id; private String name; private String department; public Employee(int id, String name, String department) { this.id = id; this.name = name; this.department = departmen...
magicoder
java
You are tasked with creating a Python program that simulates a simple neural network using the Brian 2 library. The neural network will consist of a single neuron with a specified set of parameters. Your goal is to implement the network and visualize its behavior using the Brian 2 and matplotlib libraries. Your progra...
```python from brian2 import * import matplotlib.pyplot as plt # Define neuron parameters resting_potential = -70*mV threshold = -50*mV reset_value = -70*mV membrane_time_constant = 10*ms synaptic_weight = 0.5 # Create a single neuron eqs = ''' dv/dt = (resting_potential - v + synaptic_weight * I) / membrane_time_con...
magicoder
python
You are tasked with implementing a TypeScript interface for an API key input. The interface should define the structure of the input required to create an API key with specific permissions. Your task is to complete the definition of the `ApiKeyInput` interface by providing the necessary properties and their types base...
```typescript export interface ApiKeyInput { /** * The name you will use to describe this API Key. */ name: string; /** * The individual permissions that you are giving to this API Key. */ permissions: string[]; // Define the type for permissions, e.g., string array or specific enum } ``` In the sol...
magicoder
typescript
You are tasked with implementing a simplified version of a Least Recently Used (LRU) cache using Python. An LRU cache is a data structure that stores a fixed number of items and evicts the least recently used item when the cache reaches its limit. The cache should support two operations: `get(key)` and `put(key, value)...
```python class LRUCache: def __init__(self, capacity: int): self.capacity = capacity self.__lookup = collections.OrderedDict() def get(self, key: int) -> int: if key in self.__lookup: value = self.__lookup.pop(key) self.__lookup[key] = value # Move the key to t...
magicoder
python
You are tasked with implementing a simple drawing application that supports different shapes. You are provided with an abstract class `Shape` that contains an abstract method `draw(self, level)`. Your task is to create concrete subclasses of `Shape` and implement the `draw` method to draw the respective shapes at the s...
```python from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def draw(self, level): pass class Rectangle(Shape): def draw(self, level): for i in range(level // 2): print(" " * level + "#" * level) class Triangle(Shape): def draw(self, level): for...
magicoder
python
You are tasked with implementing a job scheduling algorithm for a system that manages scheduled jobs. Each job has a unique identifier and a scheduled execution time. The system needs to efficiently handle the scheduling and execution of these jobs based on their scheduled times. You are given a `ScheduledJobsControlle...
```java import java.util.PriorityQueue; class ScheduledJobsController { private PriorityQueue<Job> jobQueue; public ScheduledJobsController() { jobQueue = new PriorityQueue<>(); } public void scheduleJob(int jobId, long scheduledTime) { Job newJob = new Job(jobId, scheduledTime); ...
magicoder
java
You are tasked with implementing a function that manages trust chains in a system. The trust chain is a data structure that links a subject to a trust anchor, along with additional data. The function should either update an existing trust chain or create a new one if it does not exist. You are given a code snippet tha...
```python from your_module import TrustChain # Import the TrustChain model from your system def manage_trust_chain(subject, fetched_trust_anchor, data): # Check if a trust chain already exists for the given subject tc = TrustChain.objects.filter(sub=subject).first() if tc: # Update the existing t...
magicoder
python
You are tasked with implementing a custom reusable view in a Swift iOS application. The view should display a list of items and allow the user to select multiple items by tapping on them. To achieve this, you need to create a custom view class that manages the selection state of each item and provides a way to retrieve...
```swift import UIKit class CustomSelectableItemsView: UIView { var items: [String] = [] var selectedItems: Set<String> = [] override func awakeFromNib() { super.awakeFromNib() cleanup() } override func prepareForReuse() { super.prepareForReuse() cleanup() } ...
magicoder
swift