query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with implementing a function to send an email notification from Zendesk to a Slack channel when a specific event occurs. The function `email_from_zendesk` takes three parameters: `event`, `slack_client`, and `zendesk_client`. The `event` parameter represents the event triggering the email notification, t...
```python def email_from_zendesk(event, slack_client, zendesk_client): # Extract relevant information from the event event_details = extract_event_details(event) # Compose the email notification message email_message = compose_email_message(event_details) # Send the email notification to the desig...
magicoder
python
You are tasked with creating a Python class to manage employees in an organization. The class should have the following functionalities: 1. Initialize the employee with their details. 2. Allow the manager to input a list of employees under them. 3. Display the details of the manager and the employees under them. You ...
```python class Employee: def __init__(self, name, emp_id, department): self.name = name self.emp_id = emp_id self.department = department self.emp_under = [] def display(self): print("Manager Name:", self.name) print("Manager ID:", self.emp_id) print("De...
magicoder
python
You are tasked with implementing a program that reads a sequence of integers from the command line arguments and calculates the sum of all the even numbers in the sequence. The program should ignore any non-integer command line arguments and consider only the valid integers for the sum calculation. Your task is to com...
```c #include <stdio.h> #include <stdlib.h> int main(int argc, char* argv[]) { int sum = 0; for (int i = 1; i < argc; i++) { char* endptr; long num = strtol(argv[i], &endptr, 10); if (*endptr == '\0') { if (num % 2 == 0) { sum += num; } } ...
magicoder
c
You are tasked with implementing a custom output buffering mechanism in C++. The provided code snippet contains a partial implementation of a custom output buffering system using the `std::ostream` class and namespaces. Your task is to complete the implementation of the custom output buffering system by defining the mi...
```cpp #include <iostream> #include <sstream> class out_buff : public std::stringbuf { public: out_buff(FILE* file) { setp(0, 0); setg(0, 0, 0); file_ = file; } ~out_buff() { sync(); } int sync() { if (pbase() != pptr()) { fwrite(pbase(), 1, ppt...
magicoder
cpp
You are working on a project that involves optimizing a system using different algorithms. One of the key steps in the optimization process is to perform a QR decomposition on a given matrix. The QR decomposition is a factorization of a matrix into an orthogonal matrix Q and an upper triangular matrix R. Your task is t...
```python import numpy as np def qr_decomposition(A): m, n = A.shape Q = np.zeros((m, n)) R = np.zeros((n, n)) for j in range(n): v = A[:, j] for i in range(j): R[i, j] = np.dot(Q[:, i], A[:, j]) v = v - R[i, j] * Q[:, i] R[j, j] = np.linalg.norm(v) ...
magicoder
python
You are tasked with creating a Python function that analyzes a given Django project's URL configuration and returns a list of all the views that are included in the project. The URL configuration is provided as a list of tuples, where each tuple represents a URL pattern and its corresponding view function. You are giv...
```python def extract_views(urlpatterns): views = [] for pattern in urlpatterns: if hasattr(pattern, 'url_patterns'): views.extend(extract_views(pattern.url_patterns)) elif hasattr(pattern, 'callback'): views.append(pattern.callback.__module__ + '.' + pattern.callback.__n...
magicoder
python
You are tasked with creating a Python unit test for a volume group snapshot creation function. The function takes in various options and should be tested to ensure that it interacts with the necessary mocks and asserts the expected behavior. Write a unit test for the `volume_group_snapshot_create_with_options` functio...
```python import unittest from unittest.mock import Mock class TestVolumeGroupSnapshot(unittest.TestCase): def setUp(self): self.app = Mock() self.client_manager = Mock() self.app.client_manager.volume = self.client_manager self.fake_volume_group = Mock() self.columns = ['co...
magicoder
python
You are working on a simulation system for a mining company. The system includes a class called `Simulator` that is responsible for simulating various scenarios related to the mining operations. The `Simulator` class has a method called `simulate` which takes a scenario generator as input and returns the simulation res...
```python class MiningSystem: def __init__(self, dm): self.dm = dm def bump_and_simulate(self, unit, shocks, scenario): result_with_bump = {} for item in shocks: currency = unit.split("/")[0] # Bump the raw materials self.dm.bump_raw_materials({item: ...
magicoder
python
You are tasked with implementing a program that takes command-line arguments and performs a specific operation based on the input. The program should accept two command-line arguments: a string representing an operation and a number on which the operation will be performed. The program should support the following oper...
```c #include <stdio.h> #include <stdlib.h> #include <string.h> int square(int num) { return num * num; } int cube(int num) { return num * num * num; } int factorial(int num) { if (num == 0 || num == 1) { return 1; } else { int result = 1; for (int i = 2; i <= num; i++) { ...
magicoder
c
You are tasked with implementing a file system utility in Python. The utility will involve creating a class to handle file operations within a directory. The provided code snippet outlines a `FileSection` class with some methods that need to be implemented. The `DIRTYPE` constant is also defined as 'dir'. Your task is...
```python DIRTYPE = 'dir' class FileSection: def __init__(self, file_path): self.file_path = file_path def read(self): with open(self.file_path, 'r') as file: content = file.read() return content def readinto(self, buffer): with open(self.file_path, 'r') as fil...
magicoder
python
You are tasked with implementing a function that processes data from a sensor network to identify specific events. The sensor network consists of multiple nodes, each generating timestamped data. The data is stored in a 2D NumPy array `G`, where each row represents a node and each column represents a timestamp. Additio...
```python import numpy as np def identify_events(G, T_test, Time): event_indices = [] for i in range(G.shape[0]): tmp_idx = np.where((G[i, :] >= T_test[i]) & (G[i, :] >= Time))[0] event_indices.append((i, tmp_idx)) return event_indices ``` The `identify_events` function iterates through eac...
magicoder
python
You are tasked with implementing a Python class that manages Docker containers for a Supervisor DNS service. The class, named `DnsManager`, has several methods and properties related to managing Docker containers. Your task is to complete the implementation of the `DnsManager` class by filling in the missing parts of t...
```python from typing import Any DNS_DOCKER_NAME = "dns_container" class DnsManager: def __init__(self, sys_plugins: Any): self.sys_plugins = sys_plugins def image(self) -> str: """Return name of Supervisor DNS image.""" return self.sys_plugins.dns.image @property def name(se...
magicoder
python
You are tasked with implementing a priority queue system for a server that processes network latency quality checks (NLQCs). The server has a function `run_next_in_queue` which takes an NLQC as input and processes it. The function also takes an optional `timeout` parameter, which specifies the maximum time the server s...
```python import queue import time class Server: def __init__(self): self.priority_queue = queue.PriorityQueue() def run_next_in_queue(self, nlqc, timeout=None): start_time = time.time() while True: if timeout is not None and time.time() - start_time >= timeout: ...
magicoder
python
You are working with a dataset containing behavioral metrics of mice in a research lab. The code snippet provided is part of a data processing pipeline to create a dataframe with behavioral metrics for all mice. The snippet iterates through each mouse's data, retrieves relevant behavioral information, and stores it in ...
```python import pandas as pd def extract_behavior_metrics(dataframe, mouse_nickname): mouse_data = dataframe[dataframe['mouse'] == mouse_nickname] if mouse_data.empty: return {} # Return empty dictionary if mouse data is not found metrics = { 'learned': mouse_data['learned'].values[0], ...
magicoder
python
You are tasked with implementing a ConstrainedAdvPoisoningGlobalExport algorithm for a machine learning model. The algorithm takes in several parameters, including delta, s, clst_model, lb, and G. Your task is to write a function that takes these parameters and performs the ConstrainedAdvPoisoningGlobalExport algorithm...
```python def constrained_adv_poisoning_global_export(delta, s, clst_model, lb, G): # Initialize the adversarial example as the original input adv_example = s # Perform the ConstrainedAdvPoisoningGlobalExport algorithm for G iterations for _ in range(G): # Compute the gradient of the loss with ...
magicoder
python
You are tasked with implementing a function to generate unique identifiers using the given code snippet as a reference. The `gen_trid` function is designed to create a random string of a specified length using a predefined character set `TRID_CSET`. The character set includes digits (0-9) and lowercase and uppercase le...
```python from random import choice from typing import List TRID_CSET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' def gen_unique_trid(length: int, existing_ids: List[str]) -> str: while True: new_id = ''.join(choice(TRID_CSET) for _ in range(length)) if new_id not in existin...
magicoder
python
You are working on a deployment script for a secure application that involves handling encrypted files. Your task is to write a Python function that simulates the decryption process of the encrypted file `secrets.tar.enc` using the provided encryption key and initialization vector (IV). The function should decrypt the ...
```python from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.primitives import padding from cryptography.hazmat.backends import default_backend import base64 import os def decrypt_secrets(encrypted_key: str, encrypted_iv: str, encrypted_file: str) -> str: try: ...
magicoder
python
You are working on a WordPress plugin that integrates with the Zopim live chat service. The code snippet provided is part of a larger PHP class that handles the plugin's settings and options. The `update_option` function is used to update a specific option in the WordPress database, and the `add_notice` method is used ...
```php function validate_and_update_zopim_settings($jsongreetings, $notices) { if (!empty($jsongreetings)) { // Validate the $jsongreetings array format (e.g., check for required keys, data types, etc.) $isValid = validate_jsongreetings($jsongreetings); // Implement the validation logic if ...
magicoder
php
You are tasked with implementing a function that borrows the standard input/output (stdio) and performs an operation on it. The function `borrow_stdio` takes two generic parameters: `F`, a closure or function, and `T`, the return type of the closure or function. The function signature is as follows: ```rust pub fn bor...
```rust use std::io; use std::io::Write; pub fn borrow_stdio<F, T>(f: F) -> Result<T, io::Error> where F: FnOnce() -> T, { let mut input = String::new(); // Read from standard input io::stdin().read_line(&mut input)?; // Execute the provided closure or function let result = f(); // Write...
magicoder
rust
You are tasked with implementing a class for a modified YOLOv3 model. The YOLOv3 model is a popular object detection algorithm, and in this case, it uses Darknet 53 as the default backbone. Your task is to complete the implementation of the `__init__` method of the YOLOv3 class, which takes in two parameters: `depth` a...
```python class YOLOv3: """ YOLOv3 model. Darknet 53 is the default backbone of this model. """ def __init__( self, depth=1.0, width=1.0, ): """ Initialize YOLOv3 model with modified Darknet 53 backbone. Args: - depth (float): Depth multiplie...
magicoder
python
You are tasked with implementing a class that parses YAML configuration files and provides methods to access and modify the configuration settings. The class should be able to handle both file-based and string-based YAML configurations. Your task is to complete the implementation of the `Yaml` class, which has two con...
```cpp #include "Yaml.h" namespace execHelper::yaml { Yaml::Yaml(const execHelper::config::Path& file) : m_yaml(file) { ; } Yaml::Yaml(const std::string& yamlConfig) : m_yaml(yamlConfig) { ; } } // namespace execHelper::yaml ``` The solution provides the complete implementation of the `Yaml` class with the ...
magicoder
cpp
You are working on a time-series database system and need to implement a function to parse query results. The function `Parse` takes several parameters including a pointer to `QueryResults`, an index `idx`, a pointer to `tsdb::label::Labels` `lset`, a vector of `tsdb::label::Labels` `lsets`, a pointer to `uint64_t` `id...
```cpp void Parse(QueryResults* results, int idx, tsdb::label::Labels* lset, std::vector<tsdb::label::Labels>* lsets, uint64_t* id, std::vector<std::vector<int64_t>>* t, std::vector<std::vector<double>>* v) { // Extract and process query results based on the provided parameters ...
magicoder
cpp
You are given a list of expenses incurred by a group of individuals. Each expense is a positive integer. Your task is to find the two expenses that sum up to a specific value. You need to write a function that takes the list of expenses and the required sum as input and returns the two expenses that satisfy the conditi...
```python from typing import List, Tuple def find_expenses(expenses: List[int], required_sum: int) -> Tuple[int, int]: expense_set = set() for expense in expenses: complement = required_sum - expense if complement in expense_set: return (complement, expense) expense_set.add(...
magicoder
python
You are tasked with creating a function that simulates the process of generating a new user ID for a website. The function should take a string representing the initial user ID and apply a series of transformations to produce the final user ID. The transformations are based on a set of rules specified below. Rules for...
```python import re def new_user_id(user_id: str) -> str: # Rule 1: Convert to lowercase user_id = user_id.lower() # Rule 2: Remove non-alphanumeric, hyphen, underscore, or period characters user_id = re.sub(r'[^a-z0-9-_.]', '', user_id) # Rule 3: Replace consecutive periods with a single...
magicoder
python
You are tasked with creating a program to manage a library's book borrowing system. The library has a collection of books, each identified by a unique ISBN (International Standard Book Number). The program should allow users to borrow and return books, as well as check the availability of a specific book. Your task is...
```python class Book: def __init__(self, isbn: str, title: str, author: str, quantity: int): self.isbn = isbn self.title = title self.author = author self.quantity = quantity class Library: def __init__(self): self.books = {} def add_book(self, isbn: str, title: str...
magicoder
python
You are tasked with creating a Python function that processes a given directory and its subdirectories to find all files that contain a specific keyword in their content. You should also handle the case where the keyword contains regular expression metacharacters. Write a function called `find_files_with_keyword(direc...
```python import os import re def find_files_with_keyword(directory, keyword): file_paths = [] keyword_pattern = re.compile(re.escape(keyword)) # Escape the keyword to handle metacharacters for root, _, files in os.walk(directory): for file in files: file_path = os.path.join(root, fil...
magicoder
python
You are tasked with implementing a class hierarchy for web components in a TypeScript project. The provided code snippet is a partial implementation of a core HTML component in TypeScript. Your task is to complete the implementation by defining the required properties and methods for the `CoreHtmlComponent` class and i...
```typescript import ISourceLines from "./ISourceLines"; import { WAComponent, WAElement } from "./WAComponents"; interface IMarkupComponent { // Define the required properties and methods for a markup component // For example: // property1: string; // method1(): void; } export class CoreHtmlComponent...
magicoder
typescript
You are tasked with implementing a function to convert a given dictionary into a JSON string. The function should handle nested dictionaries and should exclude any empty dictionaries from the output. The provided code snippet is part of a larger function that constructs a JSON string from a dictionary. The `result` var...
```python def ConvertDictionaryToJSON(dictionary): def ConvertToJSONString(value): if isinstance(value, dict): return ConvertDictionaryToJSON(value) else: return json.dumps(value) result = [] for key, value in dictionary.items(): if isinstance(value, dict): ...
magicoder
python
You are tasked with implementing a method for drawing objects in a game. The method `DrawWorker` takes in the location (`loc`), rotation (`rot`), object definition (`thingDef`), object instance (`thing`), and extra rotation (`extraRotation`) as parameters. Your task is to complete the implementation of the `DrawWorker`...
```csharp public override void DrawWorker(Vector3 loc, Rot4 rot, ThingDef thingDef, Thing thing, float extraRotation) { // Perform necessary calculations or transformations based on the parameters // Draw the object at the specified location with the given rotation and extra rotation // Example pseudo-code...
magicoder
csharp
You are tasked with creating a script to automate the provisioning of software packages on a Linux system. The script should handle the installation and version locking of the "puppet" package, as well as perform a system update using the "yum" package manager. Your task is to complete the script by adding the necessar...
```bash #!/bin/bash # Check if puppet is installed if ! rpm -q puppet &> /dev/null; then # Install and version lock puppet echo "Installing and version locking puppet..." yum install -y puppet yum versionlock puppet else echo "Puppet already installed" fi # Run system update echo "Running yum upda...
magicoder
shell
You are tasked with creating a Python program that organizes files in a specified directory based on their file extensions. Your program should prompt the user to input a source directory and a destination directory. It should then scan the source directory for files and move them to the destination directory, organizi...
```python import os import shutil def organize_files_by_extension(): source_dir = input("Enter the source directory path: ") destination_dir = input("Enter the destination directory path: ") if not os.path.exists(source_dir): print("Source directory does not exist.") return if not os.p...
magicoder
python
You are tasked with creating a data provider method for a testing framework that reads search terms from an external CSV file and provides them as test data for search functionality testing. Your task is to implement the `csvToMap` method and the `multipleSearchTermsFromExternalSource` data provider method. The `csvTo...
```java import org.testng.annotations.DataProvider; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class SearchTermsDataProvider { public static List<Map<String, String...
magicoder
java
You are tasked with implementing a function to create a user from input email and password. The function should prompt the user to specify their email and password for a given server host, and optionally an alias. The function should then check if it is possible to log in with the provided credentials and return the us...
```python class User: def __init__(self, email, password, alias=None): self.email = email self.password = password self.alias = alias def create_user_from_input_email_and_password(host, alias=None): """ Ask email and password, check that it is possible to login with this credentials...
magicoder
python
You are tasked with implementing a Python class method that manages a pool of VIP users in a web application. The class, named `VIPManager`, contains a method `create_pool` that takes in a `context` object and a `pool` object as parameters. The `pool` object represents a new pool of VIP users to be created in the appli...
```python class VIPManager: def __init__(self, events, database): self.events = events # Events related to VIP management self.database = database # Database for VIP user management def create_pool(self, context, pool): if not pool.name: raise ValueError("VIP pool name can...
magicoder
python
You are tasked with designing a database schema for a university's course management system. The system should maintain information about departments, courses, and users (such as students, professors, and staff). Each course is associated with a department, and users may be related to courses in various roles (e.g., st...
```php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateUniversitySchema extends Migration { public function up() { Schema::create('departments', function (Blueprint $table) { $table->id(); ...
magicoder
php
You are tasked with creating a program to parse and process HTML table data. Given an HTML table snippet as a string, your program should extract the table data and perform specific operations on it. Write a function `process_html_table` that takes in a string `html_table` representing an HTML table and returns a lis...
```python from bs4 import BeautifulSoup def process_html_table(html_table): soup = BeautifulSoup(html_table, 'html.parser') table = soup.find('table') headers = [header.text for header in table.find_all('th')] rows = table.find_all('tr')[1:] # Exclude the header row result = [] for row in rows...
magicoder
python
You are tasked with creating a TypeScript module that provides autocomplete functionality for a web application. The module should export various classes and interfaces related to autocomplete functionality. The provided code snippet is a partial export statement from a TypeScript module that includes the export of dif...
```typescript // sc-autocomplete.model.ts export interface SCAutocompleteModel { // Define the structure of the autocomplete data // Example: id: number; label: string; // Add other properties as required } // clr-autocomplete.item.ts export class CLRAutocompleteItem { // Represent an item in the autocompl...
magicoder
typescript
You are tasked with creating a function that processes data from an API and performs a specific setup operation. The function `setup` takes two parameters: a reference to a `barrel` object obtained from the `api` and a `schema_name` string. The function is asynchronous and returns a result that may contain an error. Yo...
```rust use std::error::Error; use std::fmt; // Define the Barrel type representing the data storage container struct Barrel; // Define the SetupError type to represent potential setup errors #[derive(Debug)] struct SetupError { message: String, } impl fmt::Display for SetupError { fn fmt(&self, f: &mut fmt:...
magicoder
rust
You are tasked with implementing a function to scrape headlines and categorize them from a satirical news website called "The Beaverton." The function should scrape headlines from the website and categorize them based on a predefined schema. The function should return a dictionary containing the scraped headlines, the ...
```python def beavertonScrape() -> dict: # Placeholder for scraped headlines (to be replaced with actual scraping logic) all_headlines = ["Satirical headline 1", "Humorous headline 2", "Sarcastic headline 3"] # Placeholder for predefined schema (to be replaced with actual schema definition) schemaList ...
magicoder
python
You are tasked with creating a script to automate the installation of software packages on a Linux system. The script should execute a series of commands to update the package repository, install specific software packages, and display messages at certain points during the process. Your task is to write a Bash script t...
```bash #!/bin/bash # Update the package repository sudo apt-get update # Install PyCharm IDE sudo apt-get install pycharm # Install PyCharm Community Edition sudo apt-get install pycharm-community # Display "Installed..." and wait for 3 seconds echo "Installed..." sleep 3 # Display "Install VLC" and wait for 3 se...
magicoder
shell
You are tasked with creating a Python function that processes financial data and generates a summary report in an Excel spreadsheet using the `openpyxl` library. The function should take in two parameters: `income_statement` and `stonk_rows`. The `income_statement` parameter is a dictionary containing financial informa...
```python import openpyxl from openpyxl.utils import get_column_letter from openpyxl.worksheet.table import Table, TableStyleInfo def generate_financial_summary(income_statement, stonk_rows): workbook = openpyxl.Workbook() worksheet = workbook.active worksheet.title = 'Financial Summary' currency = in...
magicoder
python
You are tasked with creating a Python function that processes a list of dictionaries representing software units. Each dictionary contains information about the unit, including a list of binary file paths. Your function should iterate through each unit, modify the file permissions of the binaries, and return the update...
```python import os import subprocess from typing import List, Dict, Union def process_units(units: List[Dict[str, Union[str, List[str]]]]) -> List[Dict[str, Union[str, List[str]]]]: for unit in units: for i in range(len(unit['binaries'])): unit['binaries'][i] = os.path.join(unzipDir, unit['bin...
magicoder
python
You are tasked with creating a Python class that interacts with a database using a Data Access Layer (DAL). The provided code snippet imports a `TestDal` class from a module named `test_db`. Your task is to implement a new class called `UserManager` that utilizes the `TestDal` to perform user management operations. Yo...
```python from .test_db import TestDal class UserManager: def __init__(self, dal: TestDal): self.dal = dal def create_user(self, username: str, email: str) -> bool: # Assuming TestDal has a method create_user that returns True on success return self.dal.create_user(username, email) ...
magicoder
python
You are tasked with implementing a Hierarchical Alternating Least Squares (HALS) algorithm for non-negative matrix factorization. In this problem, you will focus on updating the components U_1, U_2, ..., U_N of a non-negative matrix factorization model. The HALS algorithm is an iterative optimization process used to fa...
```python # iii) Update component U_1, U_2, ... U_N # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ while result.still_optimizing: # First, HALS update. for n in range(X.ndim): # Select all components, but U_n components_except_n = [U_i for i, U_i in enumerate(com...
magicoder
python
You are tasked with creating a C# program that simulates a simple proxy server. The program should intercept and modify HTTP requests before forwarding them to the destination server. Your task is to implement the proxy server functionality to modify the HTTP request headers. Your program should have the following fea...
```csharp using System; using System.Net; using System.Net.Sockets; using System.Text; namespace ProxyServerApp { public class ProxyServer { private int port; private TcpListener listener; public ProxyServer(int port) { this.port = port; listener = new T...
magicoder
csharp
You are tasked with implementing a file system utility function in Rust. The function should read the contents of a directory and return a mapping of file names to their corresponding metadata. You are provided with a code snippet that demonstrates the usage of the `read_entries` function. The function takes a mutable...
```rust use std::collections::HashMap; use std::fs; use std::path::Path; fn read_entries(dir: &mut fs::ReadDir) -> Result<HashMap<String, fs::Metadata>, std::io::Error> { let mut entries_map = HashMap::new(); for entry in dir { let entry = entry?; let path = entry.path(); let file_name...
magicoder
rust
You are tasked with implementing a class that performs matrix decomposition to extract scale, rotation, and translation components from a 4x4 transformation matrix. The transformation matrix is represented using the `mat4` data type, and the decomposition process involves using the `glm::decompose` function from the GL...
```cpp #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtx/matrix_decompose.hpp> class Transform { public: glm::vec3 scale; glm::quat rotation; glm::vec3 position; Transform(glm::mat4 matrix) { glm::vec3 skew; glm::vec4 persp...
magicoder
cpp
You are given the inorder and postorder traversal sequences of a binary tree. Your task is to construct the binary tree from these traversal sequences and return the root node of the tree. The inorder traversal sequence of a binary tree is a list of nodes obtained by performing an inorder traversal of the tree. Simila...
```python class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution(object): def buildTree(self, inorder, postorder): """ :type inorder: List[int] :type postorder: List[int] :rtype:...
magicoder
python
You are tasked with creating a model factory for a fictional web application. The application is a platform for managing and sharing recipes. Your task is to implement a model factory for the `Recipe` model using a programming language of your choice. The `Recipe` model has the following attributes: - `id`: a unique i...
```python import random import faker fake = faker.Faker() def generate_fake_recipe_instances(num_instances): recipes = [] for _ in range(num_instances): recipe = { 'id': fake.uuid4(), 'name': fake.catch_phrase(), 'description': fake.text(max_nb_chars=200), ...
magicoder
python
You are tasked with implementing a Python function that processes a given string to remove any leading indentation based on the provided indentation level and quote character. The function should take the following parameters: - `text`: A string representing the text to be processed. - `indent`: An integer representing...
```python def remove_indentation(text, indent, quote, indent_char): """Remove leading indentation based on the provided parameters""" lines = text.splitlines() processed_lines = [] for line in lines: if line.startswith(quote): line_indent = len(quote) else: line_i...
magicoder
python
You are tasked with implementing a class for controlling a motor in a robotic system. The class should provide methods for checking if the motor is ready and for retrieving the target position of the motor. Below is the skeleton of the motor control class: ```java public class MotorController { /** * Retrieves th...
```java public class MotorController { private boolean motorAttached; private String attachedControllerType; public MotorController() { this.motorAttached = false; this.attachedControllerType = ""; } /** * Retrieves the target position for the motor. * * @return the target position */ ...
magicoder
java
You are tasked with implementing a function that processes a given TypeScript interface and extracts all the properties defined within it. The function should return an array containing the names of all the properties found in the interface. Write a function `extractInterfaceProperties` that takes a string representin...
```typescript function extractInterfaceProperties(interfaceString: string): string[] { const propertyRegex = /(\w+):/g; const properties: string[] = []; let match; while ((match = propertyRegex.exec(interfaceString)) !== null) { properties.push(match[1]); } return properties; } // Test the function wit...
magicoder
typescript
You are tasked with creating a Rust macro that generates code based on the provided input. The macro should take a list of operating systems and their corresponding pollers, and generate type aliases based on the target operating system. The macro should handle the case when the target operating system is "macos" diffe...
```rust macro_rules! attr_group { ( #![cfg(target_os = "macos")] $($rest:tt)* ) => { $($rest)* }; ( #![cfg(target_os = $os:literal)] $($rest:tt)* ) => { $($rest)* }; } ``` The provided solution demonstrates a macro implementation that handles the d...
magicoder
rust
You are tasked with implementing a network graph data structure to represent user authentication activities within a computer network. The network consists of nodes representing users and computers, and edges representing authentication activities. The provided code snippet demonstrates the addition of nodes and edges ...
```python class NetworkGraph: def __init__(self): self.nodes = {} self.edges = {} def add_node(self, node, properties): self.nodes[node] = properties def add_edge(self, source, target, properties): if (source, target) not in self.edges: self.edges[(source, targe...
magicoder
python
You are tasked with implementing a caching mechanism for thumbnail images in a file management system. The system has a method `cacheReceiveThumb` that takes in a `BaseFileInfo` object and an `InputStream` containing the thumbnail image data. The method is responsible for caching the thumbnail image and ensuring that d...
```java import java.util.HashMap; import java.util.Map; public class ThumbnailCache { private static Map<String, byte[]> cache = new HashMap<>(); /** * Caches the received thumbnail image. * @param fileInfo the information about the file * @param inputStream the input stream containing the thum...
magicoder
java
You are tasked with creating a simple HTTP server using Swift's NIO (Network I/O) framework. Your server should be able to handle incoming HTTP requests and respond with a predefined message. You will need to set up the server, define the request handling logic, and configure it to listen on a specific port. Your task...
```swift import NIO import NIOHTTP1 class HTTPRequestHandler: ChannelInboundHandler { typealias InboundIn = HTTPServerRequestPart typealias OutboundOut = HTTPServerResponsePart func channelRead(context: ChannelHandlerContext, data: NIOAny) { let reqPart = self.unwrapInboundIn(data) switch...
magicoder
swift
You are tasked with creating a Python package that can sign and verify Docker images. The package should include a function to retrieve the version of the package. Your task is to implement the `docker_sign_verify` package with the required functionality. Your task is to create a Python package `docker_sign_verify` wi...
```python # docker_sign_verify/__init__.py import subprocess import os __version__ = "1.0.0" def get_version(): return __version__ def sign_image(image_path, signature_path, private_key): try: subprocess.run(["docker", "trust", "sign", image_path, "--key", private_key, "--output", signature_path], c...
magicoder
python
You are tasked with implementing a custom macro in Rust that generates a nested structure of code based on the input provided. Your macro should take a single input token and generate a specific pattern of nested code based on that input. Your task is to create a macro called `nested_macro` that takes a single input t...
```rust macro_rules! nested_macro { ($token:tt) => { fn main() { { println!("Hello, World!"); } } }; } fn main() { nested_macro!($); } ``` In the solution, the `nested_macro` macro is defined using the `macro_rules!` syntax. It takes a single input to...
magicoder
rust
You are given a grid of pixels represented as a 2D array. Each pixel is initially set to either 0 or 1. The grid can be manipulated by a series of commands to rotate specific columns by a given number of steps. The rotation of a column involves shifting the elements in that column downwards by the specified number of s...
```python from typing import List def apply_rotations(grid: List[List[int]], commands: List[str]) -> List[List[int]]: for command in commands: parts = command.split() col_index = int(parts[2].split('=')[1]) steps = int(parts[-1]) col = [grid[i][col_index] for i in range(len(grid))] ...
magicoder
python
You are tasked with creating a Python class for a neural network model. The class should include a method for training the model using mini-batch gradient descent. The provided code snippet is a part of the training method within the class. Your task is to complete the implementation of the training method by adding th...
```python # Assuming the class name is NeuralNetwork and the training method is train_model class NeuralNetwork: def train_model(self, database, total_batch, epoch): avg_cost = 0 for i in range(total_batch): batch_x, batch_y = self.get_next_batch(database, i) # Run optimizat...
magicoder
python
You are given a code snippet that initializes an array of strings representing the days of the week and declares some variables. Your task is to write a program that takes input for a number of test cases, and for each test case, it reads two dates in the format "yyyy-mm-dd" and calculates the number of days between th...
```cpp #include <iostream> #include <string> using namespace std; const string days[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; int dayOfWeek(int y, int m, int d) { if (m < 3) { m += 12; y--; } int c = y / 100; y %= 100; int f = d + ((13 * (m...
magicoder
cpp
You are tasked with implementing a function to save an image represented as a NumPy array to a file. The function should take the image array, file name, and an optional output directory as input, and save the image to the specified location. If the output directory does not exist, it should be created. The image array...
```python import os import numpy as np from PIL import Image def save_img(img_np, file_name, out_dir='./'): if not os.path.exists(out_dir): os.makedirs(out_dir) if len(img_np.shape) == 3: # Color image image = Image.fromarray(img_np.transpose(1, 2, 0).astype('uint8')) else: # Graysca...
magicoder
python
You are tasked with implementing a Python class that simulates a simple bank account. The class should have methods to deposit funds, withdraw funds, and check the current balance. Additionally, the class should keep track of the total number of transactions (deposits and withdrawals) made on the account. Your task is...
```python # Test the BankAccount class account = BankAccount(1000) # Initialize account with $1000 print(account.get_balance()) # Output: 1000 print(account.get_total_transactions()) # Output: 0 account.deposit(500) # Deposit $500 print(account.get_balance()) # Output: 1500 print(account.get_total_transactions())...
magicoder
python
You are tasked with implementing a Python class for a NoEnvInputTranslationVariationalAutoEncoder. The class inherits from a superclass and has specific parameters for its initialization. Your task is to complete the implementation of the `NoEnvInputTranslationVariationalAutoEncoder` class by defining its `__init__` m...
```python class NoEnvInputTranslationVariationalAutoEncoder(SuperClass): def __init__(self, enc_layers, dec_layers, softmax=False, temperature=1.0): super(NoEnvInputTranslationVariationalAutoEncoder, self).__init__(enc_layers, dec_layers) self.softmax = softmax self.temperature = temperature...
magicoder
python
You are tasked with implementing a function that processes a given JavaScript code snippet to identify and extract all the unique CSS styles applied to a specific HTML element. The function should take the JavaScript code snippet as input and return an array of unique CSS styles found within the snippet. The JavaScrip...
```javascript function extractUniqueCSSStyles(codeSnippet) { const regex = /style=\{({[^{}]*})\}/g; const matches = codeSnippet.match(regex); const styles = []; if (matches) { matches.forEach(match => { const styleObj = eval(`(${match})`); for (const key in styleObj) { const styleString...
magicoder
javascript
You are tasked with implementing a genetic algorithm for feature selection in a machine learning context. The genetic algorithm is used to evolve a population of feature subsets to maximize the accuracy of a machine learning model. The algorithm uses a fitness function to evaluate the performance of each feature subset...
To solve this problem, you can use a genetic algorithm library such as DEAP (Distributed Evolutionary Algorithms in Python) to implement the genetic algorithm for feature selection. Below is a Python solution using DEAP to perform feature selection with the given parameters: ```python import random from deap import ba...
magicoder
python
You are tasked with implementing a Python function that processes a given string to extract specific information. The function should extract and return the Python class name and the first character of the string. The input string will be in the format of a Python function definition, and the output should be the extra...
```python import re def extract_info(function_str): # Extract class name class_name_match = re.search(r'def\s+([^\s(]+)\(', function_str) class_name = class_name_match.group(1) if class_name_match else None # Extract first character of docstring docstring_match = re.search(r'"""(.).*"""', function...
magicoder
python
You are tasked with implementing a custom thread management system in Swift. Your goal is to create a class called `CustomThread` that extends the functionality of the standard `Thread` class. The `CustomThread` class should have the following features: 1. A property called `isCustom` that returns true if the thread is...
The `CustomThread` class extends the `Thread` class and adds the required properties and methods. The `isCustom` property returns true, indicating that the thread is a custom thread. The `executeCustomTask` method takes a closure as a parameter and executes it on the custom thread using the `perform` method. Inside the...
magicoder
python
You are tasked with creating a Python function to parse and extract information about the active scene in Autodesk Maya. The function should retrieve specific attributes related to the scene and return them in a dictionary format. You are provided with a code snippet that demonstrates the expected attributes to be cap...
```python import maya.cmds as cmds def parse_active_scene(): parsed = { "start_frame": cmds.playbackOptions(minTime=True, query=True), "end_frame": cmds.playbackOptions(maxTime=True, query=True), "width": cmds.getAttr("defaultResolution.width"), "height": cmds.getAttr("defaultResolu...
magicoder
python
You are tasked with creating a Python class that generates an animation of a pigeon's flight using the `matplotlib.animation` library. The pigeon's body parts are represented as nodes, and the connections between them as edges. The animation will show the movement of the pigeon's body parts over a specified range of fr...
```python import matplotlib.pyplot as plt import matplotlib.animation as animation class PigeonAnimatorFactory: def __init__(self, connections): self.connections = connections def animate(self, frame): # Define the logic to update the positions of the pigeon's body parts for each frame ...
magicoder
python
You are tasked with implementing a time difference calculation function in a messaging application. The application uses PHP and HTML to display messages with their creation timestamps. The code snippet provided is a part of the HTML template used to display the creation timestamp of a message. The PHP code `<?=$Messag...
```php class TimeLibrary { public function getTimeDifferenceDateAndNowString($creationDate) { $currentTime = time(); $messageTime = strtotime($creationDate); $timeDifference = $currentTime - $messageTime; if ($timeDifference < 60) { return "just now"; } elseif ($...
magicoder
php
You are tasked with creating a Rust function that processes a given version string and returns a formatted string with an icon, the version number, and a specified color. The function should take a string representing the Rust compiler version as input and return the formatted string. The icon should be "🦀", and the c...
```rust struct ModuleInfo { icon: String, text: String, color: String, } impl ModuleInfo { fn of() -> ModuleInfo { ModuleInfo { icon: String::new(), text: String::new(), color: String::new(), } } fn icon(mut self, icon: &str) -> ModuleInfo { ...
magicoder
rust
You are tasked with implementing a simplified task management system for a software application. The system consists of a TaskManager class with the following methods: 1. `publish_abort(log_key)`: This method publishes an abort command for the task identified by the given log_key. 2. `wait_for_tasks(log_key)`: This m...
```python class TaskManager: def __init__(self): self.log_names = [] # Initialize an empty list to store log names def publish_abort(self, log_key): # Publish an abort command for the task identified by the given log_key # Implementation details not provided, assume functionality to pu...
magicoder
python
You are tasked with implementing a custom logging system in C#. The system should support logging messages at different log levels and provide the flexibility to log messages either directly as strings or through function delegates. Your task is to create a class `CustomLogger` that adheres to the following requiremen...
```csharp using System; public enum MvxLogLevel { Debug, Info, Warn, Error, Fatal } public interface IMvxLog { void Log(MvxLogLevel logLevel, string message, Exception exception = null, params object[] formatParams); } public class CustomLogger : IMvxLog { private void GuardAgainstNullLog...
magicoder
csharp
You are tasked with creating a Rust command-line application for managing configuration settings. The application should support four subcommands: `ConfigPath`, `ConfigRemove`, `ConfigSet`, and `ConfigSetInto`. Each subcommand corresponds to a different operation on the configuration settings. Your task is to implemen...
```rust use clap::{App, Arg, SubCommand}; fn main() { let matches = App::new("config-manager") .version("1.0") .author("Your Name") .about("Manage configuration settings") .subcommand( SubCommand::with_name("ConfigPath") .about("Display the path of the co...
magicoder
rust
You are given a string containing a mix of uppercase and lowercase letters. Your task is to write a function that returns a new string where the uppercase letters are converted to lowercase and the lowercase letters are converted to uppercase. Any characters that are not letters should remain unchanged. Write a functi...
```python def swapCase(s): swapped = "" for char in s: if char.isalpha(): if char.islower(): swapped += char.upper() else: swapped += char.lower() else: swapped += char return swapped # Test cases print(swapCase("Hello Worl...
magicoder
python
You are tasked with implementing a function that sorts a list of results based on a specific criterion. The results are represented as a list of tuples, where each tuple contains information about a result. Your task is to sort the results based on the third element of each tuple in descending order. Write a function ...
```python from typing import List, Tuple, Any def sort_results(results: List[Tuple[Any, Any, Any]]) -> List[Tuple[Any, Any, Any]]: return sorted(results, key=lambda r: -r[2]) ``` The `sort_results` function takes a list of tuples `results` as input and uses the `sorted` function to sort the results based on the t...
magicoder
python
You are tasked with designing a system for managing different flows within a mobile application. The system will involve creating and managing instances of various flow classes, each responsible for a specific aspect of the application's functionality. You are provided with a code snippet that initializes a `UITabBarC...
```swift // Define the BookingService class class BookingService { // Implementation of the BookingService class } // Define the AuthService class class AuthService { // Implementation of the AuthService class } // Define the MyStaysFlow class class MyStaysFlow { let bookingService: BookingService ...
magicoder
swift
You are tasked with implementing a message processor for a network communication system. The message processor is responsible for processing different types of messages and may support acknowledgment functionality. Your task is to implement the initialization process for the message processor based on the provided code...
```java // Load message types and set acknowledgment functionality during message processor initialization public void initializeMessageProcessor() throws InitializationException { try { // Load message types processed by this message processor this.messageTypes = properties.getEnumListProperty(PROP...
magicoder
java
You are tasked with creating a word guessing game in Python. The game will randomly select a word from a predefined dictionary and allow the player to guess letters until they either correctly guess the word or run out of attempts. Your task is to implement the `WordGuessGame` class with the following specifications: ...
```python import random class WordGuessGame: def __init__(self, dictionary): self.secret_word = random.choice(dictionary) self.guesses = set() def guess(self, letter): self.guesses.add(letter) def display_word(self): displayed_word = '' for char in self.secret_word...
magicoder
python
You are tasked with implementing a message handling system for a version protocol. The system should be able to process different versions of messages and handle them according to specific rules. Each message has a version number and a payload. Your task is to implement a function that processes the messages according ...
```python class Message: def __init__(self, version, payload): self.version = version self.payload = payload def print_responses(version_protocol): """Print version response handling behavior.""" messages = [ Message('v0', 1), Message('v1', 2), Message('v2', 3), ...
magicoder
python
You are tasked with implementing a function to determine the winning hand in a Chinese card game called "Hupai32". In this game, players are dealt a hand of cards, and the goal is to identify if the hand is a winning combination according to the game's rules. The game involves a set of cards and specific combinations t...
```python def hupai32_deal(self): hupaidevide_unranked = [] # 胡牌分割,没有进行排序之前的部分 hupaidevide = [] # 胡牌处理过程的中间变量 def hupai(tehai, sorted_): # Check if the hand is already sorted, if not, sort the hand if not sorted_: tehai.sort() # Implement the rules ...
magicoder
python
You are tasked with implementing a dependency injection container that supports resolving service registrations based on resolution requests. The container should provide a method `GetRegistration` that takes a `ResolutionRequest` object as input and returns the corresponding `IServiceRegistration` object. The `Resolu...
```csharp public class DependencyInjectionContainer { private List<IServiceRegistration> registrations; public DependencyInjectionContainer() { registrations = new List<IServiceRegistration>(); } public void RegisterService(IServiceRegistration registration) { registrations.Add...
magicoder
csharp
You are tasked with creating a Rust library for generating secure and memorable passwords inspired by the xkcd comic #936. The library should allow users to configure the number of words in the password, the minimum length of each word, and whether to include special characters. Your task is to implement the `Configura...
```rust mod xkcd_pass { pub struct Configuration { num_words: i32, min_word_length: i32, include_special_chars: bool, } impl Configuration { pub fn new(num_words: i32, min_word_length: i32, include_special_chars: bool) -> Configuration { Configuration { ...
magicoder
rust
You are tasked with creating a program that retrieves weather information from an external API and processes the data to display specific details. The `get_weather()` function is provided to retrieve the weather data, but it is not fully implemented. Your task is to complete the `get_weather()` function and create addi...
```python import requests def get_weather(location): api_key = "YOUR_API_KEY" # Replace with your actual API key url = f"http://api.openweathermap.org/data/2.5/weather?q={location}&appid={api_key}&units=metric" response = requests.get(url) data = response.json() weather_info = { "temp...
magicoder
python
You are tasked with implementing a Redux reducer function in TypeScript for managing the authentication state of a web application. The provided code snippet outlines the initial state and the action types related to authentication. Your task is to complete the reducer function that handles these actions and updates t...
The provided solution completes the TypeScript reducer function for managing the authentication state in a Redux store. The reducer function handles different action types related to authentication and updates the state accordingly. The `authReducer` function takes the current state and an action as input and returns ...
magicoder
typescript
You are tasked with creating a program that utilizes the Sentence Transformers library to perform semantic similarity analysis on a set of sentences. The Sentence Transformers library provides pre-trained models to convert sentences into numerical vectors, allowing for comparison of semantic similarity between sentence...
```python from sentence_transformers import SentenceTransformer import numpy as np def calculate_semantic_similarity(sentences): model = SentenceTransformer('your_model_name_or_path') # Replace 'your_model_name_or_path' with the desired model name or path # Obtain sentence embeddings sentence_embeddings ...
magicoder
python
You are tasked with creating a custom suggestion provider for a development tool. The tool allows users to specify a branch name for a version control system, and the suggestion provider should offer a list of valid branch names based on certain criteria. Your goal is to implement the suggestion provider class to gener...
```csharp public class BranchNameSuggestionProvider : ISuggestionProvider { public async Task<IEnumerable<string>> GetSuggestions() { // Retrieve the list of branches from the version control system (e.g., Git, SVN, etc.) IEnumerable<string> allBranches = await VersionControlSystem.GetBranchesAs...
magicoder
csharp
You are tasked with creating a script to automate the process of loading user data into a web application using the `curl` command. The script should take user input for `username`, `password`, and `userid`, and then send a POST request to the specified URL with the user data in JSON format. Your task is to write a Ba...
```bash #!/bin/bash # Prompt user for input read -p "Enter username: " username read -s -p "Enter password: " password read -p "Enter userid: " userid # Validate user input if [[ -z $username || -z $password || -z $userid ]]; then echo "Error: Username, password, and userid cannot be empty." >&2 exit 1 fi # Cons...
magicoder
shell
You are tasked with implementing a function that processes a list of items and creates a list of view models for each item. The provided code snippet is a part of a Swift application and defines a `ListingViewModel` struct with a method `listOfItemVM()` that needs to be completed. The `ListingViewModel` struct contains...
```swift import Foundation // Assuming the structure of CatalogueData and ListingItemViewModel struct CatalogueData { // Define the structure of CatalogueData } struct ListingItemViewModel { // Define the structure of ListingItemViewModel } struct ListingViewModel { let data: CatalogueData func ...
magicoder
swift
You are tasked with implementing a function that reads a requirements file and returns a dictionary containing the dependencies and their versions. The requirements file follows a specific format where each line contains a package name and its version, separated by an equals sign. For example, the file may look like th...
```python from typing import Dict def _read_requirements_file(file_path: str) -> Dict[str, str]: dependencies = {} try: with open(file_path, 'r') as file: for line in file: line = line.strip() if '==' in line: package, version = line.split...
magicoder
python
You are tasked with implementing a generic method for converting a Data Transfer Object (DTO) to a Plain Old Java Object (POJO). The provided code snippet is a part of an abstract class `BaseDTO` that contains a method `toEntity` for this purpose. Your task is to complete the implementation of the `toEntity` method to ...
```java import org.modelmapper.ModelMapper; @Data public abstract class BaseDTO { private static final ModelMapper modelMapper = new ModelMapper(); /** * DTO转PO * @param entityClass PO对象的字节码 * @param <T> PO对象的类型 * @return PO对象 */ public <T> T toEntity(Class<T> entityClass) { ...
magicoder
java
You are tasked with implementing a bandpass filter for a given signal. A bandpass filter allows signals within a certain frequency range to pass through while attenuating frequencies outside this range. The filter is defined by its lower and upper cutoff frequencies. You are given a signal in the form of a list of floa...
```python def apply_bandpass_filter(signal, lower_cutoff, upper_cutoff): """ Apply a bandpass filter to the given signal. Args: signal: A list of floating-point numbers representing the input signal. lower_cutoff: A floating-point number representing the lower cutoff frequency of the bandpass filte...
magicoder
python
You are given a dictionary containing keys representing different tasks and their corresponding boolean values indicating whether the task is completed or not. Your task is to write a function that returns the percentage of completed tasks in the dictionary. Write a function `calculate_completion_percentage(tasks: dic...
```python def calculate_completion_percentage(tasks: dict) -> float: completed_tasks = sum(1 for task_completed in tasks.values() if task_completed) total_tasks = len(tasks) completion_percentage = (completed_tasks / total_tasks) * 100 return round(completion_percentage, 2) ``` The `calculate_completio...
magicoder
python
You are tasked with implementing a text box generator in Rust. The text box generator takes an iterator of lines and an optional header, and produces an iterator of strings where each string represents a line of the text box. The text box should have a specific format and styling. The text box should be generated as f...
```rust use std::fmt::Display; fn text_box<T: Display, S: Display>( mut lines: impl Iterator<Item=T>, header: Option<S>, ) -> impl Iterator<Item=String> { let mut result = Vec::new(); let mut max_line_length = 0; // Calculate the maximum line length lines.clone().for_each(|line| { let ...
magicoder
rust
You are tasked with creating a Python function that processes and displays an image using the `guidata` library. The function should take an image file path as input and display the image in a GUI window with a specified title. Write a function `display_image` that takes two parameters: - `image_path` (string): The fi...
```python import guidata from guidata import qapplication from guidata.dataset.datatypes import Image def display_image(image_path, title): qapp = qapplication() # Create a QApplication instance image = Image(image_path) # Load the image from the given path image_widget = image.edit_traits() # Create a ...
magicoder
python
You are tasked with creating a command-line tool to automate the deployment process for a web application. The tool should execute a series of commands to ensure that the application is properly updated and optimized. Your task is to write a Python script that simulates the behavior of the deployment tool by executing ...
```python import subprocess def execute_command(command): try: subprocess.run(command, shell=True, check=True) except subprocess.CalledProcessError as e: print(f"Error executing command '{command}': {e}") exit(1) def main(): commands = [ "./artisan migrate --force", ...
magicoder
python
You are tasked with implementing a function to calculate the Stochastic Oscillator (STOCH) indicator for a given set of stock prices. The STOCH indicator is a momentum indicator that shows the location of the close relative to the high-low range over a set number of periods. It consists of two lines: %K and %D. The %K ...
```javascript function calculateSTOCH(prices, period) { const result = []; for (let i = 0; i < prices.length; i++) { if (i < period - 1) { result.push({ period: i + 1, %K: null, %D: null }); } else { const currentPrices = prices.slice(i - period + 1, i + 1); const lowestLow = Math.min(...c...
magicoder
javascript
You are tasked with implementing a RangeTimePlot class that can be used to visualize time-based data within a specified range. The class should support adding data points with associated timestamps and then be able to generate a time plot within a given time range. The RangeTimePlot class should have the following met...
```python class RangeTimePlot: def __init__(self): self.data_points = [] def add_data_point(self, timestamp, value): self.data_points.append((timestamp, value)) def generate_plot(self, start_time, end_time): time_plot = [f"{timestamp} | {value}" for timestamp, value in self.data_po...
magicoder
python
You are tasked with implementing a mock class for a USB library in Java. The USB library provides a `PollfdListener` interface, and you need to create a mock implementation for testing purposes. The `PollfdListener` interface is used for monitoring file descriptors for events. Your task is to complete the implementati...
```java package org.usb4java.mocks; import java.io.FileDescriptor; import org.usb4java.PollfdListener; /** * A mocked pollfd listener implementation for testing purposes. */ public class PollfdListenerMock implements PollfdListener { @Override public void pollfdEvent(FileDescriptor fd, short events) { ...
magicoder
java