query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with implementing a class for managing financial instruments, specifically a Floating Rate Bond. The given code snippet is a part of a Python class that deals with encoding and decoding Floating Rate Bond objects using the FlatBuffers library. Your task is to create a method within the FloatingRateBond c...
```python class FloatingRateBond: # Other methods and attributes are not shown for brevity def calculate_accrued_interest(self, nominal_interest_rate, face_value, accrual_period, base_value): accrued_interest = (nominal_interest_rate * face_value * accrual_period) / base_value return accrued_in...
magicoder
python
You are given a list of strings, where each string represents a fragment of a larger string. Your task is to find the shortest superstring that contains all the given fragments. A superstring is a string that contains all the given strings as substrings. Write a function `shortestSuperstring` to find the shortest supe...
```python from itertools import permutations class Solution: def shortestSuperstring(self, A: List[str]) -> str: def overlap(a, b): max_overlap = 0 for i in range(min(len(a), len(b)), -1, -1): if a.endswith(b[:i]): return i return max_...
magicoder
python
You are given an array `buffer` of length `n`, initially filled with zeros. You need to fill the array with the minimum number of operations required to transform each element `i` into a specific value. The operation allowed is to increment the value of an element by 1. However, if the index `i` is divisible by 2, you ...
```python from typing import List def minOperations(buffer: List[int], n: int) -> int: for i in range(1, n): buffer[i] = buffer[i - 1] + 1 if i % 2 == 0: buffer[i] = min(buffer[i], buffer[i // 2] + 1) return buffer[n - 1] # Test the function buffer = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ...
magicoder
python
You are tasked with implementing a function to resize an image based on certain constraints. The function should take an input image and resize it to fit within specified dimensions, while also returning additional information about the resizing process. Write a function `resize_image` that takes the following paramet...
```python import numpy as np def resize_image(image, min_dim, max_dim, padding): original_shape = image.shape # Calculate the dimensions for resizing while maintaining aspect ratio h, w = original_shape[:2] scale = min(max_dim / max(h, w), min_dim / min(h, w)) new_h, new_w = int(round(h * scale)), ...
magicoder
python
You are tasked with implementing a graph data structure and performing various operations on it. The graph will be represented using an adjacency list. You need to implement the following operations for the graph: 1. Add a vertex to the graph. 2. Add an edge between two vertices. 3. Remove a vertex and all its associa...
```python class Graph: def __init__(self): self.adjacency_list = {} def add_vertex(self, vertex): if vertex not in self.adjacency_list: self.adjacency_list[vertex] = [] def add_edge(self, vertex1, vertex2): if vertex1 in self.adjacency_list and vertex2 in self.adjacency...
magicoder
python
You are tasked with implementing a CSS class parser that can extract and count the number of unique CSS classes used in a given CSS file. A CSS class is defined as any string that follows the period (.) character and is immediately followed by a valid class name. The parser should ignore any pseudo-classes or pseudo-el...
```javascript function countUniqueCSSClasses(cssContent) { // Regular expression to match CSS classes const classRegex = /\.([a-zA-Z][\w-]*)/g; let uniqueClasses = new Set(); // Extract and store unique CSS classes let match; while ((match = classRegex.exec(cssContent)) !== null) { ...
magicoder
javascript
You are given a list of integers representing the scores of a game. The game has a rule that a player can only score if the previous two scores are both even. If the player's score is even, it is added to the total score; otherwise, it is ignored. Write a function `calculate_total_score(scores)` that takes in the list ...
```python from typing import List def calculate_total_score(scores: List[int]) -> int: total_score = 0 prev_prev_even = False # Initialize the flag for the previous two scores being even prev_even = False # Initialize the flag for the previous score being even for score in scores: if score %...
magicoder
python
You are tasked with implementing a function that constructs a binary search tree (BST) from a given list of prices. Each node in the BST represents a price, and the left child of a node contains prices lower than the node's price, while the right child contains prices higher than the node's price. The function should r...
```python from typing import List class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def construct_price_bst(prices: List[int]) -> TreeNode: def insert_node(root, val): if not root: return TreeNode(va...
magicoder
python
You are tasked with creating a Python function that generates a recurrent neural network (RNN) model for a given sequence length and set of parameters. The function should be able to create both unidirectional and bidirectional RNN models using the Keras library. The function should take the following inputs: - `seq_l...
```python import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers def create_rnn_model(seq_length, params): model = keras.Sequential() if params['bidirectional']: model.add(layers.Bidirectional(layers.GRU(units=params['units']), input_shape=(seq_length, 1))) el...
magicoder
python
You are tasked with implementing a Monte Carlo Tree Search (MCTS) algorithm for a game-playing AI. The MCTS algorithm is used to make decisions in a game by simulating multiple possible moves and selecting the best one based on the simulation results. Your goal is to complete the implementation of the MCTS algorithm by...
```python import time import random class MctsNode: def __init__(self, state): self.state = state self.games = 0 self.wins = 0 self.children = [] class MctsAlgorithm: def __init__(self, tree): self.tree = tree self.stats = Stats() def run(self, n): ...
magicoder
python
You are tasked with implementing a function to build a URL query string from a dictionary of parameters. The function should take a dictionary of parameters and an optional convention string as input and return a URL query string. The function signature should be: ```python def http_build_query(params: dict, conventio...
```python def http_build_query(params: dict, convention: str = "%s") -> str: if len(params) == 0: return "" output = [] for key, value in params.items(): if isinstance(value, list): for i, v in enumerate(value): output.append(f"{key}{convention % i}={v}") ...
magicoder
python
You are tasked with implementing a function that validates the client's IP address based on a given HTTP request. The function should extract the real IP address from the request's metadata and compare it with a list of allowed IP addresses for a specific group. If the extracted IP address is found in the list of allow...
```python def my_key(group, request, allowed_ips): try: real_ip = request.META.get('HTTP_X_FORWARDED_FOR') if real_ip: real_ip = real_ip.split(',')[0].strip() # Extract the first IP if multiple IPs are present if real_ip in allowed_ips.get(group, []): return ...
magicoder
python
You are tasked with implementing a function to calculate the SHA-256 hash of a file using Python. The SHA-256 algorithm is a widely used cryptographic hash function that produces a 256-bit (32-byte) hash value. Your task is to create a Python function that takes a filename as input, reads the file in blocks, and then c...
```python import hashlib def sha256_file(filename: str, block_size: int = 65536) -> None: digest = hashlib.sha256() # Create a SHA-256 hash object with open(filename, 'rb') as f: # Open the file in binary mode for chunk in iter(lambda: f.read(block_size), b''): # Read the file in blocks ...
magicoder
python
You are tasked with implementing a statistical summary function for a dataset. The function should calculate various statistical measures such as count, mean, standard deviation, minimum value, and specified percentiles. You are given a code snippet that initializes the percentiles and headers for the summary. Your ta...
```rust use std::collections::HashMap; use statrs::statistics::Statistics; fn calculate_summary(dataset: &[f64]) -> HashMap<String, f64> { let mut summary: HashMap<String, f64> = HashMap::new(); let count = dataset.len() as f64; let mean = dataset.iter().sum::<f64>() / count; let std = dataset.populat...
magicoder
rust
You are tasked with implementing a function to parse and process a network socket's received data. The function should extract and process the received data to determine if it meets specific criteria. You are given a code snippet of a PHP function `check_socket()` that initializes a variable `$rx_buffer` to store the...
```php private function check_socket() { $rx_buffer = ""; // Received data from the network socket // Check if the received data contains a specific keyword "SUCCESS" if (strpos($rx_buffer, "SUCCESS") !== false) { return true; } // If the received data does not contain "SUCCESS", return f...
magicoder
php
You are tasked with creating a program that can determine the specificity of CSS selectors. In CSS, specificity is a weight that is applied to a given CSS declaration, determining which styles are ultimately applied to an element. The specificity is calculated based on the components of a selector. The components are r...
```python from typing import List def calculate_specificity(selector: str) -> List[int]: inline_styles = selector.count("style=") ids = selector.count("#") classes_pseudo_attrs = selector.count(".") + selector.count(":") + selector.count("[") elements_pseudo_elements = selector.count(" ") + 1 # Counti...
magicoder
python
You are tasked with creating a parallel rendering algorithm for a graphics processing unit (GPU). The algorithm should render an image by accumulating multiple samples on top of each other. The provided code snippet is a part of the existing rendering framework and contains a method `render` that is responsible for ren...
```rust use std::time::{Duration, Instant}; impl Renderer { /// Render another sample of the image, adding it on top of the already accumulated buffer. pub fn render(&mut self, use_optix: bool) -> Result<Duration, RenderError> { let module = &self.module; let stream = &self.stream; let...
magicoder
rust
You are tasked with creating a C# wrapper for a native library that provides access to key-related functionalities in a UI framework. The given code snippet contains C# declarations for three external functions that interface with the native library using PInvoke. Your goal is to implement the corresponding C# wrapper ...
```csharp using System; using System.Runtime.InteropServices; public class KeyWrapper { // Retrieves the state of a key using the native library function StateGet public int GetKeyState(IntPtr keyHandle) { return NativeMethods.StateGet(new HandleRef(this, keyHandle)); } // Retrieves the lo...
magicoder
csharp
You are tasked with creating a Python module for a robotics simulation system. The module should include functions for reading instrument and detector descriptions, as well as for simulating a robotic sequence. Your task is to implement the necessary functions to achieve this. You are provided with a code snippet that...
```python # Implement the required functions and classes # Function to read instrument description file def read_instrument_description_file(file_path): # Implementation to read and return instrument description from the file pass # Function to read detector description def read_detector_description(detector_...
magicoder
python
You are tasked with implementing a Python class that represents a URL object. The class should have methods to parse the URL and extract its components such as the protocol, domain, path, query parameters, and fragment. Your task is to complete the implementation of the `URLParser` class by adding the necessary method...
```python import urllib.parse class URLParser: def __init__(self, url): self.url = url def parse_protocol(self): return urllib.parse.urlparse(self.url).scheme def parse_domain(self): return urllib.parse.urlparse(self.url).netloc def parse_path(self): return urllib.par...
magicoder
python
You are tasked with creating a Python function that simulates the behavior of the `shutil.rmtree()` function, which recursively removes a directory and its contents. Your function should handle potential errors that may occur during the deletion process. Write a Python function called `safe_remove_directory(path)` tha...
```python import shutil def safe_remove_directory(path): try: shutil.rmtree(path) except OSError as err: print(f"Unable to delete directory {path} due to: {err}") # Example usage directory_path = '/path/to/directory' safe_remove_directory(directory_path) ``` The `safe_remove_directory()` func...
magicoder
python
You are tasked with implementing a permission filter for a system that lists ATBDs (Algorithm Theoretical Basis Documents) along with their summary version information. The system should only display versions with status "Published" if the user is not logged in. Additionally, if a user is logged in and has a specific r...
```python from typing import List, Optional class ATBD: def __init__(self, name: str, version: str, status: str): self.name = name self.version = version self.status = status class UserInfo: def __init__(self, sub: str): self.sub = sub def filter_ATBDs(role: str, user: Optiona...
magicoder
python
You are tasked with creating a function that processes file names and paths based on a given directory and file name string. The function should handle the scenario where a file with the same name already exists in the directory. Write a function `processFileNameAndPath` that takes in three parameters: - `log_dir`: A...
```php function processFileNameAndPath($log_dir, $ResultFileNameStr, $fileExtension) { $aryFileName = getFileNameAndPath($log_dir, $ResultFileNameStr, $fileExtension); if (count($aryFileName) > 0) { $baseFileName = $ResultFileNameStr; $counter = 1; while (in_array($baseFile...
magicoder
php
You are given a PHP array `$input` that contains a nested structure of keys and values. The keys are strings, and the values can be either integers or arrays with the same structure. Your task is to write a function `flattenArray($input)` that takes this nested array as input and returns a flattened array where the key...
```php function flattenArray($input, $prefix = '') { $result = []; foreach ($input as $key => $value) { if (is_array($value)) { $result = array_merge($result, flattenArray($value, $prefix . $key . '_')); } else { $result[$prefix . $key] = $value; } } retur...
magicoder
php
You are tasked with creating a Python function that processes linguistic features of words in a text. The function should take a word object as input and extract relevant morphological features from it. The morphological features are represented as a string in the format "key1=value1|key2=value2|...|keyN=valueN". The f...
```python def extract_morphological_features(word, featlst): if word.feats: # Check if morphological features exist # Create a dictionary from the morphological features string morph_feat_dict = dict(x.split("=") for x in word.feats.split("|")) feat_form = '' for feat in featlst: ...
magicoder
python
You are tasked with implementing a custom neural network layer in PyTorch. The layer, named `CustomLayer`, consists of the following components: - `split_token`: a learnable parameter initialized with Xavier uniform distribution, represented as a 1x`h_dim` tensor. - `operation_mix`: an instance of the `OperationMix` cl...
```python import torch import torch.nn as nn class CustomLayer(nn.Module): def __init__(self, h_dim, num_layers, dropout): super(CustomLayer, self).__init__() self.split_token = nn.Parameter(torch.Tensor(1, h_dim)) torch.nn.init.xavier_uniform_(self.split_token.data) self.operation_...
magicoder
python
You are working on a healthcare data processing system that deals with blood pressure measurements. Your task is to write a Python function that calculates the standard deviation and variability of diastolic blood pressure readings from a given dataset. You are given the following code snippet as a starting point: ``...
```python from typing import List, Tuple import statistics def calculate_diastolic_stats(data: List[float]) -> Tuple[float, float]: if not data: return 0, 0 # Handle empty input list std_dev = statistics.stdev(data) if len(data) > 1 else 0 # Calculate standard deviation variability = max(data) -...
magicoder
python
You are tasked with creating a Python program that processes files within a specified directory. The program should perform the following tasks: 1. List all the files in the specified directory. 2. For each file, determine its size in bytes and the date and time it was last modified. 3. Print the file name, size, and ...
```python import os import datetime def file_process(dir): files = os.listdir(dir) for file in files: file_path = os.path.join(dir, file) if os.path.isfile(file_path): file_size = os.path.getsize(file_path) last_modified = os.path.getmtime(file_path) last_mod...
magicoder
python
You are tasked with creating a Python function that processes data from a file bundle and performs specific operations on the data. The file bundle contains multiple data files, each with a specific format and content. Your function should be able to read the data from these files, process it according to certain rules...
```python from typing import Any from data_processing import process_text_data, process_csv_data, process_json_data def process_data_from_bundle(bundle_path: str) -> Any: processed_result = [] file_paths = get_file_paths_from_bundle(bundle_path) # Assume this function returns a list of file paths in the bundl...
magicoder
python
You are tasked with creating a Python package management system that can dynamically load and instantiate frontend modules for various components of a multimedia application. The package structure follows a specific naming convention, and the system should be able to identify and load these modules at runtime. Your ta...
```python import importlib import pkgutil def load_frontend_module(name, frontendArgs=None, frontendArgsNamespace=None): module_path = f"multimedia_package.{name}.frontend" module = importlib.import_module(module_path) frontend_instance = module.Frontend(args=frontendArgs, namespace=frontendArgsNamespace) ...
magicoder
python
You are tasked with creating a Python function that simulates a simple card game. The game involves drawing cards from a standard 52-card deck and comparing the drawn cards to determine the winner. The function should take two arguments: `player1` and `player2`, each representing a list of cards drawn by the respective...
```python def compare_cards(player1, player2): if not player1 or not player2: return "No cards to compare!" card_values = {'2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'J': 11, 'Q': 12, 'K': 13, 'A': 14} card_suits = {'H': 1, 'D': 2, 'C': 3, 'S': 4} last_card_playe...
magicoder
python
You are tasked with implementing a Java interface for handling Base64-encoded CSV files. The interface, `Base64SpiConstants`, contains two constants related to the Base64-encoded CSV file format. The constant `BASE64_CSV_FILE_TYPE` represents the file type, and `DEFAULT_CSV_CELL_SEPARATOR` represents the default separa...
```java package com.github.chenjianjx.ssioextsample.spi.clientexternal.base64csv; import java.io.*; import java.util.Base64; import java.util.List; public class Base64CsvHandler implements Base64SpiConstants { @Override public String readBase64CsvFile(String filePath) { try (BufferedReader reader = n...
magicoder
java
You are tasked with creating a custom tag helper for a Razor Pages application. Tag helpers are a feature in ASP.NET Core that enables server-side code to participate in creating and rendering HTML elements in Razor files. In this problem, you will be implementing a custom tag helper to enhance the functionality of a R...
To create a custom tag helper for the Razor Pages application, you can follow the steps below: 1. Create a new class that inherits from TagHelper class provided by ASP.NET Core. ```csharp using Microsoft.AspNetCore.Razor.TagHelpers; namespace SampleRazorPagesApplication { public class CustomTagHelper : TagHelper ...
magicoder
csharp
You are tasked with implementing a function that processes execution blocks and methods. An execution block is a unit of code that needs to be executed, and a method is a set of instructions for processing execution blocks. Your goal is to create a function that takes in two lists of execution blocks, along with a set ...
```python from typing import List, Dict, Any class ExecutionBlock: pass # Placeholder for the ExecutionBlock class definition class Methods: pass # Placeholder for the Methods class definition class parserReturnType: pass # Placeholder for the parserReturnType class definition def block_executor(ebs:...
magicoder
python
You are tasked with implementing a circular buffer data structure to store health entries in a health monitoring system. The circular buffer should have a maximum capacity of 50 entries, and when the buffer is full, adding a new entry should replace the oldest entry in the buffer. Your task is to implement the `Circula...
```csharp using System; using System.Collections.Generic; public class BadHealthEntry { public DateTime Timestamp { get; set; } public string Message { get; set; } } public class CircularHealthBuffer { private List<BadHealthEntry> _entries; private int _currentIndex; public CircularHealthBuffer()...
magicoder
csharp
You are tasked with creating a Python function that processes a list of file paths and extracts specific information from each file. The function should take in three parameters: `save_dir` (string), `wsi_patch_info_dir` (string), and `extract_info` (function). The `wsi_patch_info_dir` contains multiple text files, eac...
```python import os from glob import glob import os.path as osp def process_bag_files(save_dir: str, wsi_patch_info_dir: str, extract_info: callable) -> None: bag_fp_list = glob(osp.join(wsi_patch_info_dir, '*.txt')) for bag_fp in bag_fp_list: extracted_info = extract_info(bag_fp) file_name = o...
magicoder
python
You are tasked with implementing a Python function that removes items from a given set that are also present in another set. You need to write a function `remove_items` that takes two sets, `setA` and `setB`, as input and returns a new set containing the elements from `setA` that are not present in `setB`. The functio...
```python def remove_items(setA: set, setB: set) -> set: return setA - setB ``` The `remove_items` function uses the set difference operator `-` to return a new set containing the elements from `setA` that are not present in `setB`. This operator efficiently removes the common elements from `setA` and returns the ...
magicoder
python
You are tasked with implementing a function to process log data and calculate statistical values for visualization. The function takes a list of log data as input and performs the following operations: 1. Prepends a 0 to each log_info array in the list. 2. Determines the minimum length among all log_info arrays. 3. Tru...
```python import numpy as np from typing import List, Tuple def process_log_data(log_infos: List[np.ndarray]) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: log_infos = [np.append([0], log_info) for log_info in log_infos] # Prepends 0 to each log_info array min_length = min(map(len, log_infos)) # ...
magicoder
python
You are tasked with implementing a text-based inventory management system for a game. The system should allow the player to add, remove, and display items in their inventory. The player should also be able to consume items from their inventory. You are given a partial code snippet for the inventory management system. ...
```python class InventoryManager: def __init__(self): self.inventory = [] def add_item(self, item): self.inventory.append(item) print(f"{item} added to the inventory.") def remove_item(self, item): if item in self.inventory: self.inventory.remove(item) ...
magicoder
python
You are tasked with implementing a concrete subclass of the `TransactionCreator` abstract class in Python. The `TransactionCreator` class has two abstract methods: `estimate_cost_for_certificate_batch` and `create_transaction`. Your task is to create a subclass called `CertificateTransactionCreator` that implements the...
```python from abc import ABC, abstractmethod ESTIMATE_NUM_INPUTS = 1 # Default value for num_inputs class TransactionCreator(ABC): @abstractmethod def estimate_cost_for_certificate_batch(self, tx_cost_constants, num_inputs=ESTIMATE_NUM_INPUTS): pass @abstractmethod def create_transaction(se...
magicoder
python
You are tasked with creating a Python function that processes a string containing information about authors and their emails. The input string follows a specific format where author names and emails are listed in a comma-separated format. Your task is to extract the author names and their corresponding emails and retur...
```python import re def extract_authors_emails(input_str: str) -> dict: author_names = re.findall(r'"(.*?)"', input_str) author_emails = re.findall(r'author_email="(.*?)"', input_str) maintainer_email = re.search(r'maintainer_email="(.*?)"', input_str).group(1) authors_emails_dict = {} for i in ra...
magicoder
python
You are tasked with implementing a function that validates the format of an email address. The function should take a string as input and return a boolean value indicating whether the input string is a valid email address or not. For the purpose of this problem, a valid email address should adhere to the following rule...
```python import re def validateEmail(email): pattern = r'^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$' return bool(re.match(pattern, email)) ``` The `validateEmail` function uses the `re` module in Python to match the input email address against a regular expression pattern. The pattern checks for the requ...
magicoder
python
You are given a string `S` containing alphanumeric and non-alphanumeric characters. Your task is to implement a function that rearranges the string such that all the non-alphabetic characters are moved to the end of the string, while maintaining the relative order of the alphabetic characters. The function should retur...
```python def rearrange_string(S: str) -> str: arr = list(S) i, j = 0, len(arr) - 1 while i < j: if not arr[i].isalpha(): i += 1 elif not arr[j].isalpha(): j -= 1 else: arr[i], arr[j] = arr[j], arr[i] i += 1 j -= 1 retur...
magicoder
python
You are tasked with implementing a file validation system for a data processing application. The system should validate the data types and lengths of headers and control information in a file before adding a batch of data to it. You are provided with a `FileValidator` class that contains methods for validating data typ...
```php public function addBatch(Batch $batch) { if ($this->validator->validateDataTypes($this->header) && $this->validator->validateLengths($this->control) && $this->validator->validateDataTypes($this->control)) { // All validations passed, add the batch to the file // Add batch impl...
magicoder
php
You are tasked with creating a Python program that simulates a simple game of rock-paper-scissors. The program should allow a user to play against the computer. The game should consist of a series of rounds, and the winner of each round should be determined based on the classic rules of rock-paper-scissors: rock beats ...
```python import random def get_user_choice(): while True: user_choice = input("Enter your choice (rock, paper, or scissors), or 'q' to quit: ").lower() if user_choice in ['rock', 'paper', 'scissors', 'q']: return user_choice else: print("Invalid choice. Please try a...
magicoder
python
You are tasked with creating a Python function that interacts with a PostgreSQL database using asynchronous programming techniques. The function should connect to the database, execute a query to retrieve the count of records from a specified table in a given schema, and then return the count as a result. If an error o...
```python import asyncio import asyncpg async def get_record_count(schema: str, table: str) -> Union[int, str]: try: # Establish a connection to the PostgreSQL database conn = await asyncpg.connect(user='username', password='password', database='dbname', host='l...
magicoder
python
You are tasked with implementing a generic method for performing conditional computation in Java. The method `computeIfMatch` takes three parameters: `target`, `predicate`, and `mapping`. The `target` represents the input value, the `predicate` is a condition that the `target` must satisfy, and the `mapping` is a funct...
```java import java.util.function.Function; import java.util.function.Predicate; public class ConditionalComputation { public static <T, R> R computeIfMatch(T target, Predicate<T> predicate, Function<T, R> mapping) { return predicate.test(target) ? mapping.apply(target) : null; } public static voi...
magicoder
java
You are tasked with implementing a simplified version of a web-based drawing game. The provided code snippet is part of the server-side logic for handling drawing submissions from players. The game involves two players, and each player takes turns drawing an image based on a prompt. The code snippet checks if the curr...
```python # Assuming the existence of a Game and Player class class Game: def __init__(self, player1=None, player2=None): self.player1 = player1 self.player2 = player2 class Player: def __init__(self, user): self.user = user self.hasDrawed = False # Assuming request.user repres...
magicoder
python
You are tasked with creating a program that processes a simplified version of Markdown text. Your program should be able to recognize and convert a specific subset of Markdown syntax into HTML. The subset of Markdown syntax to be supported includes: 1. Headers: Lines starting with one or more `#` characters followed b...
```python import re def markdownToHTML(markdown: str) -> str: # Convert headers markdown = re.sub(r'^(#+)\s(.*)$', lambda match: f'<h{len(match.group(1))}>{match.group(2)}</h{len(match.group(1))}>', markdown, flags=re.MULTILINE) # Convert bold text markdown = re.sub(r'\*\*(.*?)\*\*', r'<strong>\1<...
magicoder
python
You are tasked with creating a Python class that represents a database table using SQLAlchemy. The table will store information about books, including their title, author, and genres. Your task is to define the SQLAlchemy model for this table and implement a method to query the database for books based on their genres....
```python from sqlalchemy import create_engine, Column, Integer, String, ARRAY from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker Base = declarative_base() class Book(Base): __tablename__ = 'books' id = Column(Integer, primary_key=True) title = Column(String) ...
magicoder
python
You are tasked with implementing a custom hook in React that manages the visibility of a component based on the user's scroll position. The hook should accept a reference to the component, as well as optional styles and additional props to be spread onto the component. When the component is scrolled into view, it shoul...
```jsx import { useState, useEffect } from 'react'; const useScrollVisibility = (ref, styles, rest) => { const [visible, setVisible] = useState(false); const handleScroll = () => { if (ref.current) { const top = ref.current.getBoundingClientRect().top; const bottom = ref.current.getBoundingClientR...
magicoder
jsx
You are tasked with creating a program that simulates a simple shell environment. The shell should support executing commands and changing the shell prompt. The supported shells are zsh and bash. When changing the shell, the prompt should reflect the change, and the available commands may differ based on the selected s...
```python import os class ShellEnvironment: def __init__(self, shell="zsh"): self.shell = shell self.prompt = f"{os.getcwd()} {os.getlogin()} $ " def execute_command(self, command): if command == "change_shell": self.change_shell() else: os.system(comman...
magicoder
python
You are tasked with implementing a generic expression interface for a simple expression tree in C#. The interface should define three properties and a generic method. The properties are: 1. `Cast` of type `BaseType`, representing the base type of the expression. 2. `DataType` of type `DataType`, representing the data ...
```csharp // Define the base type and data type enums public enum BaseType { Integer, String, Boolean } public enum DataType { Number, Text, Logical } // Define the expression visitor interface public interface IExpressionVisitor<T> { T VisitIntegerExpression(IExpression<BaseType, DataType> expression); T Visi...
magicoder
csharp
You are tasked with implementing a feedforward neural network using the provided `Network` class. The network will have a variable number of layers and neurons per layer. Your goal is to complete the implementation by adding the functionality to initialize the weights between the layers. The `Network` class has an `__...
```python class Network: def __init__(self, layer_sizes): # layer_sizes: list of numbers representing number of neurons per layer # Create a numpy array of biases for each layer except the (first) input layer self.biases = [rand.randn(l, 1) for l in layer_sizes[1:]] # Initialize th...
magicoder
python
You are tasked with implementing a simplified version of a state management library in TypeScript. The library should support defining a model with initial state, reducers, effects, and a method to reset the state. Your task is to complete the implementation of the `BasicDva` class by adding the necessary methods and p...
```typescript export class BasicDva<T> { state: T; initState: T; namespace: string; reducers?: Basic.Reducers<T>; effects?: Basic.Effects; resetState: Basic.ReducersFun<T>; constructor(ModelType: Basic.BaseModel<T>) { this.state = ModelType.state; this.initState = ModelType.state; this.namesp...
magicoder
typescript
You are working on a blockchain implementation and need to create a function to handle block creation and validation. The function `get_skips_and_block_making_time` returns the number of blocks to skip and the timestamp for block making. The `make_block` function is used to create a new block, and the `Transaction` cla...
```python def create_and_validate_block(chains, next_validator_id, privkeys, randaos, vchashes, ct, casper_config): skip_count, timestamp = get_skips_and_block_making_time(chains[1].state, next_validator_id) assert skip_count == 1 b3 = make_block(chains[1], privkeys[next_validator_id], randaos[next_validato...
magicoder
python
You are tasked with creating a program that fetches real-time cryptocurrency price data from different API endpoints and extracts specific information from the responses. The program should be able to handle multiple API endpoints and extract the required data based on the provided keys. You are given a list of API en...
```python import requests def fetch_crypto_data(api_data): result = {} for endpoint in api_data: url = endpoint[0] keys = endpoint[1:] response = requests.get(url) if response.status_code == 200: data = response.json() extracted_data = data fo...
magicoder
python
You are tasked with creating a layout manager for a user interface in a mobile application. The layout manager should be able to position and size UI elements based on a set of constraints. Each constraint is defined by a pair of UI elements and optional constants for positioning. The constraints are represented as met...
```swift class LayoutManager { var constraints: [String: NSLayoutConstraint] = [:] func addConstraint(_ constraint: NSLayoutConstraint, for key: String) { constraints[key] = constraint } func calculateLayout() { // Implement the layout calculation logic here // Iterate through ...
magicoder
swift
You are tasked with implementing a DAO (Data Access Object) for managing AttachmentType objects in a Java application. The AttachmentType class represents different types of attachments that can be associated with other entities in the application. Your goal is to create a DAO interface and its implementation using Goo...
```java // AttachmentTypeDAO.java package edu.upenn.cis.ppod.dao; import com.google.inject.ImplementedBy; import edu.upenn.cis.ppod.model.AttachmentType; @ImplementedBy(AttachmentTypeDAOImpl.class) public interface AttachmentTypeDAO { AttachmentType findById(long id); void save(AttachmentType attachmentType);...
magicoder
java
You are tasked with implementing a function that will take in a list of integers and return the median of the list. The median of a list of numbers is the middle number when the list is sorted in ascending order. If the list has an odd number of elements, the median is the middle number. If the list has an even number ...
```python from typing import List def find_median(nums: List[int]) -> float: nums.sort() n = len(nums) if n % 2 == 0: return (nums[n // 2 - 1] + nums[n // 2]) / 2 else: return float(nums[n // 2]) ``` The `find_median` function first sorts the input list `nums`. Then, it calculates the l...
magicoder
python
You are tasked with implementing a message consumer for a pub/sub system using Python's asyncio library. The provided code snippet is a part of the consumer logic, which is responsible for pulling messages from different channels. Your task is to complete the implementation of the `pull_message` method in the `PubSubCo...
```python import asyncio class PubSubConsumer: def __init__(self, channels, consumer_wait_time, pull_message_wait_time): self._channels = channels self._consumer_wait_time = consumer_wait_time self._pull_message_wait_time = pull_message_wait_time self._current_channel_index = 0 ...
magicoder
python
You are tasked with implementing a function that can retrieve a value from a JSON object using an array of integers and/or strings as a path. The JSON object may contain complex nested structures, and the path array will specify the sequence of keys or indices to traverse in order to reach the desired value. You need ...
```swift func getValueFromJSON(_ json: Any, _ path: [Any]) -> Any? { var current: Any? = json for component in path { if let key = component as? String, let dict = current as? [String: Any] { current = dict[key] } else if let index = component as? Int, let array = current as? [Any], ...
magicoder
swift
You are tasked with simulating a biochemical reaction using a Python package called `tellurium`. The code snippet provided initializes some variables and then uses the `tellurium` package to simulate a biochemical model. Your task is to write a Python function that takes the initialized variables and simulates the bioc...
```python import tellurium as te def simulate_biochemical_model(VM1, Keq1, h, V4, KS4): model = ''' # Define the biochemical model using the variables provided VM1 = {} Keq1 = {} h = {} V4 = {} KS4 = {} # Define the biochemical reactions and equations here # ... end''' # ...
magicoder
python
You are tasked with designing a Swift protocol for a Moonbeam bonus service. The protocol should define the required methods for interacting with the Moonbeam bonus service. The service is responsible for managing bonus rewards for participants in a crowdloan campaign on the Moonbeam network. The protocol should includ...
```swift // Define the MoonbeamBonusServiceProtocol protocol MoonbeamBonusServiceProtocol { var view: MoonbeamTermsViewProtocol? { get set } var assetInfo: AssetBalanceDisplayInfo { get } var wireframe: MoonbeamTermsWireframeProtocol { get } var interactor: MoonbeamTermsInteractorInputProtocol { get } ...
magicoder
swift
You are tasked with implementing a Python function that processes historical data from a machine learning model and visualizes the loss over epochs using matplotlib. The function should take the historical data as input and generate a plot showing the validation loss and training loss over the epochs. The function sig...
```python import matplotlib.pyplot as plt def plot_loss(history): plt.figure(figsize=(12,4)) plt.plot(history['val_loss']) plt.plot(history['loss']) plt.legend(['val_loss', 'loss']) plt.title('Loss') plt.xlabel('Epochs') plt.ylabel('Loss') plt.show() ``` The `plot_loss` function takes t...
magicoder
python
You are tasked with implementing a function to validate transaction pool statistics in a blockchain system. The provided code snippet is part of a blockchain node's codebase and contains a method for asserting transaction pool statistics. The `assert_tx_pool_statics` method is responsible for validating the total size...
```rust pub fn assert_tx_pool_statics(&self, total_tx_size: u64, total_tx_cycles: u64) { let tx_pool_info = self.get_tip_tx_pool_info(); assert_eq!(tx_pool_info.pending.value(), total_tx_size); assert_eq!(tx_pool_info.proposed.value(), total_tx_cycles); } ``` In the solution, the `assert_tx_pool_statics` m...
magicoder
rust
You are tasked with creating a Python function to process weather data stored in NetCDF files using the xarray library. The function should read multiple NetCDF files, extract specific weather data variables, and calculate the average value of these variables over a specified time period. Write a Python function `calc...
```python import xarray as xr import pandas as pd from glob import glob import os def calculate_weather_average(file_pattern, variable_names, start_date, end_date): # Find all files matching the file pattern files = glob(file_pattern) # Create an empty dictionary to store the average values averag...
magicoder
python
You are given a list of strings representing file paths. Each file path consists of a sequence of directories separated by slashes ("/"). Your task is to write a function that returns the longest common prefix among all the file paths. If there is no common prefix, the function should return an empty string. For examp...
```python from typing import List def longest_common_prefix(file_paths: List[str]) -> str: if not file_paths: return "" min_len = min(len(path) for path in file_paths) prefix = "" for i in range(min_len): char = file_paths[0][i] if all(path[i] == char for path in file_paths): ...
magicoder
python
You are tasked with creating a command-line tool that emulates the functionality of the `alias` command in Unix-like operating systems. The `alias` command allows users to create custom shortcuts for other commands or command sequences. Your tool should support creating, listing, and removing aliases for shell commands...
```python import os import sys import shlex ALIASES_FILE = os.path.expanduser("~/.custom_aliases") def load_aliases(): aliases = {} if os.path.exists(ALIASES_FILE): with open(ALIASES_FILE, "r") as file: for line in file: name, command = line.strip().split("=", 1) ...
magicoder
python
You are tasked with implementing a histogram matching algorithm to modify the pixel values of an input image based on the cumulative distribution functions (CDFs) of the input and a template image. The CDF of an image represents the cumulative distribution of pixel intensities, and histogram matching aims to transform ...
```python import numpy as np def pad_cdf(c, b): ''' c: CDF of input image computed with the function cdf() b: histogram of input image computed with the function hist() returns the padded CDF values ''' # pad the beginning and ending pixels and their CDF values c = np.insert(c, 0, [0] * b[0...
magicoder
python
You are tasked with implementing a custom button class in Swift that includes a feature to display an unread message count label. The custom button class should have the following requirements: - It should be a subclass of `UIButton`. - It should have a private property `unreadLabel` of type `UILabel` to display the un...
```swift import UIKit class ChatNavigationButton: UIButton { private let unreadLabel = UILabel() var unreadCount: Int = 0 { didSet { unreadLabel.isHidden = unreadCount == 0 unreadLabel.text = "\(unreadCount)" } } override init(frame: CGRect) { super.ini...
magicoder
swift
You are tasked with creating a simple image processing application. The application should allow users to load an image, apply a specified filter, and display the filtered image. To achieve this, you need to implement the following functionalities: 1. Load an image: Create a function that allows the user to select an ...
```csharp using System; using System.Drawing; using System.Windows.Forms; public class ImageProcessor { private PictureBox forgroundImageBox; // Assume this PictureBox is initialized and configured in the user interface // Function to load an image, apply a specified filter, and display the filtered image ...
magicoder
csharp
You are tasked with creating a program that analyzes the frequency of words in a given text file. Your program should read the contents of the text file, tokenize the words, and then count the frequency of each word. For the purpose of this problem, a word is defined as a sequence of characters separated by spaces or p...
```python import re def word_frequency_analysis(file_path, stop_words): word_freq = {} with open(file_path, 'r') as file: text = file.read().lower() # Read the file and convert the text to lowercase # Tokenize the words using regular expression words = re.findall(r'\b\w+\...
magicoder
python
You are tasked with implementing a simplified version of the `MoCoV2` class, which is used for contrastive learning in deep learning models. The provided code snippet is a partial implementation of the `MoCoV2` class in Python using PyTorch. Your task is to complete the implementation by adding a method to calculate th...
```python import torch.nn.functional as F class MoCoV2(object): def __init__(self, outputs_q, outputs_k, queue, t=0.07): super().__init__() self.outputs_q = F.normalize(outputs_q, dim=1) self.outputs_k = F.normalize(outputs_k, dim=1) self.queue = queue.clone().detach() def con...
magicoder
python
You are tasked with creating a plugin for a simulation environment using Gazebo, a popular robotics simulator. Your goal is to develop a plugin that loads a maze world and a robot model into the simulation environment. The provided code snippet is a part of the plugin that loads the maze world and a robot model. Your ...
```cpp #include <vector> #include <queue> #include <utility> #include <unordered_map> class MazeSolver { public: std::vector<std::pair<int, int>> findShortestPath(const std::vector<std::vector<int>>& maze, std::pair<int, int> start, ...
magicoder
cpp
You are tasked with creating a script to automate the deployment of a dashboard application using npm. The dashboard application is built using various front-end technologies such as React, Vue, or Angular. Your script should handle the deployment process, including building the application and starting the server. Yo...
```bash #!/bin/bash # Determine the type of dashboard application (React, Vue, or Angular) if [ -f "package.json" ]; then if grep -q '"vue"' package.json; then app_type="vue" elif grep -q '"@angular/core"' package.json; then app_type="angular" else app_type="react" fi else e...
magicoder
shell
You are tasked with implementing a lemmatization and stemming function for text preprocessing. Lemmatization involves reducing words to their base or dictionary form, while stemming involves reducing words to their root form. Your task is to create a Python function that takes a list of reviews as input, performs lemma...
```python from nltk.stem import WordNetLemmatizer from nltk.stem import PorterStemmer import nltk nltk.download('wordnet') def lemmatization(reviews): # Initialize lemmatizer and stemmer wn_lem = WordNetLemmatizer() stemmer = PorterStemmer() lemmatized_reviews = [] for review in reviews: ...
magicoder
python
You are tasked with implementing a function to swap the byte order of a given command header structure in a C++ program. The command header structure is defined as follows: ```cpp struct CommandHeader { USHORT CommandId; BYTE DestMachineId[MACHINE_ID_SIZE]; BYTE SrcMachineId[MACHINE_ID_SIZE]; }; ``` The f...
```cpp void ByteSwapCommandHeader(CommandHeader* pCommandHeader) { pCommandHeader->CommandId = ByteSwapShort(pCommandHeader->CommandId); for (int i = 0; i < MACHINE_ID_SIZE; i++) { pCommandHeader->DestMachineId[i] = ByteSwapByte(pCommandHeader->DestMachineId[i]); pCommandHeader->SrcMachineId[i] ...
magicoder
cpp
You are tasked with implementing a C++ function that generates an output stream for a deep tiled output part. The function signature is provided as follows: ```cpp void abi_gen_imf_deeptiledoutputpart(std::ostream& os); ``` Your task is to create a function `abi_gen_imf_deeptiledoutputpart` that takes an `std::ostrea...
```cpp #include <ostream> void abi_gen_imf_deeptiledoutputpart(std::ostream& os) { // Assume the deep tiled output part format is a placeholder for a specific format used in computer graphics and visual effects. // Generate the deep tiled output part content and write it to the provided output stream. // F...
magicoder
cpp
You are tasked with implementing a Java method to extract and format error messages from an exception as JSON. The method should take an exception object and a class name as input and return a JSON object containing the error message details. You are given the following method signature to implement: ```java public st...
```java import org.json.JSONArray; import org.json.JSONObject; public class ErrorUtil { public static JSONObject getMessageJSON(Exception exception, String endClass) { JSONObject jsonobj_error = new JSONObject(); JSONObject jsonobj_error_data = new JSONObject(); JSONArray jsonarray_element ...
magicoder
java
You are given a Python code snippet that seems to be incomplete. Your task is to complete the code by implementing a function that calculates the length of the longest consecutive subsequence of a given list of integers. The given code snippet is as follows: ```python <gh_stars>0 def length(t1, n): # Your implemen...
```python def length(t1, n): if not t1: return 0 t1_set = set(t1) max_length = 0 for num in t1_set: if num - 1 not in t1_set: current_num = num current_length = 1 while current_num + 1 in t1_set: current_num += 1 curr...
magicoder
python
You are tasked with implementing a file handling utility in Python. Your task is to create a program that allows users to copy the contents of one file to another, with the option to specify whether the destination file should be overwritten if it already exists. The program should provide a command-line interface for ...
```python import argparse import os import shutil def main(): parser = argparse.ArgumentParser(description='File handling utility') parser.add_argument('source', help='Path to the source file') parser.add_argument('destination', help='Path to the destination file') parser.add_argument('--overwrite', ac...
magicoder
python
You are tasked with implementing a function to calculate the volume of water that can be trapped in a series of connected vertical pillars. Each pillar has a specific height, and the distance between each pillar is uniform. The pillars are represented by an array of non-negative integers, where each integer represents ...
```python from typing import List def trapped_water_volume(pillar_heights: List[int]) -> int: n = len(pillar_heights) if n < 3: return 0 left_max = [0] * n right_max = [0] * n left_max[0] = pillar_heights[0] for i in range(1, n): left_max[i] = max(left_max[i-1], pillar_heights...
magicoder
python
You are tasked with implementing a class called `SortedStack` that represents a stack data structure with the following methods: 1. `push(value)`: Adds a new element `value` to the stack. 2. `pop()`: Removes and returns the top element from the stack. 3. `peek(index)`: Returns the element at the specified `index` from...
```python class SortedStack: def __init__(self): self.contents = [] self._sorted = False def push(self, value): self.contents.append(value) self._sorted = False def pop(self): if not self._sorted: self.sort() return self.contents.pop() def p...
magicoder
python
You are tasked with implementing a URL routing system for a web server. The server receives HTTP requests and needs to map the requested URL paths to corresponding handler functions based on predefined URL patterns. You are given a code snippet that iterates through a collection of URL patterns and checks if the curre...
```cpp #include <iostream> #include <vector> #include <memory> namespace http { class IRequest { // Define IRequest class members }; class IResponse { // Define IResponse class members }; } namespace conf { class Settings { // Define Settings class members }; } class ...
magicoder
cpp
You are tasked with implementing a control system for a Brushless DC Motor (BLDCM) using the given code snippet as a starting point. The code snippet initializes hall sensors and a timer for the BLDCM control. Your task is to complete the implementation by writing the necessary functions to control the BLDCM based on t...
```cpp // Define the commutation sequence for driving the BLDCM based on hall sensor inputs void commutateMotor(bool hallBState, bool hallCState) { if (hallBState && !hallCState) { // Commutation sequence for driving the BLDCM when hallB is high and hallC is low // Implement the corresponding motor ...
magicoder
cpp
You are tasked with implementing a function to find the range of a specific tag within a given tweet. The tag is represented by a string and is enclosed within "#" symbols. The function should return the start and end indices of the tag within the tweet. If the tag is not found, the function should return (-1, -1). Fu...
```swift func findTagRange(tweet: String, tag: String) -> (Int, Int) { if let start = tweet.range(of: "#\(tag)")?.lowerBound { let startIndex = tweet.distance(from: tweet.startIndex, to: start) let endIndex = startIndex + tag.count + 1 // +1 to account for the '#' symbol return (startIndex, ...
magicoder
swift
You are tasked with creating a Python class that simulates a simple configuration manager. The class should allow users to define configuration settings and retrieve them using attribute access. Additionally, the class should support a special mode called `orm_mode`, which, when enabled, should convert attribute access...
```python class Config: def __init__(self): self.settings = {} self.orm_mode = False def enable_orm_mode(self): self.orm_mode = True def __setattr__(self, name, value): if self.orm_mode: name = self._convert_to_snake_case(name) self.settings[name] = valu...
magicoder
python
You are tasked with implementing a class `ToFloat` that converts a given string to a floating-point number. The class should have a method `convert` that takes a string as input and returns the corresponding floating-point number. The conversion should handle both integer and decimal strings, and should also consider s...
```javascript class ToFloat { convert(str) { const trimmedStr = str.trim(); const parsedFloat = parseFloat(trimmedStr); return isNaN(parsedFloat) ? NaN : parsedFloat; } } // Test cases const converter = new ToFloat(); console.log(converter.convert(" 3.14 ")); // Output: 3.14 console.log(converter.conve...
magicoder
javascript
You are working on a project that involves analyzing text data within a SQL Server environment. Your task is to create a Python script that connects to a local SQL Server database, installs the "textblob" package using the `sqlmlutils` library, and then performs sentiment analysis on a specific table within the databas...
```python import sqlmlutils from textblob import TextBlob # Establish a connection to the local SQL Server database connection = sqlmlutils.ConnectionInfo(server="localhost", database="Test") try: # Install the "textblob" package using the sqlmlutils library sqlmlutils.SQLPackageManager(connection).install("t...
magicoder
python
You are tasked with implementing a Python function to compute the R2T pulse shape for nuclear magnetic resonance (NMR) experiments. The R2T pulse shape is determined by a match condition equation: [1 or 2]*wr - W_I_eff - W_S_eff = 0, where wr is a variable, and W_I_eff and W_S_eff are effective widths. Your function sh...
```python # R2T.py # Import necessary modules import sys sys.path.append(root.UtilPath.getTopspinHome() + '/exp/stan/nmr/py/BioPY/modules/') import R2T # Define the function to compute R2T pulse shape def compute_R2T_pulse_shape(): # Obtain the R2T pulse shape Shape = R2T.dialog() # Calculate the sca...
magicoder
python
You are tasked with implementing a function that takes an array of integers as input and returns the maximum sum of a subarray within that array. A subarray is defined as a contiguous block of elements within the original array. The function should return 0 if the array is empty or contains only negative numbers. You ...
```java public class MaxSubarraySum { public static int maxSubarraySum(int[] arr) { if (arr.length == 0) { return 0; } int maxSum = 0; int currentSum = 0; for (int num : arr) { currentSum = Math.max(num, currentSum + num); maxSum = Math.m...
magicoder
java
You are tasked with creating a script to automate the installation of OpenSSL on a Windows system using the MinGW cross-compiler. Your script should download the OpenSSL source code, verify its integrity using SHA256, extract the files, configure the build options based on the architecture, and then compile and install...
```bash #!/bin/bash # Step 1: Create installation directory mkdir -p "$OPENSSL_PREFIX_DIR" # Step 2: Download OpenSSL source code wget $WGET_OPTIONS "https://www.openssl.org/source/$OPENSSL_FILENAME" # Step 3: Verify SHA256 hash check_sha256() { echo "$2 $1" | sha256sum -c --status - if [ $? -ne 0 ]; then ec...
magicoder
shell
You are given a list `nk` containing three positive integers. Your task is to write a function `calculate_combinations(nk)` that calculates the number of combinations possible for a given set of items. The first integer `n` represents the total number of items, and the second integer `k` represents the number of items ...
```python from itertools import combinations def calculate_combinations(nk, verbose=0): n, k, _ = nk comb = list(combinations(range(1, n+1), k)) num_combinations = len(comb) if verbose: print(f"Number of combinations for choosing {k} items from {n} items: {num_combinations}") print("Com...
magicoder
python
You are tasked with implementing a Python class that facilitates the download of medical image datasets for research purposes. The provided code snippet includes imports and a data class for download parameters. Your task is to create a class called `MedicalImageDownloader` that encapsulates the functionality to downlo...
```python import logging from dataclasses import dataclass from typing import List from sla_cli.src.download.isic import IsicMetadataDownloader, IsicImageDownloader from sla_cli.src.download.ph2 import Ph2Downloader from sla_cli.src.download.pad_ufes_20 import PadUfes20Downloader from sla_cli.src.download.mednode impo...
magicoder
python
You are tasked with implementing a custom dictionary class in Python that supports default values for keys that are not present in the dictionary. The class should be able to accept a default value during initialization and return this default value for any key that is not present in the dictionary. If a key is explici...
```python class CustomDict: def __init__(self, default=None): self.default = default self.data = {} def __getitem__(self, key): return self.data.get(key, self.default) def __setitem__(self, key, value): if value is None: self.data[key] = None else: ...
magicoder
python
You are tasked with creating a program to determine the winner of a game of Connect Five, a variant of the classic game Connect Four. In Connect Five, players take turns placing their pieces on a grid, aiming to connect five of their pieces in a row, column, or diagonal before their opponent does. Your task is to impl...
```python def checkWin(board, currentPiece, x, y): directions = [(0, 1), (1, 0), (1, 1), (1, -1)] # right, down, diagonal right, diagonal left for dx, dy in directions: count = 1 row, col = x, y # Check in both directions for each possible winning line for _ in range(2): ...
magicoder
python
You are tasked with developing a data access layer for a payment processing system. The system needs to connect to a database to retrieve and store payment-related information. The code snippet provided defines a class `DataAccessConstants` with an internal constant string `ConnectionStringName` set to "Payments". This...
```csharp using System; using System.Data; using System.Data.SqlClient; internal static class DataAccessConstants { internal const string ConnectionStringName = "Payments"; } public class PaymentDataAccess { public string RetrievePaymentData(int paymentId) { string connectionString = GetConnection...
magicoder
csharp
You are tasked with implementing a settings management system for a web application. The system should allow for dynamic reloading of settings when they are changed. You are provided with a code snippet that handles the reloading of settings when a specific setting is changed. Your task is to implement the `reload_api_...
```python def reload_api_settings(setting, value, DEFAULTS, IMPORT_STRINGS): if setting == 'REST_KNOX': knox_settings = knox_APISettings(value, DEFAULTS, IMPORT_STRINGS) # Perform any additional actions needed to apply the reloaded settings ``` In the solution, the `reload_api_settings` function tak...
magicoder
python
You are tasked with implementing a resource consumption control mechanism for a web server application. The given code snippet is a part of this mechanism and is responsible for handling the response from a client request. The code snippet includes the initialization of variables and the processing of the response enti...
```java import java.io.InputStream; public class ResourceControlManager { private boolean consumed; private InputLimit limit; private InputStream instream; private ResourceFactory resourceFactory; private Resource resource; public ResourceControlManager(int maxResponseSizeBytes, ResourceFactor...
magicoder
java