query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with creating a script to automate the setup and configuration of a Python environment for a data science project. The script should perform the following tasks:
1. Activate the `conda` environment named `fis` using the `conda activate` command.
2. Install specific Jupyter Lab extensions using the `jupy... | ```bash
#!/bin/bash
# Activate the conda environment named 'fis'
source ~/miniconda3/etc/profile.d/conda.sh
conda activate fis
# Install specific Jupyter Lab extensions
jupyter labextension install @axlair/jupyterlab_vim @jupyterlab/toc @ryantam626/jupyterlab_code_formatter
# Build the Jupyter Lab application with a... | magicoder | shell |
You are tasked with creating a custom assertion function for testing user interface elements in an iOS app using XCTest framework. The function should wait for a specific condition to be met before proceeding with the test. Your task is to implement the `waitUntil` function and the `tap` function that utilizes it.
The... | ```swift
import XCTest
enum ElementStatus: String {
case exist = "exists == true"
case hittable = "isHittable == true"
// Add more conditions as needed
}
func waitUntil(element: XCUIElement, condition: ElementStatus, timeout: TimeInterval = TimeInterval(5)) {
let expectation = XCTNSPredicateExpectatio... | magicoder | swift |
You are tasked with implementing a function to invert the colors of a given RGB image. The function should take an input image, convert it to grayscale, and then invert the grayscale values to produce the final inverted image.
You are provided with a code snippet that partially implements the inversion process. Your t... | ```python
import skimage
from skimage.color import rgb2gray
from skimage import data
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams['font.size'] = 18
import numpy as np
def Invert(image):
grayim = rgb2gray(image)
a, b = np.shape(grayim)
inverted = np.empty([a, b])
for k in range(... | magicoder | python |
You are tasked with implementing a message queue system that supports reading and peeking at data in a message. The provided code snippet is a part of the message queue system and includes a method for peeking at data in a message. Your task is to complete the implementation of the `Output_Buffers::peek` method.
The `... | ```cpp
size_t Output_Buffers::peek(byte output[], size_t length, Pipe::message_id msg)
{
SecureQueue* q = get(msg); // Assume get(msg) returns the SecureQueue associated with the given message ID
if(q)
return q->read(output, length); // Read up to 'length' bytes of data from the queue and store it in the 'o... | magicoder | cpp |
You are tasked with creating a Python class that handles platform-specific commands and exceptions. Your class should be able to run commands locally and handle various platform-related issues. You need to implement the class with the given requirements and exceptions.
Create a Python class `PlatformHandler` with the ... | ```python
from .command_runner import LocalCommandRunner
from .platform_domain import CommandNotAvailableIssue, UnsupportedOperatingSystemIssue, UnsupportedPlatformException
from .platform_domain import OperatingSystem, PlatformIssue, PlatformScope
class PlatformHandler:
def __init__(self):
self.command_ru... | magicoder | python |
You are tasked with implementing a recursive function to draw a tree with two branches. The tree will be represented using ASCII characters, and the function should take the height of the tree as input. The tree will have a trunk represented by the character '|' and branches represented by the character '*'. The trunk ... | ```python
def draw_tree(height):
def draw_branches(level):
if level > 0:
draw_branches(level - 1)
print(' ' * (height - level) + '*' * (2 * level - 1))
draw_branches(height)
print(' ' * (height - 1) + '|')
# Example usage
draw_tree(3)
```
The `draw_tree` function first defi... | magicoder | python |
You are tasked with implementing a cache system for storing and retrieving bit sets associated with specific queries in a search engine application. The cache system is designed to store the bit sets generated from queries and retrieve them efficiently when the same query is encountered again. Your task is to write a m... | ```java
public class CacheSystem {
private Map<Query, BitSet> cacheMap;
public CacheSystem() {
this.cacheMap = new HashMap<>();
}
public BitSet getBitSet(Query query, LeafContext leafContext) {
BitSet cachedBitSet = cacheMap.get(query);
if (cachedBitSet == null) {
/... | magicoder | java |
You are tasked with implementing a method to update a Spectacle object in a Java web service. The method signature is as follows:
```java
public EspectaculoDetailDTO updateEspectaculo(Long id, EspectaculoDetailDTO espectaculo) throws BusinessLogicException, UnsupportedOperationException
```
The `updateEspectaculo` me... | ```java
public EspectaculoDetailDTO updateEspectaculo(Long id, EspectaculoDetailDTO espectaculo) throws BusinessLogicException, UnsupportedOperationException {
// Check if the Spectacle with the given id exists
EspectaculoDetailDTO existingEspectaculo = // Retrieve the existing Spectacle from the database using... | magicoder | java |
You are tasked with creating a Python script to convert SVG files to PNG format using the Inkscape command-line tool. The script should iterate through all the files in a specified input directory, identify the SVG files, and then convert each SVG file to a PNG file with a specified width and height using the Inkscape ... | ```python
import os
def convert_svg_to_png(inputDir: str, outputDir: str, width: int, height: int) -> None:
for item in os.listdir(inputDir):
split = item.split(".")
if split[-1] == "svg":
filename = '.'.join(split[:-1])
print("Converting " + filename)
os.system(... | magicoder | python |
You are tasked with implementing a function to calculate the power of a given number. The function should handle both positive and negative exponents. You are given a code snippet that partially implements the power calculation function. Your task is to complete the function and handle all edge cases.
You are provided... | ```cpp
double myPow(double x, int n) {
if (n == 0) {
return 1;
} else if (n == 1) {
return x;
} else if (n == -1) {
return 1 / x;
} else {
double temp = myPow(x, n / 2);
if (n % 2 == 0) {
return temp * temp;
} else {
return n < 0 ? ... | magicoder | cpp |
You are tasked with creating a shell script that processes command-line arguments and provides specific information about them. Your script should accept at least two parameters and then display the following information:
- The first parameter passed to the script.
- The second parameter passed to the script.
- All the... | ```bash
#!/bin/bash
echo "First Parameter : $1"
echo "Second Parameter : $2"
echo "Quoted Values: \"$@\""
echo "Quoted Values: $*"
echo "Total Number of Parameters : $#"
```
The provided solution is a shell script named `argument_processor.sh` that correctly processes the command-line arguments and displays the requi... | magicoder | shell |
You are tasked with creating a Python program that interacts with a natural language generation (NLG) server to generate dynamic and personalized text content. The NLG server is provided by the `jady` library, which offers a range of functionalities for generating natural language text based on input data.
Your progra... | ```python
import jady.nlg_server
import requests
def connect_to_nlg_server():
# Connect to the NLG server
nlg_server = jady.nlg_server.connect()
return nlg_server
def retrieve_input_data():
# Retrieve input data from a specified source (e.g., database or API)
response = requests.get('https://api.e... | magicoder | python |
You are tasked with creating a Python function that compares a list of actual results with a list of expected results and raises specific assertions for any discrepancies. The function should take in two parameters: `results` and `expected_results`. Each `results` list contains objects with attributes `type_name`, `tex... | ```python
class Result:
def __init__(self, type_name, text, resolution):
self.type_name = type_name
self.text = text
self.resolution = resolution
def compare_results(results, expected_results):
assert len(results) == len(expected_results), "Length of results and expected_results lists d... | magicoder | python |
You are tasked with implementing a function that handles GraphQL types in Python. The function should be able to determine the nullable type of a given GraphQL type and handle cases where the type is not nullable.
Write a function `get_nullable_type` that takes a GraphQL type as input and returns its nullable counterp... | ```python
from graphql import GraphQLNonNull
def get_nullable_type(graphql_type):
if isinstance(graphql_type, GraphQLNonNull):
return graphql_type.of_type
else:
return graphql_type
```
The `get_nullable_type` function first checks if the input `graphql_type` is an instance of `GraphQLNonNull`.... | magicoder | python |
You are tasked with implementing a simple 3D rendering engine in Rust. The `Model` struct represents a 3D model, and the `shade_views` method is responsible for shading the views of the model. The method returns a boolean value indicating whether the shading operation was successful or not. Your task is to complete the... | ```rust
impl Model {
fn shade_views(&mut self) -> bool {
// Perform shading calculations for each view of the model
// ...
// If shading operation was successful, return true
true
}
}
```
In the solution, the `shade_views` method is completed by performing the necessary shading ... | magicoder | rust |
You are tasked with implementing a Discrete Gaussian Distribution Polynomial Sampler in Python. The Discrete Gaussian Distribution is a probability distribution over the integers, and the sampler should generate random samples from this distribution for polynomials over a given ring.
Your task is to complete the imple... | ```python
from sage.stats.distributions.discrete_gaussian_polynomial import DiscreteGaussianDistributionIntegerSampler
class DiscreteGaussianDistributionPolynomialSampler:
def __init__(self, P, n, sigma):
"""
Initialize the DiscreteGaussianDistributionPolynomialSampler.
INPUT:
- P:... | magicoder | python |
You are tasked with implementing a custom `Sentinel` class in Python that represents a special value used to indicate the absence of a "real" value. The `Sentinel` class should be designed to behave similarly to the `_NONE` class in the provided code snippet.
Your task is to create a `Sentinel` class that, when used a... | ```python
class SentinelMeta(type):
_instances = {}
def __call__(cls, name, *args, **kwargs):
if name not in cls._instances:
cls._instances[name] = super().__call__(name, *args, **kwargs)
return cls._instances[name]
def __repr__(cls):
return f'<{cls.__name__}>'
class ... | magicoder | python |
You are tasked with creating a program to analyze salary data for employees in different departments of a company. The data is represented as a list of tuples, where each tuple contains the employee's name, department, current salary, and previous salary. Your task is to write a function that calculates the average sal... | ```python
def highest_avg_salary_increase(data):
department_salary_increase = {}
department_count = {}
for _, department, current_salary, previous_salary in data:
increase = current_salary - previous_salary
if department in department_salary_increase:
department_salary_incre... | magicoder | python |
You are tasked with implementing a function to calculate the indices of vertices and faces for a 3D box mesh. The given code snippet provides some context and partial implementation for this task. The box is divided into segments along its length, width, and height, and the function needs to calculate the indices of ve... | ```cpp
void CalculateIndices(int WP, int LP, int HP, int WidthSegments, int LengthSegments, int HeightSegments) {
int VertexIndex1, VertexIndex2, IndexIndex1, IndexIndex2;
// Calculate the indices of vertices for the left and right faces of the box
VertexIndex1 = 2 * (WP * LP + HP * LP);
VertexIndex2 =... | magicoder | cpp |
You are tasked with creating a custom dependency injection framework for a Java application. The framework should allow for the binding of interfaces to their respective implementations. To achieve this, you need to implement a simplified version of the dependency injection framework using Java.
Your task is to create... | ```java
import java.util.HashMap;
import java.util.Map;
public class DependencyInjector {
private Map<Class<?>, Object> bindings = new HashMap<>();
public <T> void bind(Class<T> interfaceClass, T implementation) {
bindings.put(interfaceClass, implementation);
}
public <T> T get(Class<T> inter... | magicoder | java |
You are tasked with implementing a custom memory management system for a programming language that supports object-oriented features. The system should include a garbage collector to automatically deallocate memory for objects that are no longer in use. To achieve this, you need to implement a mark-and-sweep garbage co... | ```swift
class Object {
var marked: Bool = false
}
class GarbageCollector {
func mark(obj: Object) {
if obj.marked {
return
}
obj.marked = true
// Recursively mark reachable objects
// Assuming the existence of a method `getReferencedObjects` that returns an... | magicoder | swift |
You are tasked with implementing a binary data reader that can parse and interpret a specific file format. The file format consists of a sequence of records, each containing a fixed number of fields. Each field has a specific data type and length. Your task is to write a Python function that reads the binary data from ... | ```python
import struct
def read_binary_data(file_path):
records = []
with open(file_path, 'rb') as file:
record_size = 4 + 8 + 10 # Size of one record in bytes
while True:
record_data = file.read(record_size)
if not record_data:
break # End of file rea... | magicoder | python |
You are tasked with implementing a transactional operation within a Laravel application. The provided code snippet is a part of a method within a Laravel Eloquent model. The `create` method is called to persist data to the database within a transaction, and a pagination value is retrieved from the input data or set to ... | ```php
public function yourMethod($data)
{
return \DB::transaction(function () use ($data) {
parent::create($data);
$paginate = $data['paginate'] ?? BaseAppEnum::DEFAULT_PAGINATION;
// Additional code for handling the transaction and pagination value retrieval
// ...
retur... | magicoder | php |
You are tasked with implementing a Python decorator that measures the execution time of a function and prints the result. The decorator should take into account any preload options specified by the user and handle them appropriately.
Your task is to complete the implementation of the `handle_preload_options` decorator... | ```python
import time
def handle_preload_options(f):
"""Extract preload options and return a wrapped callable."""
def caller(ctx, *args, **kwargs):
app = ctx.obj.app
preload_options = [o.name for o in app.user_options.get('preload', [])]
if preload_options:
user_options = ... | magicoder | python |
You are tasked with implementing a simplified version of a JavaScript Extension (JSX) object for handling attributes in an XML Forms Architecture (XFA) environment. The provided code snippet is a part of the CJX_Area class, which is responsible for managing the attributes of an area in an XFA form.
The `CJX_Area` clas... | ```javascript
// Define a JavaScript object named Area
const Area = {
// Implement the x method to handle attribute manipulation
x: function(pValue, bSetting, eAttribute) {
if (bSetting) {
// Set the value of the specified attribute to the value represented by pValue
// Implement logic to set the at... | magicoder | javascript |
You are tasked with implementing a custom weight decay optimizer for a neural network training process. The optimizer is based on the Adam optimizer with the addition of a weight decay term. The provided code snippet is a part of the optimizer's update step, where the weight decay is applied to the parameters of the ne... | ```python
# Update step for the custom weight decay optimizer
self.updates.append(K.update(m, m_t)) # Update first moment estimate
self.updates.append(K.update(v, v_t)) # Update second moment estimate
# Apply constraints to the updated parameter, if specified
if getattr(p, 'constraint', None) is not None:
new_p ... | magicoder | python |
You are tasked with creating a web application for a car rental company. The application should allow users to view available cars, make reservations, and manage their reservations. As part of this project, you need to implement a feature that allows users to update their reservation details, including the pickup and r... | ```php
public function updateReservation(Request $request, $id)
{
$reservation = Reservation::find($id);
$validatedData = $request->validate([
'pickup_date' => 'required|date',
'return_date' => 'required|date|after:pickup_date',
]);
$reservation->pickup_date = $validatedData['pickup_da... | magicoder | php |
You are tasked with creating a task management system for a game. Each task has specific attributes and requirements. Your goal is to implement a function that calculates the total time required to complete a task at a given level, taking into account the time cost function and whether banking the resource is allowed.
... | ```typescript
function calculateTotalTime(task: Task, level: number): number {
let totalResourcesNeeded = task.resourcesNeeded.reduce((total, resource) => total + resource.amount, 0);
let totalResourcesGained = task.resourcesGained.reduce((total, resource) => total + resource.amount, 0);
let resourcesToConsider ... | magicoder | typescript |
You are tasked with creating a Python function that parses a user-agent string to extract specific information about the client's browser and operating system. The user-agent string contains details about the client's browser, rendering engine, and operating system. Your function should extract and return the browser n... | ```python
import re
def parse_user_agent(user_agent: str) -> dict:
browser_info = re.search(r'(\w+)\/([\d.]+)', user_agent)
os_info = re.search(r'\((.*?)\)', user_agent)
browser = browser_info.group(1)
version = browser_info.group(2)
os = os_info.group(1).split(';')[0]
return {
"brows... | magicoder | python |
You are working on a software project that involves parsing and extracting information from a specific type of source code written in a language that includes Cyrillic characters. The code snippet provided is a part of a Python class method that is responsible for processing and formatting this source code. The method ... | ```python
import re
def extract_functions(source_code):
functions = re.findall(r'((\&НА\w+\s*\n|\n)(?=ФУНКЦИЯ|ПРОЦЕДУРА)(ФУНКЦИЯ|ПРОЦЕДУРА)\s+([\w\dА-Яа-я\_]+)(\(.*\));*(ЭКСПОРТ)*([^ꡏ]*?)(?=КОНЕЦФУНКЦИИ|КОНЕЦПРОЦЕДУРЫ)(КОНЕЦФУНКЦИИ|КОНЕЦПРОЦЕДУРЫ))', source_code)
extracted_functions = []
for func in functi... | magicoder | python |
You are tasked with creating a script to manage software packages in a Linux distribution using the KISS package manager. The KISS package manager is a simple package manager that uses a file-based approach to package management. The script should iterate through a list of package categories and install the packages wi... | ```bash
#!/bin/bash
# Define the list of package categories
categories=("core" "extra" "base" "wayland" "game")
# Iterate through each category and install the packages
for category in "${categories[@]}"; do
# Assuming the package names are stored in separate files for each category
while IFS= read -r package... | magicoder | shell |
You are tasked with implementing a function to calculate the Cramér-Rao lower bound (CRB) for a single particle state in a simulation. The CRB is a measure of the precision of parameter estimation in statistical models. The provided code snippet initializes a single particle state, updates it with different radii, and ... | ```python
import numpy as np
def calculate_crb(imsize, rads, radius, sigma):
s = init.create_single_particle_state(imsize=imsize, radius=radius, sigma=sigma)
blocks = s.blocks_particle(0)
crbs = []
for rad in rads:
print("Radius", rad)
s.update(blocks[-1], np.array([rad]))
crb... | magicoder | python |
You are tasked with creating a program that simulates a version control system for a software project. The program should support the following operations:
1. `run_test -i`: Run the test suite in isolation mode.
2. `run_test -c`: Run the test suite in coverage mode.
3. `run_test -a committer`: Run the test suite in ac... | ```python
class VersionControl:
def run_test(self, mode: str, committer: str = None) -> str:
if mode == "-i":
return "Running test suite in isolation mode"
elif mode == "-c":
return "Running test suite in coverage mode"
elif mode == "-a" and committer:
ret... | magicoder | python |
You are tasked with creating a RESTful API for managing a list of products using Django and Django REST framework. Your task is to implement two views for the product model: one for listing and creating products, and another for retrieving, updating, and deleting individual products.
You are provided with the followin... | ```python
# models.py
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
price = models.DecimalField(max_digits=10, decimal_places=2)
created_at = models.DateTimeField(auto_now_add=True)
# serializers.py
from rest_framewor... | magicoder | python |
You are tasked with implementing a function that filters a collection of art pieces based on various criteria. The function should take in a list of art pieces, each represented by a structure containing the following fields:
- `categoryId` (integer): The category ID of the art piece.
- `from` (string): The starting d... | ```java
import java.util.ArrayList;
import java.util.List;
class ArtPiece {
int categoryId;
String from;
String to;
String title;
int artistId;
int styleId;
public ArtPiece(int categoryId, String from, String to, String title, int artistId, int styleId) {
this.categoryId = category... | magicoder | java |
You are tasked with implementing a simple cache system using Python. The cache system should support the following operations: get(key), set(key, value), and delete(key). Additionally, the cache should have a maximum capacity, and when the capacity is reached, the least recently used item should be evicted to make spac... | ```python
from .cache import CacheCommand
class Cache:
def __init__(self, capacity):
self.capacity = capacity
self.cache_command = CacheCommand()
def get(self, key):
return self.cache_command.get(key)
def set(self, key, value):
if self.cache_command.get(key) is not... | magicoder | python |
You are tasked with implementing a method for creating an `ObjectSet` from a raw pointer in the context of the Fontconfig library. The `ObjectSet` represents a set of font objects, and the method `from_raw` is responsible for constructing this set from a raw pointer to a `FcObjectSet`. The method assumes ownership of t... | ```rust
use fontconfig_sys as sys;
use std::ptr;
pub struct Fontconfig;
pub struct ObjectSet {
// Define the fields and methods for the ObjectSet struct
}
impl Fontconfig {
/// The `FcObjectSet` must not be null. This method assumes ownership of the `FcObjectSet`.
pub fn from_raw(_: &Fontconfig, raw_set:... | magicoder | rust |
You are working on a natural language processing (NLP) project and need to manage various pre-trained models and resources stored in different locations. The provided code snippet shows a configuration file with paths to different resources stored in Amazon S3 buckets. Your task is to write a Python function that extra... | ```python
def parse_model_config(config):
word_embedding = {}
contextual_embedding = {}
generative_model = {}
for model, path in config.items():
if isinstance(path, str):
if model == "glove":
word_embedding[model] = path
else:
generative_m... | magicoder | python |
You are working on a software project that involves generating reports using JasperReports, a popular Java reporting library. As part of this project, you need to implement a feature that allows users to save reports in multiple sheets within an Excel file. You have come across a code snippet from the JasperReports lib... | The solution involves understanding the purpose of the `JRMultipleSheetsXlsSaveContributor` class and using it as a reference to implement the feature for saving reports in multiple sheets within an Excel file.
The `JRMultipleSheetsXlsSaveContributor` class is likely a contributor class that extends the functionality ... | magicoder | java |
You are tasked with creating a Python function that simulates a simple banking system. The function should allow users to deposit, withdraw, and check their balance. Additionally, the function should handle cases where the user tries to withdraw more money than their current balance allows.
Your task is to implement t... | ```python
class WithdrawalError(Exception):
pass
class BankAccount:
def __init__(self, initial_balance):
self.balance = initial_balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount > self.balance:
raise WithdrawalError("In... | magicoder | python |
You are tasked with creating a Python function that processes a list of pictures and returns a dictionary containing the count of pictures processed and the average size of the pictures. You should also write unit tests for this function using the `unittest` framework.
Create a Python function `process_pictures(pictur... | ```python
import os
import unittest
from typing import List, Dict, Union
def process_pictures(pictures: List[str]) -> Dict[str, Union[int, float]]:
if not pictures:
return {'count': 0, 'average_size': 0.0}
total_size = 0
for picture in pictures:
total_size += os.path.getsize(picture)
... | magicoder | python |
You are tasked with implementing a function that sends an SMS signature application using the provided code snippet as a reference. The function should construct a request payload based on the given parameters and make a POST request to a specific endpoint. Your task is to create the function that accomplishes this tas... | ```php
function sendSMSApplication($content, $contentType, $description = null, $countryType = null, $signatureFileBase64 = null, $signatureFileFormat = null) {
$params = ['content' => $content, 'contentType' => $contentType];
if ($description) $params['description'] = $description;
if ($countryType) $param... | magicoder | php |
You are given a list of integers representing the heights of a series of buildings. Each integer represents the height of a building at a specific position. Your task is to write a function `max_area` to find the maximum area that can be formed by selecting two buildings. The area is calculated by multiplying the minim... | ```python
def max_area(heights):
max_area = 0
left = 0
right = len(heights) - 1
while left < right:
width = right - left
h = min(heights[left], heights[right])
area = width * h
max_area = max(max_area, area)
if heights[left] < heights[right]:
... | magicoder | python |
You are tasked with creating a Java class that implements a specific data access pattern using the Spring Data JPA framework. Your goal is to define a custom repository interface that extends the JpaRepository interface and provides additional functionality for interacting with a database table.
Create a Java interfac... | ```java
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
public interface RsUserdynamiclikeDAO extends JpaRepository<RsUserdynamiclike, String> {
// Define a dynamic qu... | magicoder | java |
You are tasked with implementing a Python class that represents 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 i... | ```python
class BankAccount:
def __init__(self, initial_balance):
self.balance = initial_balance
self.transactions = 0
def deposit(self, amount):
self.balance += amount
self.transactions += 1
def withdraw(self, amount):
if self.balance >= amount:
self.ba... | magicoder | python |
You are tasked with creating a script to automate the retrieval of the IP address of a specific Kubernetes node and setting it as an environment variable. The Kubernetes cluster has a node named "test-gslb1-${NODE_ROLE}" where ${NODE_ROLE} is a placeholder for the role of the node. The IP address of this node needs to ... | ```bash
#!/bin/bash
# Set the value of NODE_ROLE
NODE_ROLE="example-role"
# Use kubectl to retrieve the IP address of the specified node and store it in HOST_ALIAS_IP2
export HOST_ALIAS_IP2=$(kubectl get nodes test-gslb1-${NODE_ROLE} -o custom-columns='IP:status.addresses[0].address' --no-headers)
# Verify the value... | magicoder | shell |
You are tasked with implementing a priority queue data structure using Python. A priority queue is a data structure that stores elements along with their associated priorities and allows for efficient retrieval of the element with the highest priority. In this problem, you will be implementing a priority queue using a ... | ```python
import heapq
import threading
class PriorityQueue:
def __init__(self):
self.data = []
self.lock = threading.Lock()
def insert(self, item, priority):
"""Inserts the given item with its associated priority into the priority queue."""
with self.lock:
heapq.he... | magicoder | python |
You are tasked with implementing a function to parse and analyze a Python script containing functions related to a job application interface. The script contains functions for opening a new tab in a web browser, resuming a job application, and creating a cover letter. Your task is to extract and display the names of th... | ```python
import re
def parse_script(script):
function_pattern = r'def\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\(\s*\):[^\"]*\"([^"]*)\"'
functions = re.findall(function_pattern, script)
return {func[0]: func[1].strip() for func in functions}
``` | magicoder | python |
You are working on a project that involves managing multiple packages, each containing various files and directories. Your task is to write a script that will remove specific files and directories from all the packages based on a given list of file and directory names.
You are given the following list of files and dir... | ```python
import os
def remove_files_and_directories(packages):
files_and_directories_to_remove = [
"tslint.json",
"yarn.lock",
"ember-cli-build.js",
".travis.yml",
"CODE_OF_CONDUCT.md",
"LICENSE",
"tmp",
"dist"
]
for package in packages:
... | magicoder | python |
You are given a snippet of code that contains an `else` statement. Your task is to create a program that simulates the behavior of this `else` statement in a specific context.
Write a Python function called `check_number` that takes an integer `num` as input. The function should return a string based on the following ... | ```python
def check_number(num):
if num > 0:
return "Positive"
elif num < 0:
return "Negative"
else:
return "Zero"
```
The `check_number` function first checks if the input `num` is greater than 0. If true, it returns "Positive". If not, it checks if `num` is less than 0. If true, i... | magicoder | python |
You are tasked with creating a web application for managing agricultural records. The application uses the Laravel framework, and you are working on the "FincaController" which is responsible for handling farm-related operations. The controller has two methods: "index" and "guardar".
The "index" method is used to disp... | ```php
public function guardar(Request $request)
{
// Retrieve the input data from the request
$data = $request->all();
// Validate the input data
$validatedData = $request->validate([
'field1' => 'required',
'field2' => 'numeric',
// Add more validation rules as per the fie... | magicoder | php |
You are given a code snippet for a function `smallestRepunitDivByK` that takes an integer `K` as input. The function is intended to find the length of the smallest positive integer `N` such that `N` is a multiple of `K`, and `N` consists only of the digit 1 repeated one or more times.
Your task is to complete the impl... | ```cpp
class Solution {
public:
set<int> ss;
int smallestRepunitDivByK(int K) {
if (K % 2 == 0 || K % 5 == 0) {
return -1; // If K is divisible by 2 or 5, it will never be possible to find a positive integer N consisting only of the digit 1 that is a multiple of K.
}
int re... | magicoder | cpp |
You are tasked with creating a Swift function that interacts with Core Data, a framework provided by Apple for managing the model layer of an application. Your function should retrieve a specific entity from the Core Data persistent store and return the results in a structured format.
Write a function `fetchEntity` th... | ```swift
func fetchEntity(entityName: String) -> [[String: Any]] {
let managedContext = persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
do {
let fetchedEntities = try managedContext.fetch(fetchRequest) as! [NSManagedObject]
var... | magicoder | swift |
You are tasked with implementing a function to decode a specific type of action from a JSON file in Swift. The action to be decoded is a navigation action called "pushView" used in a mobile application framework. The action contains a route with a URL that may include a placeholder for a variable. Your task is to write... | ```swift
import Foundation
struct Navigate: Codable {
var route: Route
}
struct Route: Codable {
var url: String
}
func decodePushViewAction(fromFile fileName: String) throws -> Navigate {
guard let fileURL = Bundle.main.url(forResource: fileName, withExtension: "json") else {
throw NSError(domai... | magicoder | swift |
You are tasked with implementing a Rust function that processes asynchronous operations and handles potential errors using the `expect` method. Your goal is to create a function that initializes a communication channel and returns a sender and receiver pair. The function should handle potential errors using the `expect... | ```rust
use std::sync::mpsc::{channel, Sender, Receiver};
use std::time::Duration;
use tokio::time;
// Define the configuration and keys types
struct Config;
struct Keys;
// Define the error type
struct Error;
// Define the init function
fn init(config: Config, keys: Keys, network_id: u32, shutdown: impl Future<Outp... | magicoder | rust |
You are tasked with implementing a class that interacts with a web API to retrieve user information and game data. The class has a method that is responsible for initializing the API connection, loading user information, and retrieving a list of all games associated with the user. The provided code snippet is a part of... | ```python
class WebAPIClient:
def __init__(self, api_key=None):
self.api_key = api_key
self.api_interface = None
self.limited = False
def initialize_api_connection(self):
if not self.api_key:
self.api_key = self.get_api_key()
if self.api_key:
... | magicoder | python |
You are tasked with implementing a function to scan a list of equities for potential diagonal butterfly spreads. A diagonal butterfly spread is an options trading strategy that involves buying and selling options at different strike prices and expiration dates. The goal is to identify equities that exhibit the potentia... | ```python
class OptionsScanner:
def __init__(self, equities):
self.equities = equities
def get_dgbs(self):
potential_dgbs = []
for equity in self.equities:
if equity.volatility > threshold:
potential_dgbs.append(equity)
return potential_dgbs
```
In t... | magicoder | python |
You are tasked with implementing a class that manages account information using the provided interface `IAccountContext`. The interface has three properties: `Id`, `HashedId`, and `PublicHashedId`. Your goal is to create a class `AccountManager` that implements the `IAccountContext` interface and provides functionality... | ```csharp
using System;
using System.Security.Cryptography;
using System.Text;
public interface IAccountContext
{
long Id { get; }
string HashedId { get; }
string PublicHashedId { get; }
}
public class AccountManager : IAccountContext
{
public long Id { get; }
public string HashedId { get; }
p... | magicoder | csharp |
You are tasked with creating a Python function that validates the methods of a class based on certain criteria. The function should take in a dictionary representing the methods of a class and a regular expression pattern, and it should perform the following tasks:
1. Check if the method names are valid by matching the... | ```python
import re
def validate_methods(methods: dict, pattern: str) -> bool:
class_method_re = re.compile(pattern)
is_need_reraise = False
for method_name, _ in methods.items():
if method_name in ["constructor", "destructor"]:
continue
try:
if not class_method_re.... | magicoder | python |
You are tasked with creating a Swift package manager tool that automates the process of adding dependencies to a Swift package. The tool should be able to parse a given configuration file and modify the package's dependencies based on the specified conditions.
The configuration file is in JSON format and contains the ... | ```swift
func updatePackageDependencies(config: [String: Any]) -> [String: Any] {
var updatedConfig = config
if let useSwiftCrypto = config["useSwiftCrypto"] as? Bool, useSwiftCrypto {
if var dependencies = updatedConfig["dependencies"] as? [[String: String]] {
dependencies.append(["url": "... | magicoder | swift |
You are tasked with creating a Vue plugin for text highlighting called "TextMarker". The plugin should be implemented as a Vue constructor and a plugin object. The "marker" variable is declared as the instance of the "TextMarker" type.
Your task is to implement the "TextMarker" plugin using Vue and TypeScript. The plu... | ```typescript
import Vue, { VueConstructor, PluginObject } from 'vue';
interface TextMarkerOptions {
element: string;
color: string;
}
class TextMarkerPlugin implements PluginObject<void> {
install(Vue: VueConstructor, options?: TextMarkerOptions): void {
Vue.prototype.$highlight = function (text: string) {... | magicoder | typescript |
You are tasked with implementing a custom PyTorch module for a sequence-to-sequence model. The module includes a forward method that takes source and answer embeddings as input and processes them using a bidirectional GRU (Gated Recurrent Unit) layer. The forward method also utilizes pack_padded_sequence and pad_packed... | ```python
import torch
import torch.nn as nn
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
class CustomSeq2SeqModule(nn.Module):
def __init__(self, gru_hidden_size, hidden_size):
super(CustomSeq2SeqModule, self).__init__()
self.bigru = nn.GRU(input_size=gru_hidden_size, h... | magicoder | python |
You are tasked with creating a Python program that utilizes the `pywatchman` library to monitor changes in a specified directory. Your program should be able to connect to the Watchman service, subscribe to changes in the directory, and then print out the details of any changes that occur.
Your program should perform ... | ```python
import pywatchman
# Connect to the Watchman service
client = pywatchman.client(timeout=2000)
# Specify the directory to monitor
watch_root = '/path/to/your/directory'
# Define the subscription criteria
subscription = {
'expression': ['allof', ['match', '*.txt']],
'fields': ['name', 'new', 'exists']... | magicoder | python |
You are tasked with implementing a JSON patch operation to remove a specific field from a JSON object. The patch operation is represented as a list of operations, and each operation specifies the type of operation (in this case, "remove") and the path to the field to be removed.
You are given a code snippet that demon... | ```java
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.fge.jsonpatch.JsonPatch;
import com.github.fge.jsonpatch.JsonPatchException;
import com.github.fge.jsonpatch.JsonPatchOperation;
import java.util.List;
import java.util.Map;
public class JsonP... | magicoder | java |
You are tasked with implementing a Python decorator that performs stack checking for a given function. The decorator should check if the stack is empty before calling the function and raise an exception if it is not. Your task is to complete the implementation of the `check_stack` decorator and apply it to the `Cleanup... | ```python
import inspect
class StackEmptyError(Exception):
pass
def check_stack(func):
def wrapper(*args, **kwargs):
if not inspect.currentframe().f_back:
raise StackEmptyError("Stack is empty, cannot execute function")
return func(*args, **kwargs)
return wrapper
@check_stack
... | magicoder | python |
You are working on a Python package for data analysis, and you need to implement a function that calculates the correlation coefficient between two sets of data. The `getters` module provides two functions: `get_dist_url` to retrieve the URL of the dataset and `scatter_values` to obtain the scatter plot values for the ... | ```python
import numpy as np
from .getters import get_dist_url, scatter_values
def calculate_correlation(dataset1, dataset2):
url1 = get_dist_url(dataset1)
url2 = get_dist_url(dataset2)
data1 = scatter_values(url1)
data2 = scatter_values(url2)
correlation_coefficient = np.corrcoef(data1, ... | magicoder | python |
You are tasked with implementing a Python class that manages the alignment tools for a graphical user interface (GUI) application. The class, `AlignDistributeToolBar`, is responsible for providing alignment functionalities for various GUI elements. The provided code snippet initializes the `AlignDistributeToolBar` clas... | ```python
class AlignDistributeToolBar:
def __init__(self, parent):
super(AlignDistributeToolBar, self).__init__(parent=parent)
self.setObjectName('Alignment Tools')
self.main_window = parent
def alignHorizontally(self, elements):
# Calculate the average y-coordinate of the elem... | magicoder | python |
You are tasked with creating a Swift function that processes a given file and returns the line and column numbers of a specific character within the file. The function should also check if the iOS version is available and handle any conditional compilation directives present in the file.
You are provided with a code s... | ```swift
func processFile(fileName: String, characterPosition: Int) -> (line: Int, column: Int, iOSAvailable: Bool, compilationDirective: String?) {
// Read the content of the file
guard let fileContent = try? String(contentsOfFile: fileName) else {
fatalError("Failed to read the file.")
}
... | magicoder | swift |
You are working on a graphics rendering engine and need to implement a method for transforming world positions to screen positions. The method should handle both orthographic and perspective projections. You are given a code snippet that contains the logic for this transformation, but it seems to have some issues. Your... | The code snippet provided contains some issues that need to be addressed to ensure the correct transformation from world positions to screen positions. Let's analyze and correct the code:
```csharp
{
var homoginizedViewPosition = worldPosition.Transform(this.ModelviewMatrix);
if (IsOrthographic)
{
... | magicoder | csharp |
You are tasked with creating a Java program that simulates a simple library management system. The system should allow users to add books, remove books, and display the list of available books. Each book in the library has a unique identifier, title, and author.
Your task is to implement the `Library` class with the f... | ```java
import java.util.HashMap;
import java.util.Map;
class Book {
private int id;
private String title;
private String author;
public Book(int id, String title, String author) {
this.id = id;
this.title = title;
this.author = author;
}
public int getId() {
r... | magicoder | java |
You are tasked with implementing a class for managing a gaming platform's user data. The class should provide methods for validating user input, checking if a user is registered, retrieving all user data, and fetching high scores within a specified time frame and category.
You are given the following method signatures... | ```php
class UserManagement
{
private $userData = [
['phone' => '1234567890', 'name' => 'User1', 'highscore' => 100, 'category' => 'A', 'registration' => true],
['phone' => '9876543210', 'name' => 'User2', 'highscore' => 150, 'category' => 'B', 'registration' => true],
['phone' => '555555555... | magicoder | php |
You are tasked with implementing a memory allocation tracking system similar to the one used in the code snippet provided. Your goal is to create a program that can track memory allocation and deallocation statistics for a custom memory management system.
Your program should provide the following functionalities:
1. I... | ```c
#include <stdio.h>
#include <stdlib.h>
typedef struct {
size_t total_allocated;
size_t total_freed;
size_t current_allocated;
size_t peak_memory;
} MemoryStats;
MemoryStats memory_stats = {0, 0, 0, 0};
void* my_malloc(size_t size) {
void* ptr = malloc(size);
if (ptr != NULL) {
me... | magicoder | c |
You are given an array of non-negative integers, where each element represents the maximum jump length from that position. Write a function `can_jump` to determine if you can reach the last index.
The function should take in a single parameter:
- `nums`: a list of non-negative integers representing the maximum jump le... | ```python
def can_jump(nums):
max_reachable = 0
for i in range(len(nums)):
if i > max_reachable:
return False
max_reachable = max(max_reachable, i + nums[i])
if max_reachable >= len(nums) - 1:
return True
return False
```
The `can_jump` function iterates thro... | magicoder | python |
You are tasked with implementing a message queue system using Java. The system should support subscribing to channels and receiving messages from those channels. You are provided with a partial code snippet for a `SubscribeManager` class, which extends an `AbstractSubscribeManager` class from the `com.pubnub.api` packa... | ```java
package com.pubnub.api;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class SubscribeManager extends AbstractSubscribeManager {
private Map<String, List<String>> subscribedChannels = new HashMap<>();
public void subscribe(String channel) {
... | magicoder | java |
You are tasked with implementing a temperature sensor query service using the DS18B20 temperature sensor. The provided code snippet is a simplified version of a RESTful API endpoint that queries the availability of DS18B20 temperature sensors.
Your task is to extend the functionality of the `DS18B20Query` class to inc... | ```python
class DS18B20Query (restful.Resource):
def __init__(self, *args, **kwargs):
self.sensor_service = kwargs['sensor_service']
def get(self):
available = lookup(self.sensor_service.get_config())
return success(available)
def get_temperature(self, sensor_address):
try:... | magicoder | python |
You are tasked with implementing a Python module that provides a custom context manager for handling file operations. The module should utilize the `elib` library and the `Context` class from the `_context` module. The custom context manager should ensure that a file is properly opened, its contents are read, and then ... | ```python
import elib
from ._context import Context
class FileHandler:
def __init__(self, filename):
self.filename = filename
self.content = None
def __enter__(self):
self.file = elib.open_file(self.filename, mode='r')
self.content = self.file.read()
return self
de... | magicoder | python |
You are tasked with implementing a file download manager that communicates with a remote server. The provided code snippet is a part of the client-side logic for initiating a file download. The snippet includes error handling and a message for starting the download process.
Your task is to complete the implementation ... | ```csharp
using System;
using System.IO;
using System.Net;
public class FileDownloadManager
{
public void DownloadFile(string remoteFilePath, string localDestinationPath)
{
try
{
// Establish a connection with the remote server
var request = (HttpWebRequest)WebRequest.Cr... | magicoder | csharp |
You are given a list of integers representing the scores of a game. The game has a rule that a player can only play if their score is greater than the average score of all players. Your task is to write a function that takes the list of scores and returns the number of players who can play the game.
Function Signature... | ```python
from typing import List
def count_eligible_players(scores: List[int]) -> int:
total_players = len(scores)
total_score = sum(scores)
average_score = total_score / total_players
eligible_players = sum(1 for score in scores if score > average_score)
return eligible_players
``` | magicoder | python |
You are given a Python function `product_sans_n(nums)` that takes a list of integers `nums` as input. The function is intended to return a new list where each element is the product of all the elements in the input list except for the element at that index. However, there are special cases to consider:
- If there are ... | ```python
from typing import List
def product_sans_n(nums: List[int]) -> List[int]:
if nums.count(0) >= 2:
return [0] * len(nums)
elif nums.count(0) == 1:
temp = [0] * len(nums)
temp[nums.index(0)] = product(nums)
return temp
res = product(nums)
return [res // i if i != ... | magicoder | python |
You are tasked with creating a Python class that simulates a simple library management system. The class should be able to add books to the library, lend books to borrowers, and display the current inventory of books. Additionally, the class should keep track of the borrowers who have borrowed books and the due dates f... | ```python
class Library:
def __init__(self, library_name):
self.library_name = library_name
self.inventory = {}
self.borrowers = {}
def add_book(self, book_title, book_author):
if (book_title, book_author) in self.inventory:
print(f"The book '{book_title}' by {book_a... | magicoder | python |
You are working on a data processing system that involves executing functions on a database node. The system uses a `db` object to interact with the database and a `df` object representing a data frame. The `run` function takes a database node `db_node` as input, retrieves an executable function from the database using... | ```python
def execute_with_db(db_node, df):
global db # Access the global db object
# Set db to a valid database interface (e.g., connecting to the database)
db = connect_to_database() # Replace with actual database connection logic
# Call the run function with the provided db_node and return the res... | magicoder | python |
You are tasked with creating a custom validation system for a form input using Python. The goal is to implement a `Validator` class that can be used to validate user input based on a given function and error message. The `create_validator` function is provided as a starting point, but you need to extend it to create a ... | ```python
from typing import Callable, Type, Text
from prompt_toolkit.validation import Validator, ValidationError
from prompt_toolkit.document import Document
class CustomValidator(Validator):
def __init__(self, function: Callable[[Text], bool], error_message: Text):
self.function = function
self.... | magicoder | python |
You are given a Python function that takes a list of tuples as input and calculates a specific value based on the elements of the tuples. Your task is to understand the given code snippet and implement a function that achieves the same result.
You need to implement a Python function called `calculate_value` that takes... | ```python
def calculate_value(input_list):
s = 0
for i in input_list:
s = s + (i[0] * i[1])
return s
t = []
x = (0, 0.2)
t.append(x)
t.append((137, 0.55))
t.append((170, 0.25)
result = calculate_value(t)
print(result) # Output: 94.45
```
The `calculate_value` function iterates through the input l... | magicoder | python |
You are tasked with implementing a Python class for managing plans in an invoicing system. The class should be able to create, update, and retrieve plan details from the invoicing system's API. Your task is to complete the implementation of the `Plan` class by adding the necessary methods to interact with the API and e... | ```python
import requests
class Plan:
def __init__(self, client, name):
self.client = client
self.name = name
def save(self):
# Implement the logic to save the plan details to the invoicing system's API
# Use requests library to make API requests
# Return True if the pl... | magicoder | python |
You are tasked with creating a Python function that interacts with an external API using the `opsramp` library. The `opsramp` library provides a set of functions to manage and monitor IT operations. Your function should authenticate with the API, retrieve a list of devices, and then return the count of devices that are... | ```python
from opsramp.api import ORapi
def count_devices_in_state(api_key, secret_key, operational_state):
# Authenticate with the OpsRamp API
or_api = ORapi(api_key, secret_key)
# Retrieve the list of devices
devices = or_api.get_devices()
# Count the devices in the specified operational state
... | magicoder | python |
You are tasked with implementing a function to process a 2D grid of points based on certain conditions. The grid is represented by its dimensions `size_x` and `size_y`, and the function is responsible for determining the properties of each point in the grid. Two helper functions, `check_point_asph` and `check_point_sph... | ```python
def process_grid(size_x, size_y, x_pos_asph, y_pos_asph, d_asph, diameter_asph, lam, lam_px, n_asph, x_pos_sph, y_pos_sph, radius_sph, d_sph, n_sph):
eps = []
for y in range(size_y):
print('Processing [{}/{}]'.format(y, size_y - 1), end="\r")
for x in range(size_x):
if chec... | magicoder | python |
You are tasked with implementing a Python function to parse a connection string for an Azure Event Hubs service bus. The connection string contains various parameters such as the endpoint, shared access key name, shared access key, and entity path. Your task is to create a function that can extract and validate these p... | ```python
class ConnectionInfo:
def __init__(self, endpoint, fully_qualified_namespace, shared_access_key_name, shared_access_key, eventhub_name):
self.endpoint = endpoint
self.fully_qualified_namespace = fully_qualified_namespace
self.shared_access_key_name = shared_access_key_name
... | magicoder | python |
You are tasked with implementing a simple physics simulation using the Box2D library. Your goal is to create a class representing a joint in the physics world and implement its functionality for updating and drawing.
You are provided with a partial code snippet that sets up a test suite for the Box2D joint class. The ... | ```cpp
#include <Box2D/Box2D.h>
class Box2DJoint {
public:
Box2DJoint(b2World& world, void* userData) : m_world(world), m_userData(userData) {}
void create() {
// Implement joint creation in the physics world
// Example:
// m_jointDef.Initialize(bodyA, bodyB, anchor);
// m_join... | magicoder | cpp |
You are tasked with implementing a shell script that processes IP address ranges and outputs the corresponding range in CIDR notation. The script should handle three different cases: single IP address, IP address with subnet mask, and no input.
Your task is to complete the shell script by implementing the missing func... | ```bash
#!/bin/bash
# Function to convert IP address to long integer
IP2long() {
local IFS=.
read -r a b c d <<< "$1"
echo $((a * 256 ** 3 + b * 256 ** 2 + c * 256 + d))
}
# Function to convert long integer to IP address
long2IP() {
local num=$1
echo "$((num >> 24 & 255)).$((num >> 16 & 255)).$((num >> 8 & ... | magicoder | shell |
You are tasked with implementing a shell script function that automates the setup and execution of a development environment using the `ddev` tool. The `ddev` tool is a local development environment management tool commonly used for web development projects.
Your task is to complete the `ddev-install` function, which ... | ```bash
ddev-install() {
if ! command -v ddev &>/dev/null; then
echo "Error: 'ddev' command not found. Please install ddev before proceeding."
return 1
fi
local project_name=$1
mkdir "$project_name" && cd "$project_name" || { echo "Error: Failed to create project directory."; return 1; ... | magicoder | shell |
You are tasked with creating a Python class that processes and analyzes video data from a dataset. The dataset contains information about various videos, including their titles, durations, and upload dates. Your goal is to create a class that can perform specific operations on this video data.
Create a Python class ca... | ```python
import json
from dateutil import parser
class VideoProcessor:
def __init__(self, file_path):
with open(file_path, 'r') as file:
self.video_data = json.load(file)
def get_longest_video(self):
longest_video = max(self.video_data, key=lambda video: self._duration_to_seconds(... | magicoder | python |
You are tasked with implementing a Variational Autoencoder (VAE) using Pyro, a probabilistic programming language built on top of PyTorch. Your goal is to define the model and guide functions for the VAE, which involves creating an encoder and decoder network, setting up the model for the conditional probability distri... | ```python
import torch
import pyro
import pyro.distributions as dist
from pyro.nn import PyroModule, PyroSample
class Encoder(PyroModule):
def __init__(self, z_dim, hidden_dim):
super(Encoder, self).__init__()
self.fc1 = torch.nn.Linear(784, hidden_dim)
self.fc21 = torch.nn.Linear(hidden_di... | magicoder | python |
You are tasked with implementing a function to calculate the sector number based on the given global angle in a coordinate system. The global angle is represented in degrees, and the sector number is determined based on the sector's angular range. The sector number is calculated by subtracting a constant offset from th... | ```java
public int calculateSectorNumber(int globalPhi) {
int globalSectorPhi = (globalPhi - 24); // Calculate the sector-specific angle
int sectorWidth = 15; // Sector's angular width
int sectorNumber = globalSectorPhi / sectorWidth; // Calculate the sector number
return sectorNumber;
}
``` | magicoder | java |
You are tasked with creating a Python program to manage NFC (Near Field Communication) tags. The program should continuously poll for NFC tags and store their information in a Parse database. NFC tags are unique identifiers that can be read by NFC-enabled devices. The code snippet provided is a part of the program and ... | ```python
import commands
import ParsePy
# Initialize ParsePy with your application ID and REST API key
ParsePy.APPLICATION_ID = "your_application_id"
ParsePy.REST_API_KEY = "your_rest_api_key"
while True:
# Poll for NFC tags
(status, tag_id) = commands.getstatusoutput("sudo ./nfc-poll")
# Check if the c... | magicoder | python |
You are tasked with implementing a message storage system that allows adding new base messages and checking for the existence of exactly the same message. The system is represented by a class with a method `add_new_base_message` that takes a new base message as input and returns the added message. The method should als... | ```python
class BaseMessage:
def __init__(self, content: str):
self.content = content
def __str__(self):
return self.content
class MessageStorageSystem:
def __init__(self):
self.base_message_dict = {}
def add_new_base_message(self, new_base_message: BaseMessage) -> BaseMessage... | magicoder | python |
You are tasked with implementing a URI redirection mechanism in a web application. The application receives URIs and needs to check if the URI is a protocol request, and if so, redirect it to a specific URI based on certain conditions. You are given a code snippet that partially implements this functionality. Your task... | ```csharp
using System;
using System.Text.RegularExpressions;
public class UriRedirector
{
private static Uri s_lastProtocolUri;
private static Uri s_lastRedirectedUri;
private static DateTime s_lastRedirectedTime;
private static Regex s_protocolRegex = new Regex(@"^(http|https|ftp)://", RegexOptions.I... | magicoder | csharp |
You are tasked with implementing a caching mechanism for a document retrieval system. The system retrieves documents based on a query and two document identifiers. To optimize performance, the system employs a caching strategy to store previously computed preferences for document pairs. Your task is to design and imple... | ```python
class DocumentCache:
def __init__(self):
self.cache = {}
def cache_preference(self, symmetric_key, preference):
self.cache[symmetric_key] = preference
def retrieve_preference(self, symmetric_key):
return self.cache.get(symmetric_key, None)
# Example usage
cache = Documen... | magicoder | python |
You are tasked with implementing a function that calculates the number of times a given character appears in a string and its subsequent substrings. The function should take two parameters: a string and a character. The function should return an array of integers, where each element represents the count of the characte... | ```javascript
function characterCountInSubstrings(str, char) {
const result = [];
for (let i = 0; i < str.length; i++) {
let count = 0;
for (let j = i; j < str.length; j++) {
if (str[j] === char) {
count++;
}
result.push(count);
}
}
return result;
}
console.log(characterCo... | magicoder | javascript |
You are tasked with creating a custom annotation in Java that can be used to specify the MIME type for a reactive socket. The annotation should allow developers to override the default MIME type if needed. Your task is to implement the custom annotation and demonstrate its usage in a sample class.
Create a custom anno... | ```java
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(ReactiveSockets.class)
@AliasFor(annotation = ReactiveSocket.class)
public @interface ReactiveSocket {
String mimeType() default "application/java-serialized-object";
}
@Target(ElementType.METHOD)
@R... | magicoder | java |
You are tasked with implementing a graph-based recommendation system using a heterogeneous graph. The system involves constructing a heterograph, setting node features, and handling self-relations. Your task is to complete the function `construct_heterograph` that takes in the following parameters:
- `target_node_type`... | ```python
import dgl
def construct_heterograph(target_node_type, edgelists, id_to_node, features):
if target_node_type in id_to_node:
# add self relation
edgelists[('target', 'self_relation', 'target')] = [(t, t) for t in id_to_node[target_node_type].values()]
g = dgl.heterograph(edgelists... | magicoder | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.