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 to process XML data received as a POST request and extract specific information from it. The XML data represents a notification for a successful recharge transaction and contains details about the transaction. Your task is to parse the XML data and extract the following infor...
```php namespace app\user\controller; use think\Db; use cmf\controller\HomeBaseController; class NotifyController extends HomeBaseController { // 充值回调 public function recharge() { $postStr = file_get_contents("php://input"); $orderxml = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_...
magicoder
php
You are tasked with creating a function that determines the frequency of each word in a given string. The function should take a string as input and return a dictionary where the keys are the unique words in the input string, and the values are the frequencies of those words. For example, given the input string "the c...
```python def wordFrequency(s: str) -> dict: word_list = s.split() # Split the input string into a list of words frequency_dict = {} # Initialize an empty dictionary to store word frequencies for word in word_list: if word in frequency_dict: frequency_dict[word] += 1 # Increment the ...
magicoder
python
You are tasked with creating a Python function that processes a dataset stored in a specified directory and performs image processing operations using the "scipy" library. Your function should traverse the directory, locate image files, and apply a specific image processing operation to each image found. If the "scipy"...
```python import os from scipy import misc def process_images(root_dir): try: import scipy except ImportError: raise ModuleImportError("The module 'scipy' could not be found.") images_dir = os.path.join(root_dir, "images") if not os.path.exists(images_dir): raise FileNotFoundEr...
magicoder
python
You are tasked with implementing a file locking mechanism in PHP to ensure that a file is not accessed by multiple processes simultaneously. You need to write a function that locks a file, updates a counter stored in the file, and returns a unique code based on the current date and the updated counter. If the file cann...
```php /** * Generates a unique code based on the current date and an updated counter. * @param string $filePath The path to the file storing the counter. * @return string The unique code in the format 'RFQ-YYYYMMDD-COUNTER' or an error message. */ function generateUniqueCode($filePath) { $file = fopen($filePat...
magicoder
php
You are tasked with implementing a class that represents a non-deterministic finite automaton (NFA) in a programming language of your choice. The given code snippet provides a partial implementation of the NFA class, including methods for setting the NFA bit, getting the accept state, and potentially other methods not ...
```java import java.util.*; public class NFA { private BitSet nfa_bit; private Accept accept; private Map<Integer, Map<Character, Set<Integer>>> transitions; public NFA() { this.nfa_bit = new BitSet(); this.accept = new Accept(); this.transitions = new HashMap<>(); } p...
magicoder
java
You are tasked with creating a function that calculates the distance between two geographical coordinates using the Haversine formula. The Haversine formula is used to calculate the distance between two points on the Earth given their latitude and longitude in decimal degrees. The formula is as follows: ``` a = sin²(Δ...
```javascript function calculateDistance(lat1, long1, lat2, long2) { const R = 6371; // Radius of the Earth in kilometers const dLat = deg2rad(lat2 - lat1); const dLong = deg2rad(long2 - long1); const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(deg2rad(lat1)) * Math.cos(deg2r...
magicoder
javascript
You are tasked with implementing a Python function that converts a PostgreSQL array-string to a Python list. The PostgreSQL array-string is represented as a comma-separated string enclosed in curly braces. The function should handle the conversion for one-dimensional arrays only. If the input is not a string or Unicode...
```python def convert_pg_array(pg_array): """ Convert a PostgreSQL array-string to a Python list. PostgreSQL <9.0 used comma-separated strings as the array datatype. This function will convert those to a list. If pg_array is not a string, it will not be modified. """ if not isinstance(pg_array, (st...
magicoder
python
You are tasked with implementing a Python class method for deserializing an event stream from a byte stream. The event stream is represented by the `EventStream` class, and the deserialization method should be implemented as the `from_bytes` class method. The deserialization process involves loading data from a CBOR-en...
```python @classmethod def from_bytes(cls, stream: IO[bytes]) -> EventStream: """ :returns EventStream: an instance of EventStream from the given bytes (which should have been produced by a prior call to ``to_bytes``) """ data = cbor2.load(stream) ...
magicoder
python
You are tasked with implementing a face recognition system that involves initializing a face recognition database by reading information from a face register file. The provided code snippet is a part of the initialization process, where the system checks if the face register file exists and creates it if it doesn't. Yo...
```python class FaceRecognitionSystem: def __init__(self, face_register_file): self.face_register_file = face_register_file self.registered_faces = [] def init_face_database(self): """ Description: Init face recognition database, read information from face_r...
magicoder
python
You are tasked with creating a Python program that simulates a simple command-line tool for performing mathematical operations. The program should accept command-line arguments to specify the operation to be performed and the operands involved. The supported operations are addition, subtraction, multiplication, and div...
```python import argparse import sys def add(args): return args.operand1 + args.operand2 def subtract(args): return args.operand1 - args.operand2 def multiply(args): return args.operand1 * args.operand2 def divide(args): if args.operand2 == 0: print("Error: Division by zero") sys.exi...
magicoder
python
You are tasked with implementing a function to parse and extract information from a Rust macro. The macro is defined using the `macro_rules!` syntax and contains a specific pattern that needs to be identified and processed. You are given a code snippet from a Rust build script that includes a function `rustc_minor_ver...
```rust fn parse_macro_pattern(macro_definition: &str, pattern: &str) -> Vec<String> { let mut occurrences = Vec::new(); let mut in_macro = false; let mut current_macro = String::new(); for line in macro_definition.lines() { if line.contains("macro_rules!") { in_macro = true; ...
magicoder
rust
You are tasked with creating a Rust function that interacts with Java through JNI (Java Native Interface). Your function will receive two parameters: `body` and `witness_set`, both of type `JRPtr` (Java Rust Pointer). The goal is to implement the logic inside the Rust function to handle these parameters and return a re...
```rust pub unsafe extern "C" fn Java_io_emurgo_rnhaskellshelley_Native_transactionNew( env: JNIEnv, _: JObject, body: JRPtr, witness_set: JRPtr ) -> jobject { // Handle exceptions and return the result to Java handle_exception_result(|| { // Extract the Rust pointer for the body parameter let body = body...
magicoder
rust
You are tasked with implementing a simplified version of a message queue system using Python's `queue` module. The system should support adding messages to the queue, retrieving messages from the queue, and handling the case when the queue is empty. You are provided with a partial implementation of the `queue_get` fun...
```python import queue import threading def queue_get(q): while True: try: return q.get(block=True, timeout=0.1) except queue.Empty: pass def queue_put(q, message): q.put(message) def main(): message_queue = queue.Queue() # Add messages to the queue for i ...
magicoder
python
You are tasked with creating a Python function that selects the best compression algorithm based on a given input data size and compression ratio. The function should take in the input data size and compression ratio, and then determine the most suitable compression algorithm from a predefined list of available codecs....
```python import blosc CNAME_AVAIL = blosc.compressor_list() CNAME_MAPPING = { 0: 'blosclz', 1: 'lz4', 2: 'snappy', 3: 'zlib', 4: 'zstd' } def select_compression_algorithm(input_data_size: int, compression_ratio: float) -> str: best_algorithm = None best_ratio = float('inf') for index...
magicoder
python
You are tasked with implementing a command-line tool for managing abbreviations in a text editor. The tool will support the creation, removal, and listing of abbreviations. Abbreviations are short forms of commands that expand into their full form when used in the text editor. Your task is to implement the `unabbrevia...
```python # Import necessary modules from .state import EOF from .tokens import TokenEof from .tokens_base import TOKEN_COMMAND_UNABBREVIATE from .tokens_base import TokenOfCommand from Vintageous import ex # Define the unabbreviate command @ex.command('unabbreviate', 'una') def unabbreviate_command(abbreviation_to_re...
magicoder
python
You are tasked with implementing a function that processes user data using the AptoSDK framework. The AptoSDK is a software development kit for building financial applications, and it provides various functionalities for managing user data and transactions. In this problem, you need to create a function that takes user...
```swift import AptoSDK import Foundation enum ProcessingResult { case success case failure(reason: String) } struct UserData { let name: String let email: String let dateOfBirth: Date // Other user data fields } class UserDataCollectorInteractorNewUserStrategy: UserDataCollectorInteractorStr...
magicoder
swift
You are tasked with implementing a program to analyze the enrichment of clipped reads in a set of samples at a given genomic coordinate. A clipped read is a sequence that has been partially removed during the sequencing process, often due to low-quality bases or adapter contamination. The goal is to determine the propo...
```python from typing import List, Dict, Union, Tuple def calculate_enrichment(samples: List[Dict[str, Union[str, List[Tuple[int, int]]]], coord: Tuple[str, int]) -> Dict[str, float]: enrichment_results = {} for sample in samples: sample_id = sample["sample_id"] clipped_reads = sample["cli...
magicoder
python
You are working on a recipe recommendation system that takes a dataset of recipes and provides recommendations based on certain criteria. The code snippet provided is a part of this system and involves reading a CSV file containing recipe data, processing the data to generate recommendations, and then printing the reco...
```python import pandas as pd def recommender(df): # Implement your recommendation algorithm here # For example, let's assume a simple recommendation algorithm based on highest ratings recommended_recipes = df.sort_values(by="rating", ascending=False).head(5)["recipe_id"].tolist() return recommended_re...
magicoder
python
You are tasked with implementing a function that converts a Python data structure into a dictionary. The function should handle nested structures and convert them into nested dictionaries. The function should be named `struct_to_dict` and should take a single argument `struct` representing the input data structure. The...
```python def struct_to_dict(struct): if isinstance(struct, dict): return {key: struct_to_dict(value) for key, value in struct.items()} elif isinstance(struct, (list, tuple)): return [struct_to_dict(item) for item in struct] elif hasattr(struct, '__dict__'): return struct_to_dict(str...
magicoder
python
You are tasked with creating a Go package that provides a shared library for interfacing with the InterPlanetary File System (IPFS). The provided code snippet demonstrates the compilation and installation process for the shared library. Your goal is to write a Go program that utilizes this shared library to interact wi...
```go package main /* #cgo LDFLAGS: -lipfs #include <stdlib.h> #include "libipfs.h" */ import "C" import ( "fmt" "unsafe" ) func main() { // Connect to the IPFS network C.connect_to_ipfs() // Add a file to the IPFS network filePath := "/path/to/your/file.txt" cFilePath := C.CString(filePath) defer C.free(uns...
magicoder
go
You are tasked with implementing a simulation of a universe using a 2D grid. The universe is represented by a boolean grid where each cell can be either alive (True) or dead (False). You need to implement a function `add_beacon` that adds a beacon pattern to the universe grid. The beacon pattern consists of two blocks ...
```python def add_beacon(universe, x, y, type='\\'): def add_block(universe, x, y): universe[(y + 1) * width + (x + 1)] = True if type == '\\': add_block(universe, x, y) add_block(universe, x + 2, y + 2) elif type == '/': add_block(universe, x + 1, y) add_block(unive...
magicoder
python
You are tasked with creating a Rust module that handles various aspects of working with Uniform Resource Identifiers (URIs). The module should include functionality for parsing, manipulating, and representing URIs. Your task is to implement the `uri` module, which will contain the following components: 1. `doc` module...
```rust // uri.rs pub mod doc { pub fn provide_documentation() { // Comprehensive documentation for the URI module // Explanation of functionality and usage } } pub mod error { pub enum UriError { ParsingError, ManipulationError, } } pub mod fields { pub struct Uri ...
magicoder
rust
You are tasked with implementing a generic repository pattern for a data access layer in a C# application. The repository pattern is a common design pattern used to abstract the data access logic from the rest of the application. In this scenario, you are required to create a generic repository interface and a concrete...
```csharp // Define the generic repository interface public interface IRepository<T> { T GetById(int id); IEnumerable<T> GetAll(); void Add(T entity); void Update(T entity); void Delete(T entity); } // Implement the concrete repository for the Division entity public class DivisionRepository : IRepo...
magicoder
csharp
You are tasked with creating a Python function that sends a POST request to a specified URL with a file payload. The function should take the URL and the file path as input and return the response from the server. You are provided with the following code snippet for inspiration: ```python import io import json import...
```python import requests def send_file_payload(url, file_path): with open(file_path, 'rb') as file: files = {'file': file} response = requests.post(url, files=files) return response ``` The `send_file_payload` function uses the `requests` library to send a POST request to the specified `u...
magicoder
python
You are tasked with implementing a DropdownFactory class that can create and manage instances of different Dropdown classes. The DropdownFactory class should have the following features: 1. It should be able to create instances of Dropdown classes based on the provided class type. 2. It should maintain a map of created...
```java import java.util.HashMap; import java.util.Map; class Dropdown { private String name; public Dropdown(String name) { this.name = name; } public String getName() { return name; } } public class DropdownFactory { private static Map<Class<? extends Dropdown>, Dropdown> i...
magicoder
java
You are tasked with implementing a custom exception class and handling its usage within a testing framework. Your goal is to create a custom exception class, write a test case to verify the exception message, and handle the exception within a testing framework. Create a custom exception class called `UnknownSelectorEx...
```java // Custom exception class public class UnknownSelectorException extends RuntimeException { public UnknownSelectorException(String selector, Throwable cause) { super("Selector not found. (" + selector + ")", cause); } } // Test case using JUnit import org.junit.Rule; import org.junit.Test; impor...
magicoder
java
You are tasked with implementing a compile-time comparison trait in C++. The trait should compare the value of a given type with the value of another type and return a boolean value indicating whether the first value is greater than the second value. Your task is to complete the implementation of the `greater_than` tr...
```cpp template <typename T, T V> struct Value { static constexpr T value = V; }; template <typename T1, typename T2> using greater_than = std::conditional_t< (T1::value > T2::value), std::true_type, std::false_type>; ``` In the solution, we define a `Value` template struct with a static constexpr member `value...
magicoder
cpp
You are tasked with implementing a custom modal input component in React. The component should display a modal window with an input field and two buttons: "Save" and "Cancel". The input field should be pre-populated with a JSON string representation of a given value, and the user should be able to edit this value. The ...
```jsx import React, { useState } from 'react'; const ModalInput = ({ element, value, onChange, onCancel }) => { const [inputValue, setInputValue] = useState(value); const handleSave = () => { try { const parsedValue = JSON.parse(inputValue); onChange(parsedValue); } catch (error) { // H...
magicoder
jsx
You are tasked with implementing a Python function that simulates a simple notification system. The function should be able to produce different types of notifications, such as success notifications and warning notifications. The function should also have the ability to play sound files synchronously or asynchronously,...
```python def notify(status, sync=False, raise_error=False): """Simulate a notification system. Parameters: status: A string representing the status of the notification, which can be either "success" or "warning". sync: A boolean indicating whether the sound file should be played synchronously....
magicoder
python
You are tasked with creating a script to automate the installation of the LPeg library for Lua. The LPeg library is stored in a tar.gz archive file named `lpeg-1.0.1.tar.gz`, and its download URL is `http://www.inf.puc-rio.br/~roberto/lpeg/lpeg-1.0.1.tar.gz`. The installation process involves extracting the contents of...
```bash #!/bin/bash lpeg_archive="lpeg-1.0.1.tar.gz" lpeg_url="http://www.inf.puc-rio.br/~roberto/lpeg/${lpeg_archive}" lua_impl="/path/to/lua/implementation" # Replace with the actual path platform="linux" # Replace with the actual platform download_lpeg() { wget "$lpeg_url" -P "$lua_impl" || exit $? } instal...
magicoder
shell
You are working on a computer vision project and are tasked with implementing a custom image classification model using a pre-trained ResNet architecture. The ResNet model consists of several layers, including convolutional layers, batch normalization, ReLU activation, and max pooling. Additionally, the model has four ...
```python def apply_resnet_blocks(x, n_blocks): # Apply batch normalization, ReLU activation, and max pooling x = self.resnet.bn1(x) x = self.resnet.relu(x) x = self.resnet.maxpool(x) # Apply ResNet blocks based on the value of n_blocks if n_blocks >= 1: x = self.resnet.layer1(x) if...
magicoder
python
You are tasked with creating a Bash script to download a specific JAR file from a remote repository. The script should take into account the version of the JAR file, resolving it if the version is "RELEASE" or "LATEST". The script should also handle the conversion of group and artifact paths to directory paths and cons...
```bash #!/bin/bash # Given variables and functions deps=("com.example.group" "artifact" "1.0.0") version="" resolve_version() { # Custom logic to resolve the version # This function is not provided, and its implementation is not necessary for this problem echo "Resolved version" } remote_repository="https...
magicoder
shell
You are tasked with implementing a function that processes XML nodes based on certain conditions. The function takes in a list of XML nodes and two boolean flags, `stop_on_next` and `tagid_required`. Each XML node is represented as an object with attributes such as `tag_type` and `attributes`. The function should retur...
```python from typing import List class Node: def __init__(self, tag_type, attributes): self.tag_type = tag_type self.attributes = attributes def process_nodes(nodes: List[Node], stop_on_next: bool, tagid_required: bool) -> List[Node]: filtered_nodes = [] for node in nodes: if stop...
magicoder
python
You are tasked with creating a class to monitor and validate network latency data. Your class should have a property `average_latency` that allows setting and getting the average latency value. Additionally, the class should have a method `validate` to ensure that the average latency value meets certain criteria. Your...
```python class NetworkMonitor: def __init__(self): self._average_latency = None @property def average_latency(self): return self._average_latency @average_latency.setter def average_latency(self, val): if val is not None: self.validate('average_latency', val) ...
magicoder
python
You are tasked with implementing a session management system for a server that handles connections and disconnections. The provided code snippet is part of a Swift application and contains a few methods related to session management. Your task is to design and implement the `SessionManager` class that encapsulates the ...
```swift import Foundation struct Session { let url: URL // Other session properties } class Server { func reconnect(to session: Session) throws { // Implementation for reconnecting to a session } func disconnect(from session: Session) throws { // Implementation for disconnecting ...
magicoder
swift
You are tasked with implementing a TypeScript class that manages Google Drive operations using OAuth2 authentication. The class should handle the authentication process and provide methods for interacting with Google Drive resources. However, the class should also ensure that certain sensitive properties are hidden fro...
```typescript import { OAuth2Client, BaseExternalAccountClient } from 'google-auth-library'; interface ITsGoogleDriveOptions { // Define the required options for Google Drive operations // (e.g., client_id, client_secret, redirect_uri, etc.) } class TsGoogleDrive { private _client?: OAuth2Client | BaseExternalA...
magicoder
typescript
You are tasked with implementing a benchmarking utility for a software system. The utility should measure the performance of various functions and provide detailed results for analysis. Your task is to design and implement the benchmarking utility using the provided code snippet as a starting point. You are given the ...
```csharp using System; using System.Diagnostics; public class BenchResult<T> { public T Result { get; set; } public TimeSpan ExecutionTime { get; set; } } public class BenchmarkUtility { public BenchResult<object> run(params string[] args) { if (args.Length == 0) { throw n...
magicoder
csharp
You are working on a ticket management system for an application. The code snippet provided is a part of a base class that is used for managing tickets and application settings. The class uses dependency injection to access the `ITicketManager` and `IApplicationSettings` interfaces. The `Ticket.Culture` property is use...
```csharp public class TicketProcessor : TicketProcessorBase { public TicketProcessor(ITicketManager ticket, IApplicationSettings applicationSettings) : base(ticket, applicationSettings) { } public bool ProcessTicket(Ticket ticket, string cultureCode) { if (ticket == null || string.IsNullOr...
magicoder
csharp
You are tasked with implementing a custom error handling mechanism in a C# application. The `SetErrorHandler` method is used to register a callback function that will be invoked whenever an error occurs in the application. Your goal is to create a class that allows users to register an error handling callback and provi...
```csharp public class ErrorHandler { private Action<object> errorCallback; private object errorContext; public void SetErrorHandler(Action<object> callback, object context) { errorCallback = callback; errorContext = context; } public void HandleError() { if (errorC...
magicoder
csharp
You are given a Python function that takes a list of arrays and a random seed as input. The function shuffles the arrays using the provided seed and returns the shuffled arrays. Your task is to implement a Python program that can accurately predict the shuffled arrays given the original arrays and the random seed. Fun...
```python from typing import List import random def predict_shuffled_arrays(arrays: List[List[int]], rand_seed: int) -> List[List[int]]: random.seed(rand_seed) shuffled_arrays = [array[:] for array in arrays] # Create a copy of the original arrays for array in shuffled_arrays: random.shuffle(arra...
magicoder
python
You are tasked with creating a Python function that interacts with a database table to manage a simple key-value cache system. The cache table has the following structure: Table Name: cache Columns: - id (BigInteger, not nullable): Unique identifier for each cache entry - key (Unicode, nullable): The key for the cache...
```python from sqlalchemy import create_engine, MetaData, Table, Column, BigInteger, Unicode, DateTime from sqlalchemy.sql import select, insert, update, delete class CacheManager: def __init__(self, db_uri): self.engine = create_engine(db_uri) self.metadata = MetaData(bind=self.engine) sel...
magicoder
python
You are tasked with creating a program that processes images using a pre-trained machine learning model. The program should take an input image, display it using a function called `imshow`, and then pass the image through the model to obtain an output. Your task is to implement a function called `process_image` that t...
```python import matplotlib.pyplot as plt def process_image(input_image, model): plt.imshow(input_image) plt.show() output = model(input_image) return output ``` In the solution, the `process_image` function first displays the input image using `imshow` and `plt.show()`. Then, it processes the in...
magicoder
python
You are tasked with creating a TypeScript class that manages a collection of records using TypeORM. Your class should provide methods to add, retrieve, update, and delete records from a database using TypeORMModule. Additionally, you need to create a service and a resolver to handle the business logic and GraphQL queri...
```typescript import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { Record } from './record.entity'; @Injectable() export class RecordsService { constructor( @InjectRepository(Record) private readonly recordRepository: ...
magicoder
typescript
You are tasked with implementing a function that takes in an array of strings representing CSS class names and returns a new string representing the concatenation of these class names with a specific prefix. The function should also ensure that the resulting string does not contain any duplicate class names. You are g...
```typescript function addPrefixAndRemoveDuplicates(classes: string[], prefix: string): string { const prefixedClasses = classes.map(className => `${prefix}${className}`); const uniquePrefixedClasses = [...new Set(prefixedClasses)]; // Using Set to remove duplicates return uniquePrefixedClasses.join(' '); } ```
magicoder
typescript
You are given a field represented as a 2D grid of characters. Each cell in the grid can be either a tree ('#') or open space ('.'). Starting from the top-left corner of the grid, you need to count the number of trees encountered while moving in specific patterns. The patterns are defined by slopes, which represent the ...
```python from typing import List def count_trees(field: List[List[str]], right_slope: int, down_slope: int) -> int: rows, cols = len(field), len(field[0]) tree_count = 0 x, y = 0, 0 # starting position while y < rows: if field[y][x % cols] == '#': tree_count += 1 x += rig...
magicoder
python
You are tasked with implementing a data streaming system for a wearable device that includes various sensors such as accelerometer, user accelerometer, gyroscope, magnetometer, and a special "magic" sensor. The system uses channels to handle the streaming of data from these sensors. However, the given code snippet show...
```java import java.util.HashMap; import java.util.Map; public class SensorDataStreamer { private Map<String, StreamHandler> sensorChannels; public SensorDataStreamer() { sensorChannels = new HashMap<>(); } public void setStreamHandler(String sensor, StreamHandler handler) { sensorCha...
magicoder
java
You are tasked with implementing a utility function to parse and validate memory limits and optimization passes for a compiler tool. The function should handle parsing memory limits as positive integers and optimization passes as comma-separated strings. The function should return the parsed values or appropriate error...
```rust use std::num::ParseIntError; fn parse_memory_limit(input: &str) -> Result<u32, ParseIntError> { match input.parse::<i32>() { Ok(num) if num > 0 => Ok(num as u32), _ => Err(ParseIntError { kind: std::num::IntErrorKind::PosOverflow }), } } fn parse_passes(input: &str) -> Result<Vec<Strin...
magicoder
rust
You are tasked with creating a Python module that interacts with a database and performs various operations on the data. The module should import functions from other modules and use them to achieve its objectives. Your task is to implement a function `process_data` in the `data_processor.py` module, which will perfor...
```python # data_processor.py from .extra_routines import state_to_id, period_to_date from .query import IBGEQuery def process_data(state_name, period_string): state_id = state_to_id(state_name) period_date = period_to_date(period_string) ibge_query = IBGEQuery() data = ibge_query.fetch_data(stat...
magicoder
python
You are tasked with creating a web application for a company that manages standards and manual procedures. The application needs to display a form with dropdown menus for selecting a standard and a manual procedure. The standards and manual procedures are fetched from a database and need to be populated dynamically in ...
```php // Assuming $standar and $mp contain the fetched data from the database // Populate the "Standard" dropdown menu foreach ($standar as $s) { echo '<option value="' . $s['id_standar'] . '">' . $s['no_standar'] . ' (' . $s['deskripsi_standar'] . ')</option>'; } // Populate the "Manual Procedure" dropdown menu...
magicoder
php
You are given a Python code snippet that contains an inefficient implementation of a depth-first search algorithm. Your task is to reimplement the depth-first search algorithm using a more elegant and efficient recursive approach. Your goal is to create a Python function that takes in a graph represented as an adjacen...
```python def depth_first_search(graph, start_node): visited = set() def dfs_helper(node): visited.add(node) for neighbor in graph[node]: if neighbor not in visited: dfs_helper(neighbor) dfs_helper(start_node) return list(visited) ``` The `depth_first_searc...
magicoder
python
You are tasked with creating a Python program that interacts with the Dialogflow API to build a simple chatbot. The chatbot will respond to user input with predefined phrases based on certain keywords. Your task is to implement the logic for processing user input and generating appropriate responses. Your program shou...
```python import dialogflow_v2 as dialogflow import random import os import logging import logging.config from dotenv import load_dotenv # Load environment variables from .env file load_dotenv() # Set up logging configuration logging.basicConfig(level=logging.INFO) # Create a function to process user input and gener...
magicoder
python
You are tasked with creating a Python function that utilizes the NumPy library to perform a specific mathematical operation. The function should take in two NumPy arrays, C and V, and a NumPy array of integers, nums. The function should calculate the result based on the following formula: result = (C * V) / nums Wher...
```python import numpy as np def calculate_result(C, V, nums): result = (C * V) / nums return result # Test the function with the given example C = np.array([1, 2, 3]) V = np.array([[4, 5, 6], [7, 8, 9]]) nums = np.array([2, 3]) expected_result = np.array([[2. , 3.33333333, 4.5], [3.5, 5.33333333, 6.]]) # Ve...
magicoder
python
You are tasked with implementing a testing framework for a user interface library. The library includes a `MenuItem` interface, which represents a menu item in a graphical user interface. The `MenuItem` interface extends the `Component` interface and provides two methods: `labelShouldHave(String text)` and `click()`. T...
```java public class TestMenuItem implements MenuItem { private String labelText; public TestMenuItem(String labelText) { this.labelText = labelText; } @Override public void labelShouldHave(String text) { if (!labelText.equals(text)) { throw new AssertionError("Label te...
magicoder
java
You are tasked with implementing a function to perform 3D convolutional soft argmax operation using the given input tensor and parameters. The soft argmax operation is a differentiable approximation of the argmax function, which is commonly used in machine learning for localization tasks. The input tensor represents a ...
```python import torch import torch.nn.functional as F def conv_soft_argmax_3d(input_tensor, input_size, kernel_size, padding, temperature): # Apply 3D convolution to the input tensor conv_output = F.conv3d(input_tensor, weight=None, bias=None, stride=1, padding=padding, dilation=1, groups=1) # Apply soft...
magicoder
python
You are tasked with designing a Java class to represent an online purchase order. The class should encapsulate the necessary attributes and provide methods to manipulate and retrieve the order details. Use the given code snippet as a starting point and expand upon it to create the complete class. Your class should inc...
```java import java.math.BigDecimal; import java.time.LocalDateTime; public class PurchaseOrder { private String username; private LocalDateTime createTime; private LocalDateTime updateTime; private String detail; private BigDecimal price; private BigDecimal discount; private Integer num; ...
magicoder
java
You are tasked with implementing a function to generate a boot sector for a FAT32 file system. The boot sector is a crucial part of the file system, containing essential information for the system to boot and access the file system. The provided code snippet is a partial implementation of this function in Python. Your...
```python def generate_boot_sector(): response = bytearray(512) # Initialize a byte array of size 512 for the boot sector response += 12 * b'\x00' # reserved space response += b'\x80' # drive number for PC-BIOS (0x80 = hard disk) response += b'\x00' # reserved space ...
magicoder
python
You are tasked with creating a program that simulates a simple text-based adventure game. The game will involve the player navigating through different rooms, encountering obstacles, and making decisions that affect the outcome of the game. Your program should include the following features: - The game should start wi...
```python class Room: def __init__(self, name, description, items=None, obstacles=None, exits=None): self.name = name self.description = description self.items = items if items else [] self.obstacles = obstacles if obstacles else {} self.exits = exits if exits else {} de...
magicoder
python
You are tasked with creating a Python script to analyze and visualize the performance data of a system using the Phoronix Test Suite (PTS). The Phoronix Test Suite is a comprehensive testing and benchmarking platform available for various operating systems. Your script should perform the following tasks: 1. Retrieve t...
```python import xml.etree.ElementTree as ET import matplotlib.pyplot as plt def retrieve_performance_data(file_path): tree = ET.parse(file_path) root = tree.getroot() performance_scores = {} for test in root.findall('.//Test'): test_name = test.find('Name').text score = float(test.find...
magicoder
python
You are tasked with creating a script that processes a directory containing executable files. Your script should iterate through each file in the directory, check if it is a regular file, readable, and executable, and if so, execute the file. Write a shell script that accomplishes the following: 1. Accepts a directory...
```bash #!/bin/bash # Check if the correct number of arguments is provided if [ "$#" -ne 1 ]; then echo "Usage: $0 <directory_path>" exit 1 fi # Store the directory path from the command-line argument d="$1" # Iterate through each file in the directory for i in `ls "$d"`; do f=$d/$i # Check if the file is a ...
magicoder
shell
You are tasked with implementing a service management system for a company that provides various services to its customers. The system should include classes for managing customer information, drafting service details, generating invoices, and calculating taxes. The provided code snippet includes the names of the class...
```python class CustomerService: def __init__(self, name, contact_details): self.name = name self.contact_details = contact_details self.service_history = [] def add_service_history(self, service_details): self.service_history.append(service_details) class DraftService: de...
magicoder
python
You are tasked with creating a simple web application using PHP and Laravel framework. Your task is to implement a feature that allows users to manage components and subcomponents. The given code snippet is a part of the routing configuration in a Laravel application. The code snippet defines several routes for the we...
```php // komponenController.php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Component; // Assuming the existence of a Component model class komponenController extends Controller { public function data() { $components = Component::all(); // Retrieve all components from...
magicoder
php
You are tasked with creating a program that analyzes a given text and counts the occurrences of each unique word. For the purpose of this problem, a word is defined as a sequence of characters separated by spaces. Punctuation marks should be disregarded, and the comparison of words should be case-insensitive. The progr...
```python def count_unique_words(text): # Remove punctuation and convert to lowercase text = ''.join(char if char.isalnum() or char.isspace() else ' ' for char in text).lower() # Split the text into words words = text.split() # Count occurrences of each word word_count = {} for wor...
magicoder
python
You are tasked with creating a Python function that generates a training dataset for a machine learning model. The function should take in parameters for the number of data points, batch size, and repeat size, and should yield batches of input data and corresponding labels. The input data should be random images, and t...
```python import numpy as np import mindspore.dataset as ds def get_data(num_data=32768, img_size=(32, 32, 3), num_classes=10, is_onehot=False): def get_data_generator(): for _ in range(num_data): img = np.random.randn(*img_size) target = np.random.randint(0, num_classes) ...
magicoder
python
You are tasked with implementing a function that takes a string as input and returns the count of each unique character in the string. The function should ignore whitespace and be case-insensitive. For example, given the input "Hello, World!", the function should return a dictionary with the counts of each character: {...
```python def count_unique_characters(input_string: str) -> dict: char_count = {} input_string = input_string.lower().replace(" ", "") # Convert to lowercase and remove whitespace for char in input_string: if char.isalpha(): # Check if the character is a letter if char in char_count: ...
magicoder
python
You are tasked with creating a Python function that interacts with a database and a GitHub API. Your function will handle the retrieval and storage of GitHub release data. You will also need to implement a function to load a personal access token from a JSON file. You are provided with the following code snippet as a ...
```python import json import time def save_releases(db, releases, repo_id): # Assuming db is a valid database connection object # Save releases to the database using the provided repo_id for release in releases: # Save release data to the database using db and repo_id pass # Placeholder fo...
magicoder
python
You are tasked with implementing a Python class that utilizes the AlexNet model for feature extraction. The AlexNet model is imported from a module called `extractors`. Your task is to create a class called `FeatureExtractor` that has a method `extract_features` which takes an image as input and returns the extracted f...
```python from .extractors import AlexNet class FeatureExtractor: def __init__(self): # Initialize the AlexNet model for feature extraction self.model = AlexNet() def extract_features(self, image): # Extract features from the input image using the AlexNet model features = self....
magicoder
python
You are tasked with implementing a function that processes a list of tuples representing product data and returns a dictionary containing the count of unique values for each category. Each tuple contains the product name and its associated categories. The function should ignore duplicate product names and count the uni...
```python def count_unique_categories(products): unique_categories_count = {} for product, categories in products: unique_categories = set(categories) if product in unique_categories_count: unique_categories_count[product] = max(len(unique_categories), unique_categories_count[product...
magicoder
python
You are given a code snippet that describes the computation of parameters for the generalized gamma distribution and the computation of percentiles at different percentages. Your task is to implement a Python function that takes in the input parameters and computes the percentiles for the given generalized gamma distri...
```python import numpy as np from scipy.optimize import least_squares def generalized_gamma_distribution_params(trA): # Compute the parameters alpha, beta, and delta of the generalized gamma distribution alpha = np.zeros(trA.size) beta = np.zeros(trA.size) delta = np.zeros(trA.size) # Initial ...
magicoder
python
You are working on a software development project that involves packaging and managing dependencies using NuGet, a popular package manager for .NET. As part of the project, you need to automate the process of packing and cleaning up old NuGet packages. The provided code snippet is a part of the automation script. The ...
```python import subprocess def pack_and_cleanup_nuget(): # Pack the project into a NuGet package subprocess.run(["nuget", "pack", "project.nuspec"]) # Remove all NuGet packages with names starting with "netmicro" from the local package cache subprocess.run(["rm", "-rf", "~/.nuget/packages/netmicro*"]...
magicoder
python
You are tasked with creating a Python function that retrieves a specific setting from a Django configuration and performs a transformation on it. The Django configuration is represented by a dictionary containing various settings. Your function should take the name of the setting as a parameter and return the transform...
```python from typing import Union, List def retrieve_and_transform_setting(setting_name: str) -> Union[str, int, List[int]]: setting_value = settings.get(setting_name) if setting_value is None: return "Setting not found" if isinstance(setting_value, str): return setting_value[::-1] eli...
magicoder
python
You are tasked with creating a Python function that processes a list of URL paths and extracts the view names associated with each path. The view name is the part of the URL path that comes after the last forward slash ("/") and before any query parameters or file extensions. Your function should return a dictionary wh...
```python from typing import List, Dict def extract_view_names(url_paths: List[str]) -> Dict[str, str]: view_names = {} for path in url_paths: parts = path.rstrip("/").split("/") view_name = parts[-1] if "?" in view_name: view_name = view_name[:view_name.index("?")] ...
magicoder
python
You are tasked with creating a program to process and display information about a trading card game. The program should handle legalities and rulings for a specific card. The card object has attributes `legalities` and `rulings`, which are lists of dictionaries containing information about the legal status of the card ...
```python def display_card_info(card): legal = "Legalities:\n" for legality in card.legalities: legal += f"{legality['format']} : {'✅' if legality['legality'] == 'Legal' else '🚫'}\n" rules = "Rulings:\n" for ruling in card.rulings: rules += f"{ruling['date']} : {ruling['text']}\n" ...
magicoder
python
You are tasked with implementing a movie recommendation system using the provided code snippet as a starting point. The system should retrieve now playing movies and display them to the user. Additionally, the system should allow users to search for specific movies and display detailed information about the selected mo...
```csharp // Define a class to represent a movie public class Movie { public string Title { get; set; } public DateTime ReleaseDate { get; set; } public string Overview { get; set; } public double Rating { get; set; } } // Define a service interface for retrieving movie data public interface IMovieServ...
magicoder
csharp
You are tasked with implementing a function that determines whether a debugger is attached to a running process. The function will take no parameters and return a boolean value indicating the presence of a debugger. You are provided with a code snippet that demonstrates the use of system calls and low-level memory ope...
```swift import Foundation func isDebuggerAttached() -> Bool { var name: [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid()] var info: kinfo_proc = kinfo_proc() var info_size = MemoryLayout<kinfo_proc>.size let isDebuggerAttached = name.withUnsafeMutableBytes { ptr in ptr.bindMemory(to: I...
magicoder
swift
You are tasked with creating a program to parse and process HTML table data. The program should extract specific information from the table and perform calculations based on the extracted data. You are given an HTML table snippet as follows: ```html </thead> <tbody> <tr> ...
```python from bs4 import BeautifulSoup import math # Given HTML table snippet html_table = ''' </thead> <tbody> <tr> <th scope="row">1</th> <td>654</td> <td>Otto</td> <td>@mdo</td> ...
magicoder
python
You are given a string `S` containing only lowercase letters. Your task is to write a function that repeatedly removes adjacent, duplicate characters from the string until no adjacent duplicates remain. The function should return the modified string. For example, if the input string is "abbaca", the function should re...
```python def removeAdjacentDuplicates(S: str) -> str: stack = [] for char in S: if stack and stack[-1] == char: stack.pop() else: stack.append(char) return ''.join(stack) ```
magicoder
python
You are tasked with creating a Python script to automate the deployment process for an AWS Lambda function using API Gateway. The deployment process involves installing the required Python packages, zipping the necessary files, and uploading the zip file to AWS Lambda. Your script should perform the following steps: 1...
```python import os import zipfile import boto3 # Step 1: Navigate to the parent directory of the project os.chdir('..') # Step 2: Install the required Python packages os.system('pip install -r requirements.txt -t dist/src') # Step 3: Zip the contents of the specified directory def zip_dir(folder_path, zip_path): ...
magicoder
python
You are tasked with creating a Rust program that interacts with the X Window System using the x11 and xft libraries. Your program needs to open a display, retrieve the default screen, and then draw a simple text string on the screen using Xft. Your task is to complete the following Rust function: ```rust fn draw_text...
```rust use x11_dl::xlib; use x11_dl::xft; fn draw_text_on_screen(text: &str) { let xlib = x11_dl::xlib::Xlib::open().expect("Unable to load xlib"); let xft = x11_dl::xft::Xft::open().expect("Unable to load xft"); let dpy = unsafe { (xlib.XOpenDisplay)(std::ptr::null()) }; let screen = unsafe { (xlib....
magicoder
rust
You are tasked with implementing a function to generate a unique identifier for a new ElectionLog entry in a Django application. The provided code snippet shows the model for ElectionLog, which includes a field for the unique identifier. Your task is to create a function that generates a new unique identifier following...
```python import uuid from .models import ElectionLog def generate_election_log_id(): while True: new_id = str(uuid.uuid4()) if not ElectionLog.objects.filter(id=new_id).exists(): return new_id ``` In this solution, the `generate_election_log_id` function uses a while loop to continuous...
magicoder
python
You are tasked with implementing a Python function that processes a table of data and performs specific operations on it. The table is represented as a list of tuples, where each tuple contains information about a person. The information includes the person's name, alias, points, and awake status. The table is generate...
```python import re from table import generate_table def process_table(table): # Filter the table to include only those persons with more than 100 points filtered_table = [person for person in table if person[2] > 100] # Sort the filtered table based on the person's name in ascending order sorted_tabl...
magicoder
python
You are tasked with creating a program that can parse and extract the domain name from a given URL. The domain name is the sequence of characters between the "http://" or "https://" and the next "/" in the URL. For example, in the URL "http://www.example.com/page1", the domain name is "www.example.com". Write a functi...
```python def extractDomainName(url: str) -> str: start_index = url.find("//") + 2 end_index = url.find("/", start_index) return url[start_index:end_index] # Test cases print(extractDomainName("http://www.example.com/page1")) # Output: "www.example.com" print(extractDomainName("https://subdomain.example.o...
magicoder
python
You are tasked with implementing a function that processes a table of product ratings and returns the average rating for each product. The table is represented as a list of dictionaries, where each dictionary contains the product name, date, and rating. Your function should calculate the average rating for each product...
```python def calculate_average_ratings(ratings): product_ratings = {} product_counts = {} for entry in ratings: product = entry['product'] rating = entry['rating'] if product in product_ratings: product_ratings[product] += rating product_counts[...
magicoder
python
You are given a Python code snippet that involves the manipulation of a 3D array `q` based on the dimensions of arrays `G`, `x`, and `P`. Your task is to write a function that takes in the arrays `G`, `x`, `P`, and `q_raw` as input and returns the modified 3D array `q` based on the operations performed in the given cod...
```python import numpy as np def modify_q(G, x, P, q_raw): lenG = len(G) lenx = len(x) lenP = len(P) q = np.zeros((lenG, lenx, lenP)) for i in range(lenG): for j in range(lenx): for k in range(lenP): if i + k * lenG < len(q_raw) and j < len(q_raw[0]): ...
magicoder
python
You are tasked with creating a Python program that processes a given directory and its subdirectories to find all image files and then convert them to a different format using the `subprocess` module. Your program should take the input directory path, the output directory path, and the desired image format as command-l...
```python import os import sys import subprocess def convert_images(input_dir, output_dir, target_format): for root, dirs, files in os.walk(input_dir): for file in files: if file.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp')): input_path = os.path.join(root, file) ...
magicoder
python
You are tasked with creating a program to send email notifications to users based on certain conditions. Your program should utilize the `System.Net.Mail` namespace in C# to send emails. You need to implement a method that takes in the recipient's email address, subject, and body of the email, and sends the email using...
```csharp using System.Net; using System.Net.Mail; public class EmailNotifier { private string smtpHost; private int smtpPort; private string smtpUsername; private string smtpPassword; public EmailNotifier(string host, int port, string username, string password) { smtpHost = host; ...
magicoder
csharp
You are tasked with creating a Python function that processes a collection of files and extracts specific information from each file. The function should utilize regular expressions to extract data from the files and store the extracted information in a structured format. You are provided with a code snippet that iter...
```python import glob import re def process_files(pathglob): file_data = [] rssrx = re.compile(r'kb=(\d+)') sizerx = re.compile(r'size=(\d+)') for path in glob.iglob(pathglob): with open(path) as f: first_line = f.readline() kb_match = rssrx.search(first_line) ...
magicoder
python
You are working on a project to process data from a scientific instrument that captures images using various filters and settings. The instrument produces an XML file containing information about the filters used, including the number of exposures, integrations, groups, filter name, mask, and readout pattern. Your task...
```python import xml.etree.ElementTree as ET def process_filters(xml_file_path): try: filter_info = {} tree = ET.parse(xml_file_path) root = tree.getroot() ns = root.find("NS").text log_error = root.find("LOG/error").text filters = root.find("{}:Template/{}:Filters"...
magicoder
python
You are tasked with creating a Python class that processes and stores contact information. The class should have methods for adding new contacts, retrieving contacts by email address, and displaying all contacts in a user-friendly format. Create a class `ContactManager` with the following methods: 1. `add_contact(emai...
```python class ContactManager: def __init__(self): self.contacts = {} def add_contact(self, email, name, phone): self.contacts[email] = {'name': name, 'phone': phone} def get_contact(self, email): contact = self.contacts.get(email) if contact: return f"Name: {c...
magicoder
python
You are tasked with implementing a function to determine the number of occurrences of a given substring within a larger string. The function should take two string inputs: the larger string and the substring to search for. The function should return the count of occurrences of the substring within the larger string. F...
```python def countSubstringOccurrences(larger_string: str, substring: str) -> int: count = 0 start = 0 while start < len(larger_string): index = larger_string.find(substring, start) if index != -1: count += 1 start = index + 1 else: break retu...
magicoder
python
You are tasked with implementing a job scheduling system using Rust. The `jobs` module contains the necessary structures and functions for managing jobs. Your task is to complete the implementation of the `jobs` module by defining a job scheduling algorithm. The `jobs` module contains the following structures: ```rust...
```rust impl JobQueue { pub fn schedule_jobs(&mut self) { self.jobs.sort_by_key(|job| job.priority); self.jobs.reverse(); } } ``` In the solution, the `schedule_jobs` function uses the `sort_by_key` method to sort the jobs based on their priority. Then, it reverses the order of the jobs to ensu...
magicoder
rust
You are tasked with creating a program that reads data from a CSV file, performs some operations on the data, and then writes the modified data back to a new CSV file. The given code snippet is a part of the program that writes the modified data to the new CSV file. Your task is to implement the function `modify_and_w...
```python import csv def modify_and_write_to_csv(input_file, output_file): with open(input_file, 'r') as file: reader = csv.reader(file) header = next(reader) data = [row for row in reader] for row in data: row[1] = int(row[1]) # Convert Quantity to integer row.append(...
magicoder
python
You are working on a bioinformatics project that involves processing DNA sequences using a specialized data structure called a label hash. The label hash is used to efficiently store and query k-mers, which are substrings of length k within a DNA sequence. In this project, you need to implement a function to process DN...
```python def tag_join_across_consume(ht): # Perform tagging/joining across consume operation # Logic to combine partitions based on tagging and joining # Your implementation of tagging/joining across consume operation goes here return ht # Return the modified label hash ``` In the solution, you wou...
magicoder
python
You are tasked with creating a Python function that simulates the behavior of a process manager for a simplified version of the Linux operating system. The process manager will be responsible for managing the lifecycle of processes, including starting, terminating, and monitoring them. Your task is to implement a Pyth...
```python import os import signal import subprocess class ProcessManager: def __init__(self): self.processes = {} def start_process(self, name: str, command: str) -> int: process = subprocess.Popen(command, shell=True) pid = process.pid self.processes[pid] = {"pid": pid, "name"...
magicoder
python
You are tasked with designing a Java class that models a simple library system. The library contains books, and each book has a unique ISBN (International Standard Book Number). Your task is to create a class `Library` that manages the books in the library. The `Library` class should have the following functionalities:...
```java import java.util.HashMap; import java.util.Map; public class Library { private Map<String, Book> books; public Library() { this.books = new HashMap<>(); } public void addBook(String isbn, String title, String author) { if (!books.containsKey(isbn)) { Book newBook =...
magicoder
java
You are tasked with implementing a background task handler for a watchOS app. The provided code snippet shows a function `handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>)` which is responsible for handling background tasks. Your goal is to extend this function to handle different types of background tasks and ex...
```swift func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) { for task in backgroundTasks { if let applicationTask = task as? WKApplicationRefreshBackgroundTask { logger.debug("Handling WKApplicationRefreshBackgroundTask...") // Trigger a refresh of the application's conten...
magicoder
swift
You are tasked with implementing a simplified version of a key-value store in Python. Your task is to create a class `KeyValueStore` with the following functionalities: 1. `__init__`: Initialize an empty key-value store. 2. `set`: Add a key-value pair to the store. If the key already exists, update its value. 3. `get`...
```python class KeyValueStore: def __init__(self): self.store = {} def set(self, key, value): self.store[key] = value def get(self, key): return self.store.get(key) def delete(self, key): if key in self.store: del self.store[key] ``` The `KeyValueStore` cla...
magicoder
python
You are given a string representing a text document. Your task is to write a function that counts the frequency of each word in the document and returns a dictionary where the keys are the unique words and the values are the frequencies of those words. Your function should ignore punctuation and be case-insensitive, ...
```python import re def word_frequency(text: str) -> dict: # Remove punctuation and convert to lowercase clean_text = re.sub(r'[^\w\s]', '', text).lower() # Split the text into words words = clean_text.split() # Count the frequency of each word frequency = {} for word in words: ...
magicoder
python
You are tasked with implementing a reinforcement learning algorithm using a neural network for Q-learning. The given code snippet is part of the Q-learning algorithm and involves processing Q-values for a batch of observations. You are provided with the following variables: - `q`: A tensor representing Q-values for th...
```python import torch.nn.functional as F # Calculate the target Q-values for the current observations q_target = BATCH.rew + (1 - BATCH.done) * self.gamma * q_target_next.gather(2, next_max_action.unsqueeze(-1)).squeeze(-1) # Calculate the Q-values for the taken actions q_pred = q.gather(2, BATCH.act.unsqueeze(-1))....
magicoder
python
You are tasked with creating a program that simulates a simple banking system. The program should allow users to create accounts, deposit and withdraw funds, and check their balance. Each account should have a unique account number, and the program should be able to handle multiple accounts. Your task is to implement ...
```java import java.util.HashMap; import java.util.Map; import java.util.Scanner; class Account { private String name; private double balance; public Account(String name, double initialBalance) { this.name = name; this.balance = initialBalance; } public String getName() { ...
magicoder
java
You are tasked with implementing a function to determine whether a given binary tree is a valid binary search tree (BST). A BST is a binary tree where each node has a key, and for any node, all keys in its left subtree are less than the node's key, and all keys in its right subtree are greater than the node's key. You...
```python class TreeNode: def __init__(self, key): self.key = key self.left = None self.right = None def isBST(tree, lastNode=[float("-infinity")]): if tree is None: return True # Check the left subtree if not isBST(tree.left, lastNode): return False # Chec...
magicoder
python