query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with creating a program that simulates a simple inventory management system for a small retail store. The system should allow users to add, remove, and update products in the inventory, as well as display the current inventory status. Your program should include the following functionalities: 1. Add a n...
```python class Product: def __init__(self, product_id, name, quantity, price): self.product_id = product_id self.name = name self.quantity = quantity self.price = price class Inventory: def __init__(self): self.products = [] def add_product(self, product): ...
magicoder
python
You are tasked with implementing a custom physics behavior for a platformer game. The game includes platforms with both regular colliders and trigger colliders. The provided code snippet is a part of the platform behavior script. The `Start` method is called when the platform is initialized. Within this method, the scr...
```csharp protected virtual void Start() { if (mPlatformCollider == null || mPlatformTrigger == null) return; Physics.IgnoreCollision(mPlatformCollider, mPlatformTrigger, true); // Check the condition to change the material of the platform collider if (/* condition to change material */) { ...
magicoder
csharp
You are tasked with creating a Python function that reads a file, converts its content to uppercase, and then counts the occurrences of each word in the file. Your function should take a filename as input and return a dictionary where the keys are the unique words in the file (case-insensitive) and the values are the c...
```python def count_word_occurrences(filename: str) -> dict: word_counts = {} with open(filename, 'r') as file: content = file.read().upper() words = content.split() for word in words: word = ''.join(filter(str.isalnum, word)) # Remove punctuation if word: ...
magicoder
python
You are tasked with implementing a custom PyTorch dataset class for adding synthetic noise to the MNIST dataset. The provided code snippet initializes a DataLoader for the noisy MNIST test dataset using the custom SyntheticNoiseDataset. Your task is to create the SyntheticNoiseDataset class, which takes the original MN...
```python import torch from torch.utils.data import Dataset import numpy as np class SyntheticNoiseDataset(Dataset): def __init__(self, original_dataset, noise_type='gaussian'): self.original_dataset = original_dataset self.noise_type = noise_type def __len__(self): return len(self.ori...
magicoder
python
You are tasked with creating a custom annotation processor in Java. Your goal is to implement a program that processes classes annotated with `@Reactant` and generates a new class that contains a method to react with other reactants. Your program should perform the following tasks: 1. Define a custom annotation `@Reac...
```java import javax.annotation.processing.*; import javax.lang.model.SourceVersion; import javax.lang.model.element.TypeElement; import javax.lang.model.element.Element; import javax.lang.model.element.Modifier; import javax.lang.model.element.VariableElement; import javax.tools.Diagnostic; import javax.tools.JavaFile...
magicoder
java
You are given a Python code snippet that includes a comment with a date and author information. Your task is to write a Python function that extracts the creation date and author from the given code snippet. Write a function `extract_info(code)` that takes a string `code` as input and returns a tuple `(creation_date, ...
```python import re def extract_info(code): comment_block = re.findall(r"'''.*?'''", code, re.DOTALL)[0] creation_date = re.search(r'Created on (.+?)\n', comment_block).group(1) author = re.search(r'@(.+?)\n', comment_block).group(1) return (creation_date, author) # Test the function with the provided...
magicoder
python
You are tasked with creating a Python decorator that logs the execution time of a function and prints the result. Your decorator should be able to handle functions with any number of positional and keyword arguments. Additionally, you need to implement a function that calculates the factorial of a given number and appl...
```python import time import functools def log_execution_time(func): @functools.wraps(func) def wrapper(*args, **kwargs): start_time = time.time() result = func(*args, **kwargs) end_time = time.time() execution_time_ms = (end_time - start_time) * 1000 print(f"Function: {...
magicoder
python
You are tasked with creating a script to automate the process of building LLVM and its related projects from source code. The script should handle extracting source code archives, setting up the directory structure, and invoking the necessary build commands. Your script should perform the following steps: 1. Extract t...
```bash #!/bin/bash # Define the version variable VERSION="10.0.0" # Step 1: Extract llvm source code tar --strip-components=1 -xf llvm-${VERSION}.src.tar.xz -C llvm # Step 2: Extract libcxxabi source code tar --strip-components=1 -xf libcxxabi-${VERSION}.src.tar.xz -C llvm/projects/libcxxabi # Step 3: Extract libc...
magicoder
shell
You are tasked with implementing a logging system for a software application. The logging system should support different levels of logging, flags, and colors for the log messages. You need to create a class `ToolLogger` with a method `log` that takes in the level of the log message, a flag, a color, the log message da...
```cpp #include <cstdio> enum class ELoggerLevel { INFO, WARNING, ERROR }; using Char = char; // Assuming Char is a typedef for char class ToolLogger { public: void log(ELoggerLevel _level, uint32_t _flag, uint32_t _color, const Char* _data, size_t _size) { // Ignoring the unused paramete...
magicoder
cpp
You are tasked with creating a Django model for a social media application that allows users to link their accounts to external providers such as Facebook. The model should store information about the user's social profile, including the provider, social ID, photo, extra data, and a reference to the user's main profile...
```python from django.db import models from django.conf import settings class SocialProfile(models.Model): PROVIDER_CHOICES = ( ('1', 'Facebook'), ) provider = models.SmallIntegerField(choices=PROVIDER_CHOICES) social_id = models.CharField(max_length=255, unique=True) photo = models.TextFi...
magicoder
python
You are tasked with implementing a Python function that processes a list of dependencies and operations related to database migrations. The function should parse the dependencies and operations and return a formatted string representing the migration operations. You are given a list of dependencies and a list of migra...
```python def process_migrations(dependencies, operations): latest_migration = max(dependencies, key=lambda x: x[1]) formatted_operations = [f"- {op.__class__.__name__}: {', '.join(f'{k}={v}' for k, v in op.__dict__.items() if not k.startswith('_')}" for op in operations] return f"Migration: {latest_migrati...
magicoder
python
You are tasked with creating a program to manage a student's course schedule. The provided code snippet is a part of a graphical user interface (GUI) for this program, written in Python using the Tkinter library. The GUI includes a list of available courses and buttons to insert a course and create a schedule. Your ta...
```python class Controle: def __init__(self): self.schedule = [] def insereDisciplina(self, course): self.schedule.append(course) def criaGrade(self): if len(self.schedule) > 0: print("Generated schedule:") for course in self.schedule: print(...
magicoder
python
You are tasked with creating a custom validation attribute for a .NET Core MVC application. The attribute should ensure that the `Keyword` property is not empty and contains at least one character. Additionally, the attribute should be applied to the `Keyword` property in a model class. Your task is to implement the cu...
```csharp using System; using System.ComponentModel.DataAnnotations; public class NotEmptyOrWhiteSpaceAttribute : ValidationAttribute { public override bool IsValid(object value) { if (value is string str) { return !string.IsNullOrWhiteSpace(str); } return false; ...
magicoder
csharp
You are tasked with creating a Java program that utilizes the Spring Framework to implement a simple JDBC-based application. Your program should include the necessary components to connect to a database, perform CRUD (Create, Read, Update, Delete) operations on a table, and demonstrate the usage of Spring's dependency ...
```java // Student.java package io.github.jeanhwea.app09_jdbc.beans; import org.springframework.stereotype.Component; @Component public class Student { private int id; private String name; private int age; // Getters and setters } // StudentDAO.java package io.github.jeanhwea.app09_jdbc.dao; import...
magicoder
java
You are tasked with implementing a custom data structure called `CustomQueue` in Rust. The `CustomQueue` should have the following functionalities: 1. `new`: Create a new empty queue. 2. `enqueue`: Add an element to the end of the queue. 3. `dequeue`: Remove and return the element at the front of the queue. 4. `peek`: ...
```rust use alloc::boxed::Box; use core::iter::FromIterator; pub struct CustomQueue<T> { head: Option<Box<Node<T>>>, tail: *mut Node<T>, } struct Node<T> { element: T, next: Option<Box<Node<T>>>, } impl<T> CustomQueue<T> { pub fn new() -> Self { CustomQueue { head: None, tail: std::ptr::n...
magicoder
rust
You are tasked with implementing a function to extract audio data from a file using the ExtAudioFile API in Swift. The given code snippet sets up the necessary variables and opens an audio file using the ExtAudioFileOpenURL function. Your task is to complete the implementation by writing a function that reads the audio...
```swift func readAudioData(from url: URL, outputFormat: AudioStreamBasicDescription) -> UnsafeMutablePointer<CChar>? { var theFileLengthInFrames: Int64 = 0 var theFileFormat = AudioStreamBasicDescription() var thePropertySize: UInt32 = UInt32(MemoryLayout.stride(ofValue: theFileFormat)) var extRef: Ext...
magicoder
swift
You are tasked with implementing a TypeScript function that takes in an array of `Types` and returns the count of occurrences of each unique type in the array. The `Types` type is a union type that can include various type literals. You need to create a function that can accurately count the occurrences of each unique ...
```typescript function countTypeOccurrences(types: Types[]): Record<string, number> { const typeOccurrences: Record<string, number> = {}; for (const type of types) { if (type in typeOccurrences) { typeOccurrences[type]++; } else { typeOccurrences[type] = 1; } } return typeOccurrences; ...
magicoder
typescript
You are tasked with implementing a program that simulates a simple options trading system. The system will allow users to buy and sell options contracts based on the current market price of the underlying asset. Each options contract represents the right to buy or sell the underlying asset at a specified price (the str...
```csharp public class OPTIONS : ApplicationTestFixture<WriteProgram> { public class WriteProgram { private decimal currentMarketPrice; private List<OptionContract> availableContracts; private Dictionary<string, List<OptionContract>> userOwnedContracts; public WriteProgram(decim...
magicoder
csharp
You are working on a Django web application that includes an admin interface and RESTful API endpoints. The code snippet provided includes some import statements for Django modules and views from a local package. Your task is to create a custom Django admin view that allows the admin to manage a specific model in the a...
To create a custom admin view for managing the `CustomModel` in the Django application, you can define a custom admin class and register it with the Django admin site. Here's a sample solution: ```python from django.contrib import admin from .models import CustomModel @admin.register(CustomModel) class CustomModelAdm...
magicoder
python
You are tasked with creating a Python program that simulates a simple online store. The program should have a class representing a product, a class representing a shopping cart, and a main program to interact with the user. The Product class should have the following attributes: - name: a string representing the name ...
```python class Product: def __init__(self, name, price): self.name = name self.price = price class ShoppingCart: def __init__(self): self.products = [] def add_to_cart(self, product): self.products.append(product) def remove_from_cart(self, product): if produc...
magicoder
python
You are given the definition of a binary tree node and a function `mergeTrees` that takes in two binary trees `t1` and `t2` as input and merges them into a new binary tree. The `mergeTrees` function creates a new binary tree by summing up the values of corresponding nodes from the input trees. If a node exists in only ...
```cpp #include <iostream> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) { if (!t1) return t2; if (!t2) return t1; TreeNode *node = n...
magicoder
cpp
You are tasked with creating a program that processes a list of files generated by the Microsoft AutoRest Code Generator. The AutoRest Code Generator produces code for interacting with RESTful APIs based on a provided OpenAPI specification. The generated code includes comments and annotations that need to be parsed and...
```python import re def extract_code_info(file_content): result = [] language_pattern = re.compile(r'# coding=([\w-]+)') version_pattern = re.compile(r'AutoRest Code Generator\.?\s+v?(\d+\.\d+\.\d+)') language_match = language_pattern.search(file_content) version_match = version_pattern.search...
magicoder
python
You are given a list of integers representing the results of a series of submissions in a programming contest. Each integer represents the result of a submission, where 1 indicates a correct answer and 0 indicates a wrong answer. Your task is to find the index of the first incorrect submission (0) in the list. If there...
```python from typing import List def find_first_incorrect(submissions: List[int]) -> int: for i in range(len(submissions)): if submissions[i] == 0: return i return -1 ```
magicoder
python
You are tasked with implementing a generic data structure in Rust that allows for the creation of a singly linked list. The linked list should support the addition of elements at the front and back, as well as the removal of elements from the front. Additionally, the linked list should provide an iterator that allows f...
```rust fn main() { // Create a new empty linked list let mut list: LinkedList<i32> = LinkedList::new(); // Add elements to the front of the linked list list.push_front(3); list.push_front(2); list.push_front(1); // Add elements to the back of the linked list list.push_back(4); lis...
magicoder
rust
You are working on a project that involves processing and visualizing 3D image data using the VTK (Visualization Toolkit) library in Python. As part of this project, you need to create a VTK pipeline to visualize a 3D image dataset using the `vtkImageDataGeometryFilter` class. The `vtkImageDataGeometryFilter` class is...
```python import vtk def create_vtk_pipeline(ptLoad): # Instantiate a vtkRenderer and a vtkRenderWindow renderer = vtk.vtkRenderer() render_window = vtk.vtkRenderWindow() render_window.AddRenderer(renderer) # Create a vtkImageDataGeometryFilter g = vtk.vtkImageDataGeometryFilter() g.SetInp...
magicoder
python
You are tasked with creating a script to automate the process of creating a bootable disk image for a custom operating system. The script should perform the following tasks: 1. Remove any existing disk image file named "bos.img" from the parent directory. 2. Create a new disk image file named "bos.img" with a capacity ...
```bash #!/bin/bash # Step 1: Remove existing disk image file rm -f ../bos.img echo "Removed existing bos.img file, if any." # Step 2: Create a new disk image file mformat -C -f 1440 -v BOS -i ../bos.img :: if [ $? -eq 0 ]; then echo "Created bos.img successfully." else echo "Failed to create bos.img." ex...
magicoder
shell
You are tasked with implementing a decorator function in Python that restricts access to a given function based on user privileges. The decorator should check if the user is logged in and has the necessary permissions to access the function. You are provided with the following code snippet for inspiration: ```python @...
```python def login_required(func): def wrapper(*args, **kwargs): # Check if user is logged in if user_is_logged_in(): return func(*args, **kwargs) else: redirect_to_login() return wrapper def template_renderer(): def decorator(func): def wrapper(*arg...
magicoder
python
You are tasked with implementing a simplified version of a peer-to-peer communication protocol using Rust. The protocol involves a handshake process between two peers to establish a connection. The provided code snippet is a part of the handshake process, where a handshake message is constructed and sent to the remote ...
```rust // Define the HandshakeMessage struct struct HandshakeMessage { remote_prot: Protocol, // Define the Protocol struct as per the protocol requirements ext: Extension, // Define the Extension struct as per the protocol requirements remote_hash: Hash, // Define the Hash struct as per the pro...
magicoder
rust
You are given a code snippet that tests a function `part2` with different inputs and expected outputs. Your task is to implement the `part2` function based on the given inputs and expected outputs. The `part2` function takes an `Input` object as input and returns an integer. The `Input` object is created using the `In...
```rust use std::fs; struct Input { file_path: String, number: i32, year: i32, } impl Input { fn new(file_path: String, number: i32, year: i32) -> Result<Input, String> { Ok(Input { file_path, number, year, }) } } fn part2(input: Input) -> i64 {...
magicoder
rust
You are tasked with creating a Django migration to alter a field in a model. The model in question is `LearnerProgressNotification` and the specific alteration involves changing a field within this model. Your task is to write the necessary migration code to achieve this alteration. Your task is to complete the `opera...
```python from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('notifications', '0005_learnerprogressnotification_assignment_collections'), ] operations = [ migrations.AlterField( model_name='learnerprogressnotification', ...
magicoder
python
You are tasked with creating a JavaScript module that exports a schema object. The schema object will define the structure and constraints for a specific data model. Your task is to implement the schema object with the following requirements: The schema object should have a property named "fields" which is an array of...
```javascript const schema = { fields: [ { name: "id", type: "number", required: true }, { name: "name", type: "string", required: true }, { name: "age", type: "number", required: false }, { name: "email", type: "string", required: false } ] }; export default schema; ```
magicoder
javascript
You are tasked with implementing a password decoder utility for a web server using Java. The `JettyPasswordDecoder` class is responsible for decoding obfuscated passwords used in the web server configuration. The `Password` class provides a method to obfuscate passwords. Your goal is to implement the `JettyPasswordDeco...
```java public class JettyPasswordDecoder { public String decode(String encodedPassword) { // Implement the decoding logic here // For example, you can use the reverse of the obfuscation process to decode the password // In this case, assuming the obfuscation is a simple reverse operation, ...
magicoder
java
You are tasked with implementing a Python class that processes sequence data from a FASTA file and organizes it into groups based on a specified sense. The class should be able to handle the loading of the FASTA file, grouping the sequences based on the specified sense, and providing access to the grouped sequences. Y...
```python import os import numpy as np from Bio import SeqIO from Bio.SeqRecord import SeqRecord from Bio.Seq import Seq class SeqGroups: def __init__(self, file_path, sense): self.file_path = file_path self.sense = sense self.ids = [] self.names = [] self.seqs = [] ...
magicoder
python
You are tasked with implementing a dynamic programming algorithm to find the minimum cost of transforming one sequence of elements into another. The cost of transformation is determined by the cost of adding, deleting, or substituting elements in the sequences. Additionally, a custom comparison function is used to comp...
To solve this problem, you can use the Wagner-Fischer algorithm, a classic dynamic programming algorithm for sequence alignment. Here's a Python implementation of the algorithm: ```python def min_cost_transform(seq1, seq2): m, n = len(seq1), len(seq2) dp = [[0] * (n + 1) for _ in range(m + 1)] for i in ra...
magicoder
python
You are tasked with implementing a class for a scientific calculator. The class should have methods to change the display mode from degrees to radians and to change the text of trigonometric function buttons when the user switches to radians mode. You need to implement the following methods in the scientific calculato...
```python class ScientificCalculator: def __init__(self, DEGButtonText, ASINButtonText, ACOSButtonText, ATANButtonText, SINButtonText): self.DEGButtonText = DEGButtonText self.ASINButtonText = ASINButtonText self.ACOSButtonText = ACOSButtonText self.ATANButtonText = ATANButtonText ...
magicoder
python
You are tasked with creating a Python function that manages the installation and configuration of a software package on a system. The function should take in various parameters to customize the installation process. Below is a code snippet that outlines the argument specifications for the function: ```python argument_...
```python def manage_software_package(**kwargs): # Perform installation or uninstallation based on the 'state' parameter if kwargs['state'] == 'present': action = 'install' # Customize installation location download_location = kwargs['download_location'] # Set service user and gr...
magicoder
python
You are tasked with implementing a custom decorator that measures the execution time of a function in Python. Your decorator should be able to calculate the time taken for the function to execute and print the result in milliseconds. You should also ensure that the original function's return value is preserved and retu...
```python from time import time from contextlib import contextmanager from functools import wraps class Timer: def __init__(self): self.start_time = 0 self.end_time = 0 def __enter__(self): self.start_time = time() return self def __exit__(self, exc_type, exc_val, exc_tb):...
magicoder
python
You are tasked with implementing a custom layout system in Swift for iOS development. The system involves creating a prefix operator function and several custom classes to handle layout attributes and constraints. Your task is to implement the missing parts of the layout system based on the given code snippet. The sys...
```swift // Define the prefix operator function for creating layout chains public prefix func &- (view: UIView) -> AJLayoutContainer { // Create a layout attribute for the top of the view let topAttribute = AJLayoutAttribute(view, attribute: .top) // Create a layout attribute for the bottom of the view...
magicoder
swift
You are tasked with creating a PHP function that processes user registration data and stores it in a database. Your function should handle validation, insertion, and error handling. You are provided with the following code snippet as a starting point: ```php if ($_SERVER['REQUEST_METHOD'] === 'POST') { $username...
```php function processRegistration($username, $email, $password) { // Validate input data if (empty($username) || empty($email) || empty($password)) { return "All fields are required."; } if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { return "Invalid email format."; } if (str...
magicoder
php
You are tasked with implementing a function that processes a given depth stencil descriptor and returns a corresponding Metal depth stencil state. The function should handle potential errors and post notifications in case of failure. You are provided with the following code snippet as a reference: ```swift } catch le...
```swift func makeDepthStencilState(descriptor: MTLDepthStencilDescriptor) -> MTLDepthStencilState? { do { return try device.makeDepthStencilState(descriptor: descriptor) } catch let error { print("Failed to create depth stencil state. ERROR: \(error)") let newError = AKError.seriousErro...
magicoder
swift
You are tasked with creating a validation rule for a specific field in a Laravel application. The application has a `store` method within a controller that handles incoming requests. The `store` method receives a `Request` object and is responsible for validating the input data before processing it further. The code sn...
```php // Custom validation rule class for checking uniqueness of 'name' field namespace App\Rules; use Illuminate\Contracts\Validation\Rule; use App\Models\YourModel; // Replace with the actual model name class UniqueName implements Rule { public function passes($attribute, $value) { // Check if the ...
magicoder
php
You are tasked with implementing a keypoint detection algorithm for a computer vision application. The algorithm takes as input a 4-dimensional array `preds` representing the predictions of a neural network for keypoints in an image. The array has the shape (N, H, W, C), where N is the number of samples, H is the heigh...
```python W = preds.shape[3] # Empty list to store the detected keypoints points = [] for i in range(15): # Assuming the keypoint coordinates and confidence scores are extracted from the 'preds' array x = preds[0, 0, 0, i] # Example: Extract x coordinate from the first sample, top-left corner, and ith keypoint...
magicoder
python
You are given a dataset containing the results of a series of experiments. The code snippet provided is a part of a Python script that generates a normal quantile-quantile (QQ) plot to assess whether the data follows a normal distribution. The QQ plot compares the quantiles of the dataset against the quantiles of a the...
```python import numpy as np import random import matplotlib.pyplot as plt def generate_qq_plot(dataset): # Generate normal distribution ndist = random.normal(loc=0, scale=1, size=len(dataset)) ndist.sort() # Fit Normal Trendline using linear regression fit = np.polyfit(ndist, sorted(dataset), 1) ...
magicoder
python
You are tasked with creating a program that analyzes HTML code to identify and count the occurrences of specific HTML tags within a given snippet. Your program should be able to handle various HTML tags and provide the count of each tag present in the input. Write a function `count_html_tags(html_snippet: str, tags: L...
```python from typing import List, Dict import re def count_html_tags(html_snippet: str, tags: List[str]) -> Dict[str, int]: tag_counts = {} for tag in tags: pattern = rf'<{tag}.*?>' count = len(re.findall(pattern, html_snippet, re.IGNORECASE)) tag_counts[tag] = count return tag_cou...
magicoder
python
You are tasked with creating a program that reads a text file and counts the occurrences of specific words within it. The program should ignore any lines that start with a "#" symbol, as these are considered comments. The words to be counted are provided in a separate input file, with each word on a new line. The progr...
```python def count_words_in_file(text_file, word_list_file): word_counts = {} with open(word_list_file, 'r') as f: words_to_count = [line.strip() for line in f if line.strip()] with open(text_file, 'r') as f: for line in f: if not line.strip().startswith('#'): ...
magicoder
python
You are tasked with implementing a custom string encoding and decoding algorithm. The encoding algorithm will take a string as input and return the encoded version of the string, while the decoding algorithm will take the encoded string and return the original string. The encoding algorithm works as follows: 1. For ea...
```swift public struct StringEncodingError: Error {} public func encode(_ input: String) -> String { var encodedString = "" for char in input { let binaryValue = String(char.asciiValue!, radix: 2) let paddedBinaryValue = String(repeating: "0", count: max(0, 8 - binaryValue.count)) + binaryValue...
magicoder
swift
You are given a function `countOccurrences` that takes in two parameters: a string `text` and a string `pattern`. The function is designed to count the number of occurrences of the `pattern` within the `text`. However, the implementation of the function is incomplete and needs to be fixed. The function `countOccurrenc...
```cpp int countOccurrences(string text, string pattern) { int cnt = 0; vector<int> pi(pattern.size(), 0); int pInd = 0; for (int i = 1; i < pattern.size(); i++) { while (pInd > 0 && pattern[i] != pattern[pInd]) { pInd = pi[pInd-1]; } if (pattern[i] == pattern[pInd]) ...
magicoder
cpp
You are given a string `s` containing only lowercase English letters. Your task is to write a function that returns the length of the longest substring without repeating characters. For example, given the input string "abcabcbb", the longest substring without repeating characters is "abc", so the function should retur...
```python def longestSubstringLength(s: str) -> int: max_length = 0 start = 0 char_index = {} for end in range(len(s)): if s[end] in char_index and char_index[s[end]] >= start: start = char_index[s[end]] + 1 char_index[s[end]] = end max_length = max(max_length, end -...
magicoder
python
You are tasked with implementing a generic image processing library in Rust. The library should support the creation and manipulation of square images represented by the `SquareImage` struct. The `SquareImage` struct has an `edge_length` field representing the length of each edge of the square image and an `inner` fiel...
```rust use serde::{Serialize, Deserialize}; #[derive(Clone, PartialEq, Serialize, Deserialize)] #[serde(from = "ImageWrapper", into = "ImageWrapper")] pub struct SquareImage<Pixel: Clone> { edge_length: usize, inner: Vec<Pixel>, } /// the representation of the minimap data on disk #[derive(Clone, PartialEq, ...
magicoder
rust
You are tasked with creating a Python class that simulates a magical witch who can cast spells and brew potions. The witch class should have the following functionalities: 1. Casting Spells: The witch should be able to cast spells by providing the spell name and the power level. The power level of a spell can range fr...
```python class MagicalWitch: def __init__(self, name): self.name = name self.spells = {} self.potions = {} def cast_spell(self, spell_name, power_level): if 1 <= power_level <= 10: self.spells[spell_name] = power_level else: print("Power level sh...
magicoder
python
You are tasked with implementing a custom view controller in Swift that manages a list of tasks. The view controller should allow users to add, remove, and display tasks. Additionally, it should provide a method to mark a task as completed. You need to implement the `Task` struct and the `TaskListViewController` class ...
```swift // Task struct to represent a task struct Task { var title: String var completed: Bool } // TaskListViewController class to manage the list of tasks class TaskListViewController: UIViewController { var tasks: [Task] = [] // Method to add a new task to the task list func addTask(title: Str...
magicoder
swift
You are tasked with creating a Django web application for a project management system. The given code snippet represents the URL patterns defined in the `urls.py` file of the Django application. Each URL pattern is associated with a specific view function that handles the corresponding HTTP request. Your task is to des...
```python # Import necessary modules from django.http import JsonResponse from django.shortcuts import get_object_or_404 from .models import UserProfile # Assuming UserProfile model exists in the application # Define the view function for the 'view_profile' URL pattern def view_profile(request, id): # Retrieve th...
magicoder
python
You are given a Python function called `uncycle` that takes a list of integers as input and returns a modified list. The function is intended to remove any cyclic shift from the input list and return the list in its original order. The code snippet provided is a part of the `uncycle` function. The function uses recurs...
```python from typing import List def uncycle(list: List[int]) -> List[int]: if not list: return list m = int(len(list) / 2) if list[0] < list[m]: return uncycle(list[m:]) # Recursively call uncycle with the second half of the list else: return uncycle(list[:m]) # Recursively ...
magicoder
python
You are tasked with creating a Python program to automate the process of fetching and organizing emails from an IMAP server. Your program should connect to the IMAP server, log in with the provided credentials, and then fetch specific information from the emails. Your program should perform the following steps: 1. Con...
```python import imaplib import email from email.header import decode_header imapserver = "your_imap_server" user = "your_username" passw = "your_password" def fetch_and_print_emails(): imap = imaplib.IMAP4_SSL(imapserver) try: imap.login(user, passw) print("Connecting and Fetching required in...
magicoder
python
You are tasked with creating a Python class that simulates a simple bank account. The class should have methods for depositing funds, withdrawing funds, and checking the current balance. Additionally, the class should have a method for transferring funds to another bank account. Your task is to implement the `BankAcco...
```python class BankAccount: def __init__(self): self.balance = 0 def deposit(self, amount): self.balance += amount def withdraw(self, amount): if self.balance >= amount: self.balance -= amount else: print("Insufficient funds") def get_balance(s...
magicoder
python
You are tasked with creating a Python function that processes a given string to extract and count the occurrences of Korean words. The function should take a string as input and return a dictionary where the keys are the unique Korean words found in the input string, and the values are the counts of each word's occurre...
```python def count_korean_words(input_string: str) -> dict: korean_words = {} words = input_string.split() for word in words: # Remove punctuation and numbers word = ''.join(filter(lambda x: '가' <= x <= '힣', word)) if word: korean_words[word] = korean_words.get(word, 0) ...
magicoder
python
You are tasked with creating a simple timer application using the GTK library in Rust. The provided code snippet initializes a GTK window and a label to display the timer. Your task is to implement the timer functionality that updates the label to show the elapsed time in the format "HH:MM:SS". Your timer should start...
```rust use gtk::prelude::*; use gtk::{Label, Window, WindowPosition, WindowType}; use std::time::{Duration, Instant}; fn main() { gtk::init().expect("Failed to initialize GTK."); let window = Window::new(WindowType::Toplevel); window.set_title("Minecraft timer"); window.set_border_width(10); win...
magicoder
rust
You are tasked with creating a Python decorator that can be used to skip a test if a specific condition is not met. The decorator should be able to handle skipping tests based on the absence of a network connection and the availability of a specific URL. Your task is to implement the `skip_if_no_network` and `skip_if_...
```python import functools import requests from ....dochelpers import exc_str from ....tests.utils import SkipTest def skip_if_no_network(func): @functools.wraps(func) def wrapper(*args, **kwargs): try: requests.get("http://www.google.com", timeout=1) except requests.ConnectionError...
magicoder
python
You are tasked with creating a program that simulates a simple banking system. The program should be able to handle various types of bank accounts, such as savings accounts and checking accounts. Additionally, it should be able to process transactions, including deposits, withdrawals, and transfers between accounts. Y...
```csharp // The solution provides the complete implementation of the BankAccount, SavingsAccount, and CheckingAccount classes, along with the InsufficientFundsException class. The classes handle deposits, withdrawals, and transfers between accounts, while also appropriately throwing and catching exceptions as specifie...
magicoder
csharp
You are tasked with implementing a function that finds the nearest free memory block in a given process's address space. The function should take a memory address as input and return the nearest free memory block address that precedes the given memory address. The memory blocks are defined using the `MEMORY_BASIC_INFOR...
```c LPVOID FindNearestFreeMemoryBlock(LPVOID nearest) { MEMORY_BASIC_INFORMATION mbi = { 0 }; LPVOID nearestFreeBlock = NULL; for (SIZE_T addr = (SIZE_T)nearest; addr > (SIZE_T)nearest - 0x80000000; addr = (SIZE_T)mbi.BaseAddress - 1) { if (!VirtualQuery((LPCVOID)addr, &mbi, sizeof(mbi))) ...
magicoder
c
You are tasked with implementing a reinforcement learning environment for a simple game. The environment is initialized with the given code snippet, which sets up the initial state and some parameters. Your task is to complete the implementation of the environment by defining the step function, which determines the beh...
```python class ReinforcementLearningEnvironment: def __init__(self, isd, np_random): self.isd = isd self.np_random = np_random self.seed() self.s = np.array([int(categorical_sample(self.isd, self.np_random))]) self.max_episode_length = 200 self.episode_length = 0 ...
magicoder
python
You are tasked with implementing a graph data structure to represent a map of cities and their connections. Each city is represented as a vertex in the graph, and the connections between cities are represented as edges. Your goal is to create a Python class that can be used to construct the graph and perform various op...
```python class Vertice: def __init__(self, name): self.name = name self.edges = [] class Graph: def __init__(self): self.vertices = {} def add_vertex(self, name): if name not in self.vertices: self.vertices[name] = Vertice(name) def add_edge(self, from_ver...
magicoder
python
You are tasked with creating a program that processes a given Laravel language file and extracts the translatable strings for further processing. In Laravel, translatable strings are typically enclosed within the `__()` helper function or its alias `@lang`. The translatable strings are enclosed within a specific syntax...
```php function extractTranslatableStrings(string $fileContent): array { $translatableStrings = []; $pattern = "/__\(['\"](.*?)['\"]\)|@lang\(['\"](.*?)['\"]\)/"; preg_match_all($pattern, $fileContent, $matches); foreach ($matches[1] as $match) { if (!empty($match)) { $translata...
magicoder
php
You are tasked with implementing a data storage system for a company's products. The system should support sparse fields, which are fields that are only stored if they have a non-default value. To achieve this, you need to design a class that can handle sparse fields and store them efficiently. You are given a code sn...
```python class SparseFieldStorage: def __init__(self): self.data = {} def store_field(self, field_name, value): if value != self._get_default_value(type(value)): self.data[field_name] = value def retrieve_field(self, field_name): return self.data.get(field_name, self._...
magicoder
python
You are tasked with creating a Python function that processes log data from a web application. The log data is represented as a list of Log objects, where each Log object has the following attributes: - `timestamp`: an integer representing the time of the log entry - `level`: a string representing the severity level of...
```python from typing import List from app.models import Log def filter_logs(logs: List[Log], severity_level: str) -> List[str]: filtered_messages = [log.message for log in logs if log.level == severity_level] return filtered_messages ```
magicoder
python
You are tasked with implementing a Python function that processes an abstract syntax tree (AST) and modifies it based on certain rules. The AST represents a snippet of Python code and needs to be transformed by inserting return statements into the code body. Additionally, the function should create an environment dicti...
```python import ast def insert_returns(body): for node in body: if isinstance(node, ast.FunctionDef): if not any(isinstance(n, ast.Return) for n in node.body): node.body.append(ast.Return(value=None)) def process_ast(body, ctx, bot): parsed = ast.parse(body) body = par...
magicoder
python
You are tasked with implementing a Python class method that sets the endianness and creates transport-specific constructors. The method should handle the setting of endianness and the creation of constructors based on the given endianness. Your task is to complete the implementation of the `__setup_constructors` method...
```python import logging class Transport: def __init__(self): self.__intep = None self.__inep = None self.__outep = None self.__cfg = None self.__dev = None self.__intf = None def _set_endian(self, endianness): # Set the endianness (little or big) ...
magicoder
python
You are tasked with simulating the display of a character on a screen using a simplified video memory system. The provided code snippet is a part of a larger system responsible for rendering characters on a display. The variables and operations used in the code snippet are as follows: - `x`: Current x-coordinate on the...
```cpp int renderScanline(int x, int cursor_x, int ma, int ra, unsigned char m_p_videoram[]) { int inv = 0; // Initialize inv to 0 int mem = (2 * (ma + x)) & 0xfff; // Calculate memory address int chr = m_p_videoram[mem] & 0x3f; // Extract character data from video memory if (x == cursor_x) inv ^= 0...
magicoder
cpp
You are tasked with creating a Python utility for file manipulation. Your task is to implement a class `FileManipulator` that provides various file operations using the methods provided in the `fileutil.utils` module. The methods to be implemented in the `FileManipulator` class are as follows: 1. `findFileNameWithoutS...
```python from typing import List from fileutil.utils import find_file_name_without_suffix, find_compressed_files, remove_dir, remove_subdir, find_files, copy_dir, write_to_file class FileManipulator: def findFileNameWithoutSuffix(self, suffix: str) -> str: return find_file_name_without_suffix(suffix) ...
magicoder
python
You are tasked with implementing a function to decompose a data URI into its constituent parts. A data URI is a scheme that provides a way to include data in-line in web pages as if they were external resources. The general format of a data URI is `data:[<media type>][;charset=<character set>][;base64],<data>`, where `...
```javascript function decomposeDataUri(dataUri) { const regex = /^data:([\w\/]+)(?:;charset=([\w-]+))?(;base64)?,(.*)$/; const match = dataUri.match(regex); if (!match) { throw new Error('Invalid data URI format'); } const [, mediaType, charset, base64, data] = match; const subType = mediaType.split(...
magicoder
javascript
You are given a code snippet that appears to be the result of fuzzing or random input generation. Your task is to analyze the code and identify the potential issues or errors present in it. The code seems to be a mix of Swift syntax elements, but it is heavily obfuscated and contains multiple nested curly braces, class...
The given code snippet appears to be heavily obfuscated and contains multiple nested curly braces, making it difficult to discern its actual purpose. It seems to be a mix of Swift syntax elements, including struct and class declarations, function definitions, and nested scopes. However, due to the excessive nesting and...
magicoder
swift
You are tasked with implementing a Python class that manages a multi-line view for displaying and selecting glyphs from a font. The class should provide methods for setting the glyphs to be displayed, as well as a callback function for handling glyph selection events. Your task is to implement the `MultiLineView` clas...
```python class MultiLineView: def __init__(self, rect, pointSize, selectionCallback): self.rect = rect self.pointSize = pointSize self.selectionCallback = selectionCallback self.glyphs = [] self.selectedGlyph = None def set(self, glyphs): self.glyphs = glyphs ...
magicoder
python
You are tasked with implementing a class that manages hotkeys for a desktop application. The class, `HotkeyManager`, is responsible for handling the registration and management of hotkeys. It provides functionality to set a hotkey, listen for hotkey events, and retrieve the current hotkey label. The class has the foll...
```swift import Foundation import Combine class HotkeyManager { @Published var currentHotkeyLabel: String = UserDefaults.globalKey?.description ?? "Set Hotkey" @Published var isListenningForHotkey: Bool = false func setHotkey(_ newHotkeyLabel: String) { // Implement setting a new hotkey and up...
magicoder
swift
You are tasked with implementing a multi-threaded program that simulates a simple banking system. The program should support multiple account holders making deposits and withdrawals concurrently while ensuring data consistency and avoiding race conditions. You are provided with a partial code snippet for the `Bank` cl...
To ensure that deposits and withdrawals are performed atomically and consistently across multiple threads, we can use the `bankLock` to synchronize access to the critical section of the `makeTransaction` method. Here's the complete implementation of the `makeTransaction` method: ```java public void makeTransaction(int...
magicoder
java
You are tasked with implementing a simple ray tracing algorithm to render a 3D scene. The provided code snippet is a part of a method in a Rust program that calculates the color emitted by a material at a given intersection point. The `emitted` method takes in a reference to a `Ray` and a `HitRecord` and returns the co...
```rust fn emitted(&self, ray_in: &Ray, hit_record: &HitRecord) -> ColorRGB { if glm::dot(ray_in.direction, hit_record.normal) < 0.0 { self.emit .value(&hit_record.uv, &hit_record.position) .truncate(3) } else { // Handle the case when the dot product is greater than or e...
magicoder
rust
You are given a simplified programming language that supports conditional statements and arithmetic operations. The conditional statement has the following syntax: ``` alt <expression> { <value1> { <statement1> } <value2> { <statement2> } ... _ { <default statement> } } ``` Where `<expression>` is an arithmetic...
```java public static String evaluateConditional(String statement, int expression) { String[] parts = statement.split("\\{"); String condition = parts[0].trim(); String[] cases = Arrays.copyOfRange(parts, 1, parts.length); for (String caseBlock : cases) { String[] caseParts = caseBlock.split("\\...
magicoder
java
You are tasked with creating a program that simulates a simple calculator. The program should take a string as input, which represents a mathematical expression in postfix notation. Postfix notation, also known as Reverse Polish Notation (RPN), is a mathematical notation in which every operator follows all of its opera...
```python def evaluate_postfix(expression): stack = [] operators = {'+': lambda x, y: x + y, '-': lambda x, y: x - y, '*': lambda x, y: x * y, '/': lambda x, y: x / y} for token in expression.split(): if token.isdigit(): stack.append(int(token)) elif token in operators: ...
magicoder
python
You are tasked with creating a program to manage the layout constraints of UI elements in a mobile application. The program should be able to parse and process layout constraint code snippets, and then output the constraints in a human-readable format. You are given a code snippet that represents layout constraints us...
```swift func parseLayoutConstraints(_ codeSnippet: String) -> String { var constraintsOutput = "Layout Constraints:\n" let lines = codeSnippet.components(separatedBy: .newlines) for line in lines { if line.contains("make.") { let components = line.components(separatedBy: ".") ...
magicoder
swift
You are tasked with creating a program that parses a given input text using a specific parsing algorithm. The input text will be provided through a text box in a Windows Forms application. Your task is to implement the parsing functionality triggered by a button click event. The parsed output should be displayed in a s...
```csharp // Assuming the OpenNLP parsing algorithm is implemented in a separate library or service // Event handler for the _btnParse button click event private void _btnParse_Click(object sender, EventArgs e) { string inputText = _txtInput.Text; string parsedOutput = ParseInputText(inputText); _lithiumCo...
magicoder
csharp
You are working on a computer vision project and need to implement a function to process and manipulate tensors representing bounding box coordinates and offsets. The code snippet provided is a part of this function, which involves reshaping and manipulating tensors using PyTorch operations. Your task is to implement ...
```python import torch def process_tensors(xs, ys, wh, kept, inds, grid_size): xs = xs.view(xs.size(0), -1, 1) ys = ys.view(ys.size(0), -1, 1) wh = _transpose_and_gather_feat(wh, inds) wh = wh.view(wh.size(0), -1, 3) kept_offset = _transpose_and_gather_feat(kept[:, :4*grid_size, :], inds)...
magicoder
python
You are tasked with implementing a virtual list component in Vue 3. A virtual list is a UI component that efficiently renders a large list of items by only rendering the visible items and dynamically updating the rendered content as the user scrolls. The provided code snippet is a part of the implementation of this vir...
```javascript setup(props, { emit, slots, attrs, expose }) { const nh = useNameHelper('virtual-list') const { items, itemSize, itemFixed, idKey, defaultKeyAt, bufferSize } = toRefs(props) const scroll = ref<InstanceType<typeof NativeScroll> | null>(null) const list = ref<HTMLElement | null>(null) const wrap...
magicoder
javascript
You are given a linked list where each node contains an integer value and a reference to the next node in the list. Write a function `detectCycle` to determine if the linked list contains a cycle and return the node where the cycle begins if it exists. The function signature is: ```python def detectCycle(head: ListNod...
```python def detectCycle(head: ListNode) -> ListNode: slow = head fast = head while fast and fast.next: slow = slow.next fast = fast.next.next if slow == fast: break if not fast or not fast.next: return None slow = head while slow != fast: ...
magicoder
python
You are working on a project that involves using the e3nn library for tensor field networks in PyTorch. Your task is to create a custom tensor field transformation using the e3nn library and apply it to a given input tensor. The transformation involves using the o3 module from e3nn to perform a specific operation on th...
```python import torch from e3nn import o3 def custom_tensor_rotation(input_tensor, rotation_matrix): # Convert the rotation matrix to a rotation matrix in SO(3) rotation_matrix_so3 = o3.rot.from_matrix(rotation_matrix) # Convert the input tensor to e3nn tensor input_tensor_e3nn = o3.spherical_harmoni...
magicoder
python
You are tasked with implementing a loss calculation method for a deep learning model. The provided code snippet is a part of a larger deep learning framework. The `calc_losses` method is responsible for calculating the loss function for the model. The method takes in input data and a boolean flag `is_train` indicating ...
```python class DeepLearningModel: def __init__(self, lambda_coarse, lambda_fine): self.lambda_coarse = lambda_coarse self.lambda_fine = lambda_fine def calc_losses(self, data, is_train, global_step, using_fine=True): # Placeholder for actual loss calculation rgb_loss = 0.0 # P...
magicoder
python
You are tasked with creating a Django view that allows users to upload a new post with a picture. The view should also associate the post with the currently logged-in user. You are given the following code snippet as a starting point: ```python from users.models import Profile class Post(models.Model): descriptio...
```python from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from django.contrib.auth.decorators import login_required from django.utils import timezone from .models import Post from .forms import PostForm @csrf_exempt @login_required def create_post(request): if request.meth...
magicoder
python
You are given a list of integers and a target value. Your task is to implement a function that finds the closest value to the target in the list. If there are multiple closest values, return the smallest one. Function Signature: `def closest_value(arr: List[int], target: int) -> int:` Input: - `arr`: A list of intege...
```python from typing import List def closest_value(arr: List[int], target: int) -> int: left, right = 0, len(arr) - 1 closest = arr[0] # Initialize closest to the first element in the list while left <= right: mid = (left + right) // 2 if arr[mid] == target: return arr[mid] ...
magicoder
python
You are tasked with implementing a state machine for a simple animation system. The animation can be in one of four states: `hide`, `hiding`, `show`, or `showing`. The state machine should support transitioning between these states and provide methods to query the current state. You are given a partial code snippet th...
```csharp public class AnimationStateMachine { public enum States { hide, hiding, show, showing, } private States state; public void StartHiding() { if (state == States.hide) { state = States.hiding; } } public void F...
magicoder
csharp
You are tasked with implementing a function that takes a list of integers as input and returns 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 numb...
```python def find_median(lst): lst.sort() # Sort the list in ascending order n = len(lst) if n % 2 == 0: # If the list has an even number of elements mid1 = n // 2 mid2 = mid1 - 1 median = (lst[mid1] + lst[mid2]) / 2 # Calculate the average of the two middle numbers else: # ...
magicoder
python
You are tasked with implementing a function that calculates the total number of ways to reach the top of a staircase. You can climb the staircase by either taking 1 or 2 steps at a time. Write a function `countWaysToTop` that takes an integer `n` as input, representing the total number of steps in the staircase, and re...
```java public class StaircaseClimbing { public static int countWaysToTop(int n) { if (n <= 1) { return n; } int[] ways = new int[n + 1]; ways[0] = 1; ways[1] = 1; for (int i = 2; i <= n; i++) { ways[i] = ways[i - 1] + ways[i - 2]; } ...
magicoder
java
You are working on a data processing pipeline for analyzing information about biographical films. The pipeline takes a CSV file `cleaned_biopics.csv` as input and performs a series of operations using command-line tools. Your task is to write a script that accomplishes the same data processing steps as the given code s...
```bash #!/bin/bash # Step 1: Extract the first and sixth columns from the CSV file using comma as the delimiter cut -f 1,6 -d, ./data/cleaned_biopics.csv | # Step 2: Remove the first line (header) from the extracted data tail -n +2 | # Step 3: Sort the data sort | # Step 4: Remove duplicate entries uniq |...
magicoder
shell
You are given a graph represented by a list of edges. Each edge is represented by a struct `Edge` containing two integers `u` and `v`, denoting the vertices it connects. Your task is to write a function to determine whether the given graph contains a cycle. Write a function `bool hasCycle(vector<Edge>& edges, int n)` ...
```cpp #include <vector> struct Edge { int u, v; Edge(int u, int v) : u(u), v(v) {} }; bool isCyclicUtil(int v, std::vector<bool>& visited, std::vector<bool>& recStack, const std::vector<std::vector<int>>& adj) { if (!visited[v]) { visited[v] = true; recStack[v] = true; for (int u...
magicoder
cpp
You are given a class `Graph` that represents a directed graph using adjacency lists. The class has a method `topologicalSort` that returns a topological ordering of the graph nodes. The method uses a helper function `topologicalSortUtil` to perform the actual topological sorting. However, the implementation of the `to...
```cpp void Graph::topologicalSortUtil(int v, bool visited[], stack<int> &Stack) { // Mark the current node as visited visited[v] = true; // Recur for all the vertices adjacent to this vertex for (auto i = adj[v].begin(); i != adj[v].end(); ++i) { if (!visited[*i]) { topologicalSort...
magicoder
cpp
You are tasked with implementing a Python class to manage tiers of a cloud computing service. The class should provide methods to retrieve all tiers and to parse a tier from a string representation. You are given a code snippet that defines a `Tier` class and a `get_all_tiers` function that returns a list of predefine...
```python class Tier: def __init__(self, service_type, deployment_type, version): self.service_type = service_type self.deployment_type = deployment_type self.version = version class TierManager: @staticmethod def get_all_tiers(): lst = [ Tier('WebServer', 'Stand...
magicoder
python
You are tasked with implementing a custom data structure to manage web service requests. The structure should support equality comparison and include a header with specific properties. Your task is to create a Swift class `WSRequest` that represents a web service request. The `WSRequest` class should have the followin...
```swift /// Define an enumeration for request methods enum WSMethod { case get, post, put, delete } /// Define the WSRequestHeader struct struct WSRequestHeader { let path: String let method: WSMethod } /// Define the WSRequest class class WSRequest: Equatable { let uniqueId: String let header: W...
magicoder
swift
You are working on a project that involves analyzing neuron shapes represented as directed graphs. The graph is represented using the networkx library in Python. You have a function that reads a neuron shape file and generates a directed graph `G` representing the neuron shape. The function also returns the neuron shap...
```python import networkx as nx import numpy as np def fix_neuron_shape(G): G_d = G.copy() # Create a copy of the original graph to apply fixes # Step 1: Identify endpoints in the graph G endpoints = [node for node in G.nodes() if len(list(G.successors(node))) == 0] # Step 2: Calculate vectors repre...
magicoder
python
You are tasked with implementing a function to calculate the inverse error function (erf_inv) for a given input value. The inverse error function is a mathematical function that maps the range of the error function onto the real numbers. The function erf_inv_impl is used to approximate the inverse error function, and i...
```rust fn erf_inv(x: f64) -> f64 { if x < -1.0 || x > 1.0 { panic!("Input value must be in the range [-1, 1]"); } if x == 0.0 { return 0.0; } let mut result = 0.0; let abs_x = x.abs(); if abs_x < 0.75 { // Polynomial coefficients for the interval [0, 0.75] ...
magicoder
rust
You are tasked with implementing a function that checks whether a given string is a valid palindrome or not. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward, disregarding spaces, punctuation, and capitalization. You need to create a function `is_valid_pa...
```python def is_valid_palindrome(s: str) -> bool: # Convert the string to lowercase and remove non-alphanumeric characters s = ''.join(char.lower() for char in s if char.isalnum()) # Check if the modified string is equal to its reverse return s == s[::-1] ``` The `is_valid_palindrome` function fi...
magicoder
python
You are tasked with implementing a Python function that generates rows based on given input parameters. The function takes two arguments: `inx`, which represents the index of the row, and `result`, which is a dictionary containing keys that can be obtained from the `processor()` function in `mori.py`. The function shou...
```python def generate_row(inx, result): """ Generate each row. Args: inx (int): Index of this row. result (dict): Value of this row. It's a dictionary, keys can be found in function processor() in mori.py. Returns: None """ # Example implementatio...
magicoder
python
You are tasked with implementing a function compiler that takes a function as input and compiles it into a callable object. The function takes a `std::valarray<double>` as input and returns a `double`. Your goal is to create a class `function_compiler` that can compile different functions and then execute them. The `f...
```cpp #include <iostream> #include <valarray> #include <functional> class function_compiler { private: std::function<double(const std::valarray<double>&)> compiled_function; public: function_compiler(std::function<double(const std::valarray<double>&)> func) : compiled_function(func) {} double execute(co...
magicoder
cpp
You are tasked with implementing a simplified version of a timer wheel data structure in C++. A timer wheel is a circular array of slots, where each slot represents a specific time interval. When a timer is added to the wheel, it is placed in the slot corresponding to its expiration time. When the wheel "ticks," it adv...
```cpp #include <iostream> #include <memory> #include <vector> #include <functional> #include <unordered_map> class TimerBase { public: virtual ~TimerBase() {} virtual void addTimer(int expiration, std::function<void()> callback) = 0; virtual void advance(int ticks) = 0; virtual std::vector<std::functi...
magicoder
cpp