query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with implementing a function that parses a given HTML file and extracts specific information from it. The HTML file contains a section with a list of assets, each represented by a `<p>` tag with an associated index and content. Your task is to write a function that extracts the index and content of each ...
```python from typing import List, Tuple from bs4 import BeautifulSoup def parse_assets(html: str) -> List[Tuple[int, str]]: soup = BeautifulSoup(html, 'html.parser') assets_div = soup.find('div', id='display-choices') assets = assets_div.find_all('p') asset_list = [(int(asset['data-index']), asset.get...
magicoder
python
You are tasked with implementing a data structure to efficiently store and retrieve information about various aspects of user interactions in a system. The data structure should support operations for adding, updating, and retrieving user interaction data. You are given the following code snippet as a reference for th...
To efficiently store and retrieve user interaction data, we can use a combination of data structures such as hash maps and linked lists. Here's a possible implementation in Python: ```python class UserInteractionData: def __init__(self): self.interactions = {} def add_interaction(self, user_id, intera...
magicoder
python
You are tasked with creating a Python function that interacts with a Sysdig Secure API to manage security policies. The function should load configuration from environment variables, validate the configuration, and then create a client to interact with the Sysdig Secure API. You are given a code snippet that partially...
```python class SdSecureClient: def __init__(self, token, url): # Initialize the client with the provided token and URL self.token = token self.url = url def create_policy(self, name, rules): # Implement this method to create a new security policy with the given name and rules ...
magicoder
python
You are tasked with implementing a parser for a simple expression language that supports logical OR operations. The language consists of expressions formed by combining strings and logical operators. The logical OR operator is represented by `||`. Your goal is to write a function that parses an input string into an exp...
```rust #[derive(Debug, PartialEq)] enum Expression { Value(String), Or(Box<Expression>, Box<Expression>), } fn parse_expression(input: &str) -> Option<Expression> { let parts: Vec<&str> = input.split("||").map(|s| s.trim()).collect(); if parts.len() == 1 { Some(Expression::Value(parts[0].to_s...
magicoder
rust
You are tasked with creating a Python function that processes a given string containing commands for setting up a workflow management system. The function should extract and return the commands for copying files to specific directories. The input string will contain multiple commands, each on a new line, with the foll...
```python from typing import List, Tuple def extract_copy_commands(input_string: str) -> List[Tuple[int, str, str]]: commands = [] lines = input_string.split('\n') for line in lines: parts = line.split(':') if len(parts) == 2: command_number, copy_command = parts[0].split(') Cop...
magicoder
python
You are tasked with creating a Python class that simulates a simple online shopping cart system. The system should be able to handle products, discounts, and payments. Your task is to implement the necessary classes and methods to manage the shopping cart functionality. Your system should have the following classes: 1...
```python class Product: def __init__(self, name, price, category): self.name = name self.price = price self.category = category def display_info(self): print(f"Product: {self.name}, Price: ${self.price}, Category: {self.category}") class Discount: def __init__(self, perce...
magicoder
python
You are working on a data validation system that uses SHACL (Shapes Constraint Language) to define constraints on RDF (Resource Description Framework) graphs. Your task is to implement a Python function that validates a given RDF data file against a SHACL shape file and returns the validation result. You are provided ...
```python from pyshacl import validate def validate_rdf_data(data_file_text, shacl_file_text): res = validate(data_file_text, shacl_graph=shacl_file_text, data_graph_format='turtle', shacl_graph_format='turtle', inference='both', debug=True) conforms, graph, string = res ...
magicoder
python
You are tasked with implementing a function that adds a label to a view in a graphical user interface. The function takes several parameters to customize the appearance and position of the label. Your goal is to write a function that can be used to add labels to a view with the specified attributes. Write a function `...
```swift func addLabel(name: String, text: String, textColor: UIColor, textAlignment: NSTextAlignment, fontName: String, fontSize: CGFloat, x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat, lines: Int) -> UILabel { let label = UILabel(frame: CGRect(x: x, y: y, width: width, height: height)) label.text = ...
magicoder
swift
You are tasked with creating a script to automate the process of exporting geospatial data using Java and Spatialite libraries. The script should set the necessary environment variables and execute a Java class to perform the export operation. Your script should perform the following steps: 1. Set the `LD_LIBRARY_PATH...
```bash #!/bin/bash # Set the LD_LIBRARY_PATH environment variable export LD_LIBRARY_PATH="spatialite-libs-linux-x86_64/lib/" # Execute the Java command java -Djava.library.path="spatialite-libs-linux-x86_64/lib/" \ -Djava.util.logging.config.file="src/test/resources/logging.properties" \ -cp "target/*:targ...
magicoder
shell
You are tasked with creating a program to simulate the deformation of an asteroid's shape. The asteroid is represented by a collection of points and triangles in a 3D space. Your goal is to implement a function that calculates the deformed resultant radius of the asteroid after a deformation process. You are given a c...
```cpp void Asteroid::calculateDeformedResultantRadius() { GLfloat maxRadius = BASE_RADIUS; // Initialize the maximum radius with the base radius for (int i = 0; i < this->asteroidPoints.size(); i++) { Point p = this->asteroidPoints.data()[i]; // Perform calculations to determine the deformed ...
magicoder
cpp
You are tasked with creating a script to automate the download of specific files from a given URL using the `wget` command. Your script should be able to handle multiple file downloads and store them in a specified directory. You are given the following code snippet as a starting point: ```bash ## Based on setup, dow...
```bash #!/bin/bash # Define variables FILES_DL="file1.txt file2.zip file3.png" # Example file names to be downloaded DIR="/path/to/directory" # Example directory path URL="http://example.com/downloads/" # Example base URL # Script to download files echo "Starting download via wget." for myfile in $FILES_DL do ...
magicoder
shell
You are tasked with creating a custom widget for a web application using GWT (Google Web Toolkit). The widget will be used for uploading files and will need to incorporate various UI elements and functionality. Your task is to implement the `FileUploadWidget` class, which should extend `Widget` and implement `IsWidget`...
```java package org.sagebionetworks.web.client.widget.upload; import org.gwtbootstrap3.client.ui.Button; import org.gwtbootstrap3.client.ui.constants.ButtonSize; import org.gwtbootstrap3.client.ui.constants.ButtonType; import org.gwtbootstrap3.client.ui.constants.IconType; import org.sagebionetworks.web.client.PortalG...
magicoder
java
You are tasked with implementing a class for solving linear programming problems using the Simplex method. The given code snippet provides the skeleton of a `LpConstraint` class, which represents a constraint in the linear programming problem. Your task is to complete the implementation of the `LpConstraint` class by a...
```python class LpConstraint(object): "A LpSolve constraint." def __init__(self, numbers, vars): self.numbers = numbers self.vars = vars self.optype = None self.rhs = None def set_optype(self, optype): "Set the type of the constraint (e.g., 'LE', 'GE', 'EQ')." ...
magicoder
python
You are tasked with creating a script to manage swap space on a Linux system. The script should check if a swapfile exists, and if not, create a new swapfile and enable it. If the swapfile already exists, the script should not make any changes. Your script should perform the following steps: 1. Check if a swapfile alr...
```bash #!/bin/bash # Check if a swapfile already exists if ! grep -q '/swapfile' /etc/fstab; then # Create a new swapfile of 1GB size sudo fallocate -l 1G /swapfile sudo chmod 600 /swapfile sudo mkswap /swapfile sudo swapon /swapfile # Add the swapfile entry to /etc/fstab echo '/swapfile none swap defa...
magicoder
shell
You are tasked with creating a Python class to represent a statement made by a player in a game. The statement consists of the player's claim and the evidence supporting it. The evidence is represented as a tuple of tuples, where each inner tuple contains the index of the player and the set of roles they claim to have....
```python from enum import Enum class Role(Enum): SEER = "Seer" DRUNK = "Drunk" ROBBER = "Robber" TROUBLEMAKER = "Troublemaker" class Statement: def __init__(self, claim, evidence): self.claim = claim self.evidence = evidence def validate_evidence(self): roles = set() ...
magicoder
python
You are tasked with implementing a Python function that calculates the log-likelihood of a given data set for a Poisson distribution. The log-likelihood is a measure of how well a probability distribution function fits a set of data. The Poisson distribution is a discrete probability distribution that expresses the pro...
```python import numpy as np from scipy.stats import poisson def calculate_log_likelihood(data): # Initialize the Poisson distribution with parameter 5 poisson_dist = poisson(mu=5) # Calculate the log-likelihood for the given data log_likelihood = np.sum(poisson_dist.logpmf(data)) return ...
magicoder
python
You are given an array of integers `numbers` of length `n`. Your task is to find the maximum product of two distinct elements in the array. Write a function `maxProduct` that takes the array `numbers` and its length `n` as input and returns the maximum product of two distinct elements in the array. The function signat...
```c long long maxProduct(int numbers[], int n) { int max_index1 = 0; for (int i = 1; i < n; ++i) { if (numbers[i] > numbers[max_index1]) { max_index1 = i; } } int max_index2 = -1; for (int j = 0; j < n; ++j) { if ((j != max_index1) && ((max_index2 == -1) || (num...
magicoder
c
You are tasked with implementing a simple abstract syntax tree (AST) for a basic programming language. The AST will consist of nodes representing different operations or expressions in the language. Each node will have a `run` method that takes a stack as input and performs the corresponding operation on the stack. The...
```python from abc import ABC, abstractmethod class Node(ABC): @abstractmethod def run(self, stack): pass class Ast: def __init__(self): self.__nodes = [] def add_node(self, node): if isinstance(node, Node): self.__nodes.append(node) else: raise...
magicoder
python
You are tasked with implementing a rate-limiting mechanism for a Twitter API client. The given code snippet is a part of a class that processes Twitter trends for a specific location. The `process` method takes a `tuple` as input, extracts the location from it, and then attempts to retrieve the trending topics for that...
To implement the rate-limiting mechanism, you can introduce a rate-limiting decorator that can be applied to the `process` method. This decorator will track the number of requests made within a specific time frame and handle rate limit errors by logging the error and sleeping for a specified time before retrying the re...
magicoder
python
You are tasked with implementing a function that takes a string representing a PHP code snippet and checks if the snippet contains an incomplete HTML table structure. An incomplete HTML table structure is defined as having an opening `<table>` tag without a corresponding closing `</table>` tag, and an opening `<tbody>`...
```python def has_incomplete_table_structure(php_code: str) -> bool: table_opening_tag_count = php_code.count('<table>') table_closing_tag_count = php_code.count('</table>') tbody_opening_tag_count = php_code.count('<tbody>') tbody_closing_tag_count = php_code.count('</tbody>') return (table_openin...
magicoder
python
You are tasked with implementing a time management system for a simulation program. The given code snippet is a part of the time management logic, which is responsible for ensuring that each "tick" of the simulation occurs at regular intervals. The code uses a loop to calculate the time remaining until the next tick an...
```rust fn manage_time() { let mut elapsed = 0; loop { let start_time = current_time_in_millis(); if elapsed >= TICK_TIME { break; // Start next tick immediately } let remaining_time = TICK_TIME - elapsed; std::thread::sleep(Duration::from_millis(remaining_ti...
magicoder
rust
You are tasked with implementing a Python class for handling video messages in a messaging application. The class, named `InputMessageVideo`, is responsible for encapsulating various attributes of a video message. The provided code snippet outlines the class structure and a static method for reading input data. Your t...
```python class InputMessageVideo: def __init__(self, video, thumbnail, added_sticker_file_ids, duration, width, height, supports_streaming, caption, ttl): self.video = video # InputFile self.thumbnail = thumbnail # InputThumbnail self.added_sticker_file_ids = added_sticker_file_ids # lis...
magicoder
python
You are tasked with simulating a passcode lock system in Swift. The passcode lock system has a delegate that is notified whenever the state of the passcode lock changes. Your goal is to implement the `PasscodeLock` class and its delegate, and then write a function to test the state change functionality. The `PasscodeL...
```swift // PasscodeLock class to simulate a passcode lock system class PasscodeLock { weak var delegate: PasscodeLockDelegate? // Method to notify the delegate when the state of the passcode lock changes func passcodeLockDidChangeState(_ lock: PasscodeLockType) { delegate?.passcodeLockDidChangeSta...
magicoder
swift
You are tasked with implementing a Python function that simulates a simple banking system. The system should allow users to create accounts, deposit and withdraw funds, and check their balance. Additionally, the system should enforce a minimum balance requirement and prevent overdrafts. Your task is to implement the `...
```python class BankingSystem: def __init__(self, min_balance): self.min_balance = min_balance self.accounts = {} def create_account(self, account_id, initial_balance): if initial_balance < self.min_balance: raise ValueError(f"Initial balance must be at least {self.min_balan...
magicoder
python
You are tasked with implementing a custom appearance for a tab bar in a mobile application. The given code snippet is a part of the configuration for the appearance of the tab bar. The `TabmanBar.Appearance` class is used to define the visual properties of the tab bar, such as background color, indicator color, and sel...
```swift bar.appearance = TabmanBar.Appearance({ (appearance) in appearance.style.background = .solid(color: UIColor.white) appearance.indicator.color = Stylesheet.Colors.base appearance.indicator.lineWeight = 3 appearance.text.font = UIFont.systemFont(ofSize: 14) appearance.state.color = .lightGray...
magicoder
swift
You are tasked with implementing a file compression algorithm using the Run-Length Encoding (RLE) technique. RLE is a simple form of data compression where consecutive identical elements are replaced with a count and a single instance of the element. For example, the string "AAABBBCCC" would be compressed to "3A3B3C". ...
```python def compress_string(input_str): compressed = "" count = 1 for i in range(1, len(input_str)): if input_str[i] == input_str[i - 1]: count += 1 else: compressed += str(count) + input_str[i - 1] count = 1 compressed += str(count) + input_str[-1] ...
magicoder
python
You are tasked with writing a Python unit test for a gRPC service called `Doubler` using the `DoublerStub` and `Number` from the `doubler_pb2_grpc` and `doubler_pb2` modules, respectively. The test should be written within the `ExampleGrpcTestCase` class, which inherits from `BaseTestCase`. The test should make use of ...
```python import logging import unittest from services.doubler.doubler_pb2_grpc import DoublerStub from services.doubler.doubler_pb2 import Number from grpc import ChannelConnectivity from grpc import StatusCode log = logging.getLogger(__name__) METADATA = (('key1', 'val1'), ('key2', 'val2'),) TIMEOUT_SEC = 0.15 clas...
magicoder
python
You are tasked with creating a Python program to analyze and display statistics about movies and TV shows. The program should accept command-line arguments to specify different types of analysis to perform. The available command-line arguments are as follows: - `-r` or `--ratings`: Shows the count of movies and TV show...
```python import argparse import pandas as pd def init_app(): # Implement the logic to initialize the application and return the DataFrame, connection object, and variable # Example: df = pd.read_csv('movies_data.csv') # Replace 'movies_data.csv' with the actual data source con = None # Replace with ...
magicoder
python
You are tasked with implementing a CompressedDictWriter class that writes data to a compressed file in a custom format. The class should support writing a header row and writing data rows to the compressed file. The header row contains the field names, and the data rows contain corresponding values for each field. Addi...
```python import csv import zlib from io import BytesIO from collections import OrderedDict from hypothesis import given import hypothesis.strategies as st class CompressedDictWriter: def __init__(self, file_obj, fieldnames): self.file_obj = file_obj self.fieldnames = fieldnames self.compre...
magicoder
python
You are tasked with creating a Python program to control a set of lights connected to a Raspberry Pi using the GPIO pins. The program should also establish a socket connection to receive commands for turning the lights on and off remotely. Your program should have the following functionalities: 1. Initialize the GPIO ...
```python import RPi.GPIO as gpio import socket # Initialize GPIO pins def initialize_gpio(): gpio.setmode(gpio.BCM) gpio.setup(18, gpio.OUT) # Example GPIO pin for controlling the lights # Toggle the state of the lights def toggle_lights(): current_state = gpio.input(18) gpio.output(18, not current_...
magicoder
python
You are tasked with creating a program that parses HTML code to extract the URLs from anchor tags. An anchor tag in HTML is denoted by `<a>` and contains an `href` attribute that specifies the URL. The program should be able to extract these URLs and store them for further processing. Write a function `extract_urls_fr...
```python import re def extract_urls_from_html(html): pattern = r'<a\s+href="([^"]+)"' urls = re.findall(pattern, html) return urls # Test the function with the provided example html = ''' </li> <li> <a href="https://www.example.com"> ...
magicoder
python
You are given a code snippet representing an array of data related to lunar months in a specific format. Each line in the code snippet represents a year and contains the following information: - The year (e.g., 2002) - An array of 4 integers representing lunar month data (e.g., 0, 2, 12, 54432) - A comment indicating t...
```python from typing import List def averageLunarMonthDays(data: List[str], startYear: int, endYear: int) -> int: total_days = 0 total_months = 0 for line in data: year, months, comment = line.split("*/{") year = int(year.strip()) if startYear <= year <= endYear: month...
magicoder
python
You are tasked with creating a program that reads a file and counts the occurrences of each word within it. Your program should ignore punctuation and consider words regardless of their case (i.e., "Word" and "word" should be considered the same). Additionally, the program should output the top N most frequently occurr...
```csharp using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; class WordCounter { static void Main() { Console.Write("Enter the file path: "); string filePath = Console.ReadLine(); if (File.Exists(filePath)) ...
magicoder
csharp
You are given a list of password policies and passwords. Each policy specifies the lowest and highest number of times a given letter must appear for the password to be valid. For example, "1-3 a" means the password must contain 'a' at least 1 time and at most 3 times. Your task is to determine the number of valid passw...
```python def count_valid_passwords(policies, letters, passwords): valid_old = 0 valid_new = 0 for (low, high), letter, password in zip(policies, letters, passwords): count = password.count(letter) if low <= count <= high: valid_old += 1 if (password[low - 1] == letter) ^...
magicoder
python
You are tasked with implementing a feature for a mobile advertising plugin called `nend_plugin`. The feature involves creating a class called `UserFeature` in the file `UserFeature.swift`. The `UserFeature` class should have a method `fetchUserDetails` that makes a network request to retrieve user details from a remote...
```swift import Foundation class UserFeature { private var userDetails: [String: Any]? // Storing user details as a dictionary func fetchUserDetails(completion: @escaping (Result<[String: Any], Error>) -> Void) { guard let url = URL(string: "https://example.com/user-details") else { co...
magicoder
swift
You are tasked with creating a Python function that simulates a simple asynchronous task management system. Your function should take a list of asynchronous tasks, each represented by an async function, and execute them concurrently. However, there is a catch - if any of the tasks raises an exception, the function shou...
```python from typing import List, Any import asyncio async def execute_async_tasks(tasks: List[asyncio.coroutine]) -> List[Any]: try: results = await asyncio.gather(*tasks, return_exceptions=True) return [result for result in results if not isinstance(result, BaseException)] except Exception a...
magicoder
python
You are tasked with implementing a function that processes a list of image file names and returns a dictionary containing the count of each unique file extension present in the list. The function should ignore case when comparing file extensions. If a file name does not have an extension, it should be counted as "no_ex...
```python from typing import List, Dict import os def count_file_extensions(file_list: List[str]) -> Dict[str, int]: extension_count = {} for file_name in file_list: _, file_extension = os.path.splitext(file_name) if file_extension: file_extension = file_extension[1:].lower() # Rem...
magicoder
python
You are tasked with implementing a function for bilinear upsampling backward propagation in a deep learning framework. Bilinear upsampling is a method for increasing the resolution of an image using interpolation. The function `upsample_bilinear2d_backward_out_cpu_template` takes the gradient of the output, the gradien...
```cpp #include <torch/torch.h> torch::Tensor upsample_bilinear2d_backward_out_cpu_template( const torch::Tensor& grad_input, const torch::Tensor& grad_output, torch::IntArrayRef osize, torch::IntArrayRef input_size, bool align_corners, double scale_h, double scale_w ) { // Get input an...
magicoder
cpp
You are given a Python code snippet that manipulates files and directories using the `os` module. Your task is to write a Python function that performs a similar file manipulation operation based on the given code snippet. You need to implement a function `file_manipulation(path: str, new_dir: str, ext: str) -> None` ...
```python import os def file_manipulation(path: str, new_dir: str, ext: str) -> None: if not os.path.exists(os.path.join(path, new_dir)): os.mkdir(os.path.join(path, new_dir)) files_to_move = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f)) and f != new_dir and f.endswith('.' + ex...
magicoder
python
You are tasked with implementing a class that acts as an adapter to enable the use of a third-party library in an existing codebase. The third-party library contains a class `Adapter` that needs to be adapted to work with an interface `ITarget`. Your task is to create an adapter class that allows the `Adapter` class to...
```csharp // Adapter class provided by the third-party library public class Adapter { public void DoSomething1() { Console.WriteLine($"{typeof(Adapter)} 适配器调用Target方法1"); } public void DoSomething2() { Console.WriteLine($"{typeof(Adapter)} 适配器调用Target方法2"); } } // ITarget inter...
magicoder
csharp
You are tasked with creating a Python function that interacts with an API to retrieve and display random facts along with their corresponding images in a Discord chat using the `discord.py` library. The code snippet provided is a part of a larger program that accomplishes this task. The `fact_embed` object is used to c...
```python import aiohttp import discord async def get_random_fact(ctx): async with aiohttp.ClientSession() as session: async with session.get("https://some-random-api.ml/facts") as response: if response.status == 200: data = await response.json() if "fact" in dat...
magicoder
python
You are tasked with implementing a TypeScript interface for configuring flash points in a visualization application. The interface, `IFlashPointOptions`, defines the properties required to customize the appearance and behavior of flash points on the visualization. Your goal is to complete the interface by adding the mi...
```typescript export default interface IFlashPointOptions { color: [number, number, number, number]; nring: number; spead: number; size: number; view: any; points: any; // Add the missing properties with their respective types intensity: number; duration: number; fade: boolean; ...
magicoder
typescript
You are tasked with implementing a function that transforms chart data based on a given configuration. The function should take in the chart data and the configuration, and return the transformed data according to the configuration. You are given the following code snippet as a starting point for the function: ```jav...
```javascript function transformChartData(chartData, lineConfig) { // Assuming lineConfig contains specific transformation settings // Implement the transformation logic based on lineConfig // Example: If lineConfig specifies scaling the data, apply the scaling transformation to chartData // Placeholde...
magicoder
javascript
You are tasked with implementing a function that processes a list of strings representing a nested structure. Each string in the list represents a level of nesting, and the indentation level indicates the depth of the nesting. Your goal is to parse the input and construct a nested data structure that represents the hie...
```kotlin fun parseNestedStructure(strings: List<String>): Any? { val nestedStructure = mutableMapOf<String, Any?>() var currentMap = nestedStructure for (line in strings) { val depth = line.takeWhile { it.isWhitespace() }.length / 2 val key = line.trim() if (depth == 0) { ...
magicoder
kotlin
You are tasked with implementing a program that simulates a simple online marketplace. The marketplace operates with a virtual currency called "credits," and users can buy and sell items using these credits. Your program should support the following operations: 1. **Add User**: Add a new user to the marketplace with a...
```python class User: def __init__(self, username: str, credits: int): self.username = username self.credits = credits self.items_for_sale = {} class Marketplace: def __init__(self): self.users = {} def add_user(self, username: str, credits: int) -> None: if usernam...
magicoder
python
You are given a snippet of code that manipulates a matrix `A1` using the `numpy` library in Python. The code uses the `fill_diagonal` function to modify specific diagonals of the matrix `A1`. Additionally, another matrix `A2` is modified by directly filling its diagonal with a constant value. Your task is to implement...
```python from typing import List, Tuple def modify_matrix(A: List[List[int]], diagonals: List[Tuple[int, int]], values: List[int]) -> List[List[int]]: for i in range(len(diagonals)): start, end = diagonals[i] value = values[i] for j in range(start, end+1): A[j][j] = value r...
magicoder
python
You are tasked with implementing a currying function in JavaScript. Currying is the process of converting a function that takes multiple arguments into a sequence of functions that each take a single argument. Your task is to create a `curry` function that takes a binary function and returns a curried version of it. Th...
```javascript function curry(func) { return function curried(...args) { if (args.length >= func.length) { return func(...args); } else { return function (...moreArgs) { return curried(...args, ...moreArgs); }; } }; } // Test the curry function with a binary function function b...
magicoder
javascript
You are tasked with creating a Python program to manage a distributed system for performing arithmetic operations. The system consists of two workers: an addition worker and a subtraction worker. These workers are responsible for asynchronously processing pairs of numbers and performing the respective arithmetic operat...
```python import random from celery import Celery # Initialize Celery application app = Celery('arithmetic_tasks', broker='pyamqp://guest@localhost//') # Define addition worker @app.task def addition_worker(payload): num_1 = payload['num_1'] num_2 = payload['num_2'] result = num_1 + num_2 print(f"Addi...
magicoder
python
You are tasked with implementing a function that takes a string representing an HTML table and returns the number of rows in the table. The HTML table is represented as a string with the following format: ```html <table> <tr> <td>...</td> <td>...</td> ... </tr> <tr> <td>...<...
```javascript function countTableRows(table) { const trRegex = /<tr>/g; const matches = table.match(trRegex); return matches ? matches.length : 0; } ``` The `countTableRows` function uses a regular expression to match all occurrences of the `<tr>` tag within the input HTML table string. It then returns the...
magicoder
javascript
You are tasked with creating a memory leak detection tool similar to Valgrind's memcheck. Your tool should be able to analyze a given C or C++ program and identify memory leaks by tracking memory allocations and deallocations. Your memory leak detection tool should take the following command-line arguments: 1. `--tool...
```c #include <stdio.h> #include <stdlib.h> #include <string.h> void analyzeMemoryLeaks(const char* tool, const char* leakCheck, const char* showLeakKinds, const char* trackOrigins, const char* programName) { // Simulate memory leak analysis based on the provided command-line arguments printf("Memory leak anal...
magicoder
c
You are tasked with implementing a C++ class that simulates a simple file system. The file system should support creating, deleting, and listing files and directories. Additionally, it should provide functionality to navigate through directories and display the current working directory. You are provided with a partia...
```cpp #include <iostream> #include <string> #include <vector> namespace paddle { namespace lite { namespace kernels { namespace host { class FileSystem { public: // Constructor to initialize the file system with a root directory FileSystem() : currentDirectory("/") {} void createFile(const std::string& ...
magicoder
cpp
You are working on a natural language processing (NLP) project and need to implement a feature builder class that utilizes word embeddings to represent words as feature vectors. Word embeddings are dense vector representations of words in a continuous vector space, often used in NLP tasks such as text classification, s...
```python class FeatureBuilder: def __init__(self, featureSet, style=None): self.featureSet = featureSet self.style = style def setFeature(self, featureName, value): # Set the feature with the given name and value # Implementation depends on the specific requirements of the feat...
magicoder
python
You are tasked with implementing a module resolution algorithm for a simple JavaScript module system. The module system uses the `export` statement to make certain elements available for use in other modules. When a module imports another module, the module resolution algorithm must determine the location of the import...
```javascript function resolveModulePath(currentModulePath, importPath) { const exports = { "./layout": "/modules/layout", "./models": "/modules/models", "./style": "/modules/style" }; if (exports.hasOwnProperty(importPath)) { return exports[importPath]; } else if (importPath.startsWith("./")) ...
magicoder
javascript
You are tasked with implementing a user authentication system for a mobile application. The system should handle user login attempts and provide appropriate feedback based on the input provided. You are given a partial code snippet that includes some of the functions and variables required for the authentication system...
```swift func didTapLoginButton(userName: String, password: String) { var usernameTextErrorMessage: String? if userName.count < 2 || userName.count > 15 { usernameTextErrorMessage = "Invalid username length. Username must be between 2 and 15 characters." } if let errorMessage = usernameTextErro...
magicoder
swift
You are given a string `S` consisting of uppercase letters. The uniqueness of a letter is determined by the number of occurrences of that letter in the string. The uniqueness of a letter at a specific index `i` is defined as the number of occurrences of the letter at index `i` multiplied by the distance between the two...
```python class Solution: def uniqueLetterString(self, S: str) -> int: import string idxes = {ch : (-1, -1) for ch in string.ascii_uppercase} ans = 0 for idx, ch in enumerate(S): i, j = idxes[ch] ans += (j - i) * (idx - j) idxes[ch] = j, idx ...
magicoder
python
You are given a triangular array of integers as shown below: ``` 20 19 01 88 02 77 99 65 04 28 41 41 26 56 83 ``` Your task is to write a function `findMaxPathSum` to find the maximum path sum from the top to the bottom of the triangle. The maximum path sum is defined as the maximum total sum of integers in a path fr...
```python from typing import List def findMaxPathSum(triangle: List[List[int]]) -> int: n = len(triangle) # Start from the second last row and move upwards for i in range(n - 2, -1, -1): for j in range(i + 1): # For each element, find the maximum sum path from that element to the b...
magicoder
python
You are given a matrix A of size m x n and an integer k. Your task is to write a function to perform a truncated Singular Value Decomposition (SVD) on the matrix A and return the reconstructed matrix using the first k singular values. The truncated SVD of a matrix A is given by A ≈ UΣV^T, where U is an m x k matrix, Σ...
```python from typing import List import numpy as np def truncated_svd(A: List[List[float]], k: int) -> List[List[float]]: A = np.array(A) U, S, Vt = np.linalg.svd(A, full_matrices=False) reconstructed_A = np.dot(U[:, :k] * S[:k], Vt[:k, :]) return reconstructed_A.tolist() ``` The `truncated_svd` func...
magicoder
python
You are tasked with implementing a class that controls the navigation between a TreeView control and a WriterControl. The class, `NavigateTreeViewControler`, has been partially implemented with a constructor and a method for starting the controller. Your task is to complete the implementation by adding methods to handl...
```csharp public class NavigateTreeViewControler { private TreeView treeView; private WriterControl writerControl; public NavigateTreeViewControler(TreeView treeView_1, WriterControl writerControl_1) { treeView = treeView_1; writerControl = writerControl_1; } public bool Start(...
magicoder
csharp
You are tasked with creating a program that analyzes a given software license text to extract and display the permissions granted by the license. The license text is a multi-line string containing various permissions and conditions. Each permission is listed as a separate line and begins with a verb or action, followed...
```python def extract_permissions(license_text): permissions = [] lines = license_text.split('\n') for line in lines: if line.strip(): # Check if the line is not empty words = line.split() if words[0].lower() == 'to' or words[0].lower() == 'and': verb = words...
magicoder
python
You are tasked with implementing a performance monitoring system for a deep learning model training process. The system should track and display the average loss, top-1 accuracy, and top-5 accuracy over the most recent 100 iterations of the training process. To achieve this, you will need to create a class to calculate...
```python import time import utils # Assume the utils module contains the AverageMeter class and other necessary utilities loss_meter = utils.AverageMeter(recent=100) top1_meter = utils.AverageMeter(recent=100) top5_meter = utils.AverageMeter(recent=100) timestamp = time.time() for i, (images, labels) in enumerate(t...
magicoder
python
You are tasked with creating a simple system information web service using Rust and Actix-web. Your goal is to implement an endpoint that returns the system information of the server in JSON format. The system information should include details such as the operating system, kernel version, CPU usage, memory usage, and ...
```rust extern crate actix_files; extern crate actix_web; extern crate sysinfo; use actix_web::{web, App, HttpServer, HttpResponse, Responder}; use sysinfo::{System, SystemExt}; fn system_info_handler() -> impl Responder { let mut sys = System::new(); sys.refresh_all(); let os = sys.get_operating_system(...
magicoder
rust
You are tasked with implementing a tokenizer for a simple programming language. The tokenizer should take an input string of code and convert it into a sequence of tokens, which are the smallest units of the language's syntax. Each token represents a specific element of the code, such as keywords, identifiers, numbers,...
```rust fn tokenize(mut job: Job) -> Vec<Token> { while !job.cursor.is_end() { // name tokens if let Some(x) = job.patterns.name.extract(job.cursor.tail()) { let x = try_traced!(x); job.push_token(Token::Name(x.name.to_string())); job.cursor.move_by(x.position.1);...
magicoder
rust
You are tasked with creating a Python function to validate a dictionary of URLs based on a given set of rules. The function should take in two parameters: a dictionary of URLs and a list of valid locations. The dictionary contains keys representing server addresses and ports, with corresponding values being lists of UR...
```python def validate_urls(valid_urls_dict: dict, valid_locations: list) -> bool: for urls in valid_urls_dict.values(): for url in urls: if url not in valid_locations: return False return True ``` The solution iterates through the values of the `valid_urls_dict` and checks ...
magicoder
python
You are tasked with creating a program to fetch and store photo records from the Flickr API. The provided code snippet initializes the `firstPage` variable with the value 1 and sets up the Flickr API using the `flickrapi` library. It then initializes an empty list `photoDb` to store fetched photo records and sets the `...
```python import flickrapi def fetch_photos_from_flickr(flickr_api_key, flickr_api_secret): firstPage = 1 flickr = flickrapi.FlickrAPI(flickr_api_key, flickr_api_secret, format='parsed-json') photoDb = [] fetchPage = firstPage while True: # Fetch photo records from the Flickr API p...
magicoder
python
You are tasked with implementing a keyframe animation system for a graphics application. The system uses a list of keyframes, each with a time value and corresponding animation value. Additionally, each keyframe may have an easing function associated with it to control the interpolation between keyframes. You are give...
```python def kf_func(t, v, easing_name, easing_args): # Implement the keyframe processing logic based on the easing function if easing_name == "linear": anim_kf.append((t, v)) # Append the keyframe with linear interpolation elif easing_name == "ease_in": # Implement ease-in interpolation b...
magicoder
python
You are tasked with implementing a function to calculate the power set of a given set of integers. The power set of a set is the set of all possible subsets, including the empty set and the set itself. For example, the power set of {1, 2, 3} is {{}, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}}. You need to implem...
```python def power_set(nums): if not nums: return [[]] # Return a list containing the empty set element = nums[0] # Choose the first element remaining_set = nums[1:] # Get the remaining set # Recursively compute the power set of the remaining set subsets = power_set(remaining_set) ...
magicoder
python
You are tasked with implementing a custom annotation category view in a Swift iOS app. The annotation category view will display a list of categories and allow the user to select a category by tapping on it. To achieve this, you need to complete the implementation of the `AnnotationCategoryView` class and its delegate ...
```swift import UIKit protocol AnnotationCategoryViewDelegate { func categorySelected(_ category: String) } class AnnotationCategoryView: UIView { var categories: [String] = [] var delegate: AnnotationCategoryViewDelegate? func setupView() { // Implement the initial appearance and behavior se...
magicoder
swift
You are tasked with implementing a ticket triaging system for a software support team. The system should categorize incoming tickets based on their type and urgency, and then redirect them to the appropriate support team. Each ticket is represented as a tuple containing the following information: ticket type (string), ...
```python def triage_ticket(ticket): ticket_type, urgency, escalation, redirect_status, _ , no_redirect = ticket if ticket_type == "PROBLEM_TICKET_TYPE" and urgency and escalation and redirect_status: return 200 else: return no_redirect() ``` The `triage_ticket` function extracts the ticket ...
magicoder
python
You are tasked with debugging and improving a piece of code that is intended to present a web page using a Safari view controller in an iOS app. The code snippet provided is a part of the implementation, but it seems to have some issues. Your goal is to identify the problems and propose a more robust and efficient solu...
1. Potential issues and improvements in the provided code: a. The comment "optional" does not provide clear context and might be misleading. b. The comment "TODO" suggests that the code might need to be revisited, indicating potential issues or incomplete implementation. c. The use of `UIApplication.shared.key...
magicoder
swift
You are tasked with creating a custom operation model for an AWS SDK application. The operation model will be used to define the input and output shapes for a specific API operation. The operation model should include the following attributes: - Operation name: A string representing the name of the API operation. - Inp...
```typescript import { OperationModel as _Operation_ } from '@aws-sdk/types'; interface Shape { // Define the structure of the shape } class CustomOperationModel implements _Operation_.OperationModel { name: string; input: Shape; output: Shape; constructor(name: string, input: Shape, output: Shape) { t...
magicoder
typescript
You are tasked with implementing a custom loading view model for a mobile application. The loading view model should conform to the `CustomizableLoadingViewModel` protocol, which is defined as follows: ```swift protocol CustomizableLoadingViewModel: AnyObject { var output: LoadingOutput? { get set } } ``` Your ta...
```swift // Define the LoadingOutput protocol for communication with the view layer protocol LoadingOutput: AnyObject { func loadingStarted() func loadingStopped() func updateLoadingProgress(_ progress: Float) } // Implement the CustomLoadingViewModel class conforming to the CustomizableLoadingViewModel pr...
magicoder
swift
You are tasked with implementing a macro for a utility module in Rust. The macro should take a list of integers as input and return the sum of all the even numbers in the list. Additionally, the macro should be able to handle an empty list and return 0 in that case. Your task is to define the macro `sum_even` within t...
```rust #[macro_use] pub mod util { macro_rules! sum_even { ([]) => { 0 }; ([$x:expr, $($xs:expr),*]) => { if $x % 2 == 0 { $x + sum_even!([$($xs),*]) } else { sum_even!([$($xs),*]) } }; } } ``` The `...
magicoder
rust
You are tasked with implementing a function to parse and process Haml templates in a Python application. Haml is a lightweight markup language that is used to describe the HTML of web pages. The function `templatize` takes a Haml template as input and converts it into a format that can be used by the application. The f...
```python import re def templatize(template, origin=None): # Regular expression pattern to match translatable strings enclosed within trans and blocktrans tags trans_pattern = r'-(\s*)trans\s+["\'](.+?)["\']' blocktrans_pattern = r'-(\s*)blocktrans\n\s+(.+?)\n' # Mark translatable strings for translat...
magicoder
python
You are tasked with creating a function that sanitizes and constructs a SQL query string based on a given template and an array of values. The function should replace placeholders in the template with the corresponding values and ensure that the final query string is safe from SQL injection attacks. Write a function `...
```javascript function sanitizeAndConstructQuery(template, values) { let query = template; for (let i = 0; i < values.length; i++) { const placeholder = new RegExp(`&${i + 1}`, 'g'); const sanitizedValue = typeof values[i] === 'string' ? `'${values[i].replace(/'/g, "''")}'` : values[i]; query = query.re...
magicoder
javascript
You are tasked with implementing a function that takes in a list of integers and returns the maximum product of any three numbers in the list. If the input list contains less than three integers, the function should return None. Write a function `max_product_of_three` that takes in a list of integers and returns the m...
```python from typing import List, Optional def max_product_of_three(nums: List[int]) -> Optional[int]: if len(nums) < 3: return None nums.sort() return max(nums[-1] * nums[-2] * nums[-3], nums[0] * nums[1] * nums[-1]) ```
magicoder
python
You are given a Python dictionary containing character keys and their corresponding hexadecimal values. Your task is to write a function that takes this dictionary as input and returns a new dictionary with the characters as keys and their corresponding ASCII values as values. Function Signature: `def hex_to_ascii(inp...
```python def hex_to_ascii(input_dict: dict) -> dict: output_dict = {} for key, value in input_dict.items(): output_dict[key] = int(value) return output_dict ```
magicoder
python
You are tasked with creating a program to manage student records in a university database. The program should include functionality to save student information and handle potential rollbacks in case of errors. Your task is to implement a method `saveStudentWithRollBack` in the `StudentService` class that saves a stud...
```java import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class Student { // Student class with relevant attributes and methods } public class StudentService { private static final String DB_URL = "jdbc:mysql://localhost/university"; private static final Strin...
magicoder
java
You are given a singly linked list and are required to determine whether the list is a palindrome. A palindrome is a sequence that reads the same forwards and backwards. You are to implement the function `isPalindrome` that takes the head of the linked list as input and returns `True` if the linked list is a palindrom...
```python class ListNode: def __init__(self, data=0, next=None): self.data = data self.next = next def isPalindrome(head: ListNode) -> bool: # Function to reverse a linked list def reverseLinkedList(node): prev = None current = node while current: next_no...
magicoder
python
You are tasked with implementing a test case for a Python application using the pytest framework. The application involves checking for the presence of support tables and ensuring that the expected support tables are available. The code snippet provided is a part of the test case implementation and includes an assertio...
```python import pytest # Fixture to provide support tables @pytest.fixture def support_tables(): return ["ANTENNA", "TRANSMITTER", "RECEIVER", "AMPLIFIER"] # Test case function to check for the presence of the "ANTENNA" table @pytest.mark.predict @pytest.mark.parametrize("table", ["ANTENNA"]) def test_lazy_table...
magicoder
python
You are working on a Python package for life cycle assessment (LCA) and need to implement a function to perform sensitivity analysis on the environmental impacts of a product. The sensitivity analysis will involve identifying the global sensitivity of various parameters in the LCA model. The package provides a module c...
```python from .sensitivity_analysis import GlobalSensitivityAnalysis def perform_global_sensitivity_analysis(lca_model): sensitivity_analysis = GlobalSensitivityAnalysis(lca_model) sensitivity_indices = {} parameters = sensitivity_analysis.get_parameters_DF() for parameter in parameters: ...
magicoder
python
You are tasked with implementing a Python class that abstracts an Asset Exchange Management (AEM) instance. The AEM class should provide functionality to connect to a connector and manage assets. The provided code snippet serves as a starting point for the AEM class, and you are required to extend it to include the nec...
```python from dampy.lib.Connector import Connector from dampy.lib.Assets import Assets class AEM: '''Class abstracting an AEM instance ''' def __init__(self): self.connected_connector = None self.assets = [] def connect_to_connector(self, connector): self.connected_connector = co...
magicoder
python
You are tasked with creating a Python function that interacts with a web browser using the Selenium library. Your function should open a specific website, perform a series of actions, and then close the browser using the `driver.quit()` method. However, you need to ensure that the browser is always closed, even if an e...
```python from selenium import webdriver from selenium.common.exceptions import WebDriverException def perform_web_actions(url): try: # Initialize the web driver driver = webdriver.Chrome() # Open the specified URL driver.get(url) # Perform some actions on ...
magicoder
python
You are tasked with implementing a function that determines the minimum number of platforms required at a railway station to avoid any schedule conflicts. Given the arrival and departure times of trains, your function should calculate the minimum number of platforms needed to ensure that no train has to wait for a plat...
```swift func minPlatforms(arrivals: [Int], departures: [Int]) -> Int { var platformsNeeded = 1 var result = 1 var i = 1 var j = 0 let n = arrivals.count while i < n && j < n { if arrivals[i] <= departures[j] { platformsNeeded += 1 i += 1 if platforms...
magicoder
swift
You are working on a cryptocurrency trading platform and need to implement a class to interact with the platform's API. The API provides methods for retrieving ticker information, OHLCV (Open, High, Low, Close, Volume) data, and order book data for different cryptocurrency trading pairs. You are tasked with implementin...
```python import requests class CryptoAPI: def __init__(self, base_url): self.base_url = base_url def api_call(self, endpoint, params, version, couple): url = f"{self.base_url}/{version}/{endpoint}/{couple}" response = requests.get(url, params=params) if response.status_code ==...
magicoder
python
You are tasked with implementing a function to detect anomalies in time series data using the median-based method. An anomaly is defined as a data point that significantly deviates from the expected behavior of the time series. The function should take as input a time series dataset, a window size for calculating the m...
```python import numpy as np def get_anomalies_median(ts, window_size, alpha): anomalies = {} for i in range(len(ts) - window_size + 1): window = ts[i:i + window_size] median = np.median(window) deviation = np.abs(ts[i + window_size - 1] - median) if deviation > alpha: ...
magicoder
python
You are working as a DevOps engineer for a company that utilizes HashiCorp Vault for managing secrets and sensitive data. As part of your responsibilities, you need to automate the process of interacting with Vault using shell scripting. Your task is to write a shell script that performs the following operations: 1. ...
```bash #!/bin/bash # Look up the details of the current Vault token vault token lookup # Store a secret in the Vault key-value store under the path `secret/example` vault kv put secret/example examplestring=helloworld exampleint=1337 # Retrieve the secret stored under the path `secret/example` from the Vault key-va...
magicoder
shell
You are tasked with implementing a label voting binary image filter using the ITK (Insight Segmentation and Registration Toolkit) library. The filter takes an input binary image and produces an output image where each pixel is assigned the label that occurs most frequently within a neighborhood around that pixel. The ...
```cpp template< typename TInputImage, typename TOutputImage > class LabelVotingBinaryImageFilter : public ImageToImageFilter< TInputImage, TOutputImage > { public: ITK_DISALLOW_COPY_AND_ASSIGN(LabelVotingBinaryImageFilter); using Self = LabelVotingBinaryImageFilter; using Superclass = ImageToImageFilter< TInput...
magicoder
cpp
You are tasked with creating a Python class to represent a hydraulic fracturing job in the oil and gas industry. The class should have attributes to store the type of hydraulic fluid used (`hyd_typ`) and the volume fraction of proppant in the fluid (`frac`). Additionally, the class should have a method to calculate the...
```python class HydraulicFracturingJob: def __init__(self, hyd_typ, frac): self.hyd_typ = hyd_typ self.frac = frac def calculate_proppant_mass(self, volume): proppant_mass = volume * self.frac * 1500 return proppant_mass # Example usage job = HydraulicFracturingJob("Water-based...
magicoder
python
You are tasked with implementing a simple user authentication system in Python. The system should allow users to set and change their passwords, lock their accounts after multiple failed login attempts, and unlock their accounts after a specified time period. You are provided with a partial code snippet for the User cl...
```python from datetime import datetime, timedelta class User: def __init__(self, user): self._user = user self._password = "" self._wasLocked = False self._lock_time = None self._container = eConsoleAppContainer() self.__appClosed_conn = self._container.appClosed.co...
magicoder
python
You are tasked with creating a program that converts Perl 6 code to Ruby using the Perlito6 compiler. The Perlito6 compiler is a tool that translates Perl 6 code into various target languages, including Ruby. Your goal is to write a Perl 6 program and then use the Perlito6 compiler to generate the equivalent Ruby code....
Perl 6 Program: ```perl class Person { has $.name; has $.age; method new($name, $age) { self.bless(:$name, :$age); } method greet() { say "Hello, my name is {$!name} and I am {$!age} years old."; } } my $person = Person.new("Alice", 25); $person.greet(); ``` Ruby Code (Genera...
magicoder
perl
You are tasked with creating a Python function that downloads a pre-trained model, loads its weights, removes the downloaded file, sets the model to evaluation mode, and returns the model. Your task is to complete the function by implementing the missing parts. Function Signature: ```python def load_and_return_model(...
```python import torch import urllib.request import os def load_and_return_model(model_weights_link: str, model_weights_path: str, global_model: torch.nn.Module) -> torch.nn.Module: # Download model weights from the given link and save to the specified path urllib.request.urlretrieve(model_weights_link, model_...
magicoder
python
You are tasked with creating a Python function that processes a dataset and trains a deep learning model using the Keras library. The function should perform data preprocessing, model training, and model evaluation. Your task is to complete the function `train_model` by filling in the missing code segments. You are p...
```python from dataset.generators import BaseGenerator from models import XceptionUnet from metrics import dice_coef, dice_loss, bce_with_tv_loss, binary_crossentropy from utils import makedir, get_number_of_steps from keras.callbacks import ModelCheckpoint from keras import backend as K import os def train_model(data...
magicoder
python
You are tasked with implementing a deserialization function for a custom data structure called `StructTag`. The `StructTag` data structure represents a tag for a structured data format and has a method `deserialize` for deserializing the tag from a byte array. The code snippet provided asserts that the deserialization ...
```python class StructTag: def __init__(self, tag_id, tag_name): self.tag_id = tag_id self.tag_name = tag_name def serialize(self): # Implement serialization logic to convert the StructTag object to a byte array # ... @staticmethod def deserialize(byte_array): #...
magicoder
python
You are tasked with implementing a simple event handling system for a graphical user interface (GUI) library. The library provides a `Widget` struct with various properties and methods. One of the properties is `y`, which represents the vertical position of the widget on the screen. The library also supports event hand...
```rust struct Widget { y: i32, save_y: i32, } enum Event { ScreenBuffer { alternate: bool, clear: bool, }, // Other event variants } impl Widget { fn handle_event(&mut self, event: Event, callback: fn(Event)) { match event { Event::ScreenBuffer { alternate,...
magicoder
rust
You are tasked with implementing a pagination system for a Firestore database. The pagination system should allow users to retrieve a specified number of documents from a collection, starting from a given cursor and optionally ending at another cursor. You are given the following parameters and types for the paginatio...
```php /** * @param int $offset The number of documents to skip before starting to return results. * @param int $limit The maximum number of documents to return. * @param \Google\Cloud\Firestore\Tests\Conformance\Cursor $start_at The cursor to start retrieving documents from. * @param \Google\Cloud\Firestore\Tests\...
magicoder
php
You are tasked with implementing a function that simulates a simple game. The game involves a player trying to reach a goal while avoiding obstacles. The player can move left or right, and the game ends when the player reaches the goal or collides with an obstacle. You are given a code snippet that represents the cond...
```python from typing import List, Set def simulate_game(player_moves: List[str], obstacles: Set[int], goal_position: int) -> str: player_position = 0 for move in player_moves: if move == "left": player_position -= 1 if player_position < 0: return "Player quits"...
magicoder
python
You are tasked with creating a class hierarchy for processing banking records related to Australian ABA (Australian Bankers' Association) files. The code snippet provided is a part of the namespace `Banking.AU.ABA.Records` and defines a class `ReturnsDetailRecord` which inherits from `DetailRecord`. The `ReturnsDetailR...
```csharp // Define the ReturnCode enumeration public enum ReturnCode { InvalidBsbNumber, AccountClosed, PaymentStopped, ReferToCustomer } // Define the DetailRecord class public class DetailRecord { public DateTime TransactionDate { get; set; } public int OriginatingTransactionDay { get; set; ...
magicoder
csharp
You are tasked with implementing a search functionality for a dataset loader in a Java application. The `DatasetLoader` class is responsible for loading datasets based on certain search criteria. The class has several member variables and a constructor that takes an `AdminView` object as a parameter. The member variab...
```java public class DatasetLoader { private Pagination pagination; private Dataset searchDataset; private String searchName; private String searchPath; private String searchStart = null; private String searchEnd = null; private String searchOwner; private boolean searchFlag = false; ...
magicoder
java
You are tasked with implementing a function to calculate the magnetic field components (Ex, Ey, Ez) at specified locations and times, given the magnetic susceptibility (kappa) and relative permittivity (epsr) values. The function should use the provided formula to calculate the magnetic field components and return them...
```python import numpy as np def calculate_magnetic_field(kappa=0.0, epsr=1.0): # Constants mu_0 = 4 * np.pi * 10**-7 # Permeability of free space # Calculate mu using the provided formula mu = mu_0 * (1 + kappa) # Calculate the magnetic field components (Ex, Ey, Ez) using the given values #...
magicoder
python
You are tasked with designing a database schema for a veterinary clinic that tracks information about animals and their physical characteristics. The schema should include a table for animals and a table for physical characteristics. The physical characteristics table should have a foreign key referencing the animal ta...
```sql -- Create the animal table CREATE TABLE animals ( id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY ); -- Create the physical characteristics table with foreign key reference CREATE TABLE physical_characteristics ( id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, animal_id INT UNSIGNED, cara VARCHAR(255), ...
magicoder
sql