query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with implementing a scale space construction algorithm for images using the given code snippet as a starting point. The scale space construction involves creating a series of smoothed and subsampled images at different scales to capture multi-scale features in the original image.
The provided code snipp... | ```java
public void createScaleSpace(Image image) {
// Initialize the octave factory with the image and parameters
OctaveFactory octaveFactory = new OctaveFactoryImpl(image, LOWE_SCALES_PER_OCTAVE, LOWE_INITIAL_SIGMA, LinearUpScaler(), Subsampler(), GaussianFilter());
// Construct the scale space by creati... | magicoder | java |
You are tasked with creating a Python function that simulates a simplified version of a library catalog system. The function should take in a list of book titles and their corresponding authors, and then allow users to search for books by either title or author. If a book is found, the function should return the book's... | ```python
def library_catalog(books):
catalog = {title: author for title, author in books}
def search_book(query):
if query in catalog:
return f'"{query}" by {catalog[query]}'
else:
for title, author in catalog.items():
if query == author:
... | magicoder | python |
You are tasked with creating a script that performs a metadata query lookup for a given entity ID using the SAML2 Metadata Query (MDQ) service. The script should accept the entity ID as a command-line argument and, optionally, the MDQ endpoint. If the MDQ endpoint is not provided as an argument, the script should defau... | ```bash
#!/bin/bash
ENTITYID=${1:?EntityID not specified. Usage: $0 <entityid> [ mdqendpoint ]}
MDQENDPOINT=${2:-${MDQENDPOINT:-http://mdq.ukfederation.org.uk/entities/}}
CURLOPTS=${CURLOPTS:-'-s'}
# Perform metadata query lookup using cURL
curl $CURLOPTS "${MDQENDPOINT}${ENTITYID}"
``` | magicoder | shell |
You are tasked with creating a command-line utility for extracting data from different file formats used in a video game. The utility should support extracting data from ".pac" and ".dds" files. For the ".pac" files, the utility should specifically support the LEGO Alpha Team game format. The utility should be able to ... | ```python
import sys
def print_help_pac():
print("LEGO Alpha Team .pac Extractor")
print("Usage: vgfutil.py lego_alpha_team pac <command> [options] <file>")
print("")
print("Example: vgfutil.py lego_alpha_team pac extract all ./audio Audio.pac")
print("")
print("All commands have the available ... | magicoder | python |
You are working on a project that involves analyzing diffuse gamma-ray data from the Fermi Gamma-ray Space Telescope using the `gammapy` library in Python. The code snippet provided uses the `FermiGalacticCenter` dataset from `gammapy.datasets` to create an integral flux image for a specific energy band and then saves ... | ```python
from astropy.units import Quantity
from gammapy.datasets import FermiGalacticCenter
def calculate_integral_flux_image(energy_band, energy_bins):
cube = FermiGalacticCenter.diffuse_model()
energy_band = Quantity(energy_band, 'GeV')
image = cube.integral_flux_image(energy_band, energy_bins=energy_b... | magicoder | python |
You are tasked with implementing a service registry system for a microservices architecture. The service registry will store information about various services, including their names, versions, and endpoints. Your goal is to design and implement a data structure to efficiently store and retrieve this information.
You ... | ```cpp
#include <unordered_map>
#include <string>
#include <memory>
// Define a structure to represent a service
struct Service {
std::string name;
std::string version;
std::string endpoint;
Service(const std::string& name, const std::string& version, const std::string& endpoint)
: name(name),... | magicoder | cpp |
You are tasked with creating a program to keep track of points scored by different teams in a sports tournament. The program should read input from the user, process the scores, and update the points accordingly. The input consists of a series of lines, each containing the names of two teams and the scores they achieve... | ```csharp
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Dictionary<string, int> points = new Dictionary<string, int>();
string input = Console.ReadLine();
while (!string.IsNullOrEmpty(input))
{
string[] inputParts = input.Spli... | magicoder | csharp |
You are tasked with creating a TypeScript module that manages workspaces for a collaborative coding platform. The module should export a set of functions and classes to handle workspace-related operations. Your goal is to implement the `workspaceService` module, which will be used by other parts of the system to intera... | ```typescript
// workspaceService.ts
// Interface for workspace information
interface WorkspaceInfo {
id: string;
name: string;
description: string;
// Add any other relevant properties
}
// Class representing a workspace
export class Workspace {
private id: string;
private name: string;
private descrip... | magicoder | typescript |
You are tasked with creating a script to automate the installation of Android SDK tools and Gradle for a development environment. The provided code snippet is a partial script that needs to be completed. The script takes two required arguments: the SDK version and the Gradle version. It then downloads the necessary SDK... | ```bash
#!/usr/bin/env bash
set -e
SDK_VERSION=${1?"sdk version missing"}
GRADLE_VERSION=${2?"gradle version missing"}
shift; shift
cd "$ANDROID_HOME"
echo "installing sdk tools $SDK_VERSION"
wget --continue "https://dl.google.com/android/repository/commandlinetools-linux-${SDK_VERSION}_latest.zip"
unzip -q commandli... | magicoder | shell |
You are tasked with implementing a Tic-Tac-Toe game in Python. The game will have two players, X and O, who take turns marking the spaces in a 3x3 grid. The game ends when either one player has three of their marks in a row, column, or diagonal, or when all 9 spaces are filled without a winner. If a player attempts to ... | ```python
import sys
def make_move(board, player, row, col):
if player not in ['X', 'O']:
print('Invalid player "{}", must be X or O'.format(player))
sys.exit(1)
if row < 0 or row > 2 or col < 0 or col > 2:
print('Invalid row or column')
sys.exit(1)
if board[row][c... | magicoder | python |
You are tasked with implementing a parallelized molecular dynamics simulation using the LAMMPS software package. LAMMPS is a widely-used open-source molecular dynamics software, and it provides a Python interface for setting up simulations. In this problem, you will be working with a code snippet that sets up the param... | ```python
# Import necessary modules
from mpi4py import MPI
from lammps import IPyLammps
# Initialize MPI communicator
comm = MPI.COMM_WORLD
me = comm.Get_rank()
# Distribute the molecular system among MPI processes
molecules_per_process = len(molecules) // comm.Get_size()
my_molecules = molecules[me * molecules_per_... | magicoder | python |
You are tasked with implementing a function to normalize a dataset using the min-max scaling technique. Min-max scaling transforms the features by scaling each feature to a given range (by default, between 0 and 1). The formula for min-max scaling is:
\[ X_{norm} = \frac{X - X_{min}}{X_{max} - X_{min}} \]
Where:
- \(... | ```python
import numpy
from typing import Tuple
def normalize_dataset(dataset: numpy.ndarray) -> Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray]:
# Calculate the ranges and minimum values for each feature
ranges = numpy.max(dataset, axis=0) - numpy.min(dataset, axis=0)
min_values = numpy.min(dataset, ax... | magicoder | python |
You are given a code snippet that appears to be part of an insertion sort algorithm. However, there are some missing parts in the code. Your task is to complete the implementation of the insertion sort algorithm and then write a function to perform a specific task using the sorted array.
Complete the implementation of... | ```cpp
// Complete the insertion sort algorithm
void insertionSort(int array[], int length) {
for (int i = 1; i < length; i++) {
int key = array[i];
int j = i - 1;
while (j >= 0 && array[j] > key) {
array[j + 1] = array[j];
j = j - 1;
}
array[j + 1] = ... | magicoder | cpp |
You are tasked with creating a program that converts a given integer into its Polish word representation. For example, the integer 123 would be converted to "sto dwadzieścia trzy". The provided code snippet can be used as a reference for the Polish word representations of hundreds.
Your task is to implement a function... | ```python
def int_to_polish_word(num: int) -> str:
ones = ["", "jeden", "dwa", "trzy", "cztery", "pięć", "sześć", "siedem", "osiem", "dziewięć"]
teens = ["", "jedenaście", "dwanaście", "trzynaście", "czternaście", "piętnaście", "szesnaście", "siedemnaście", "osiemnaście", "dziewiętnaście"]
tens = ["", "dzie... | magicoder | python |
You are tasked with implementing a method to execute a command with a single hash parameter in a remote procedure call (RPC) console. The provided code snippet is a part of a class method `exec_cmd_with_hash_param` which takes a command `cmd` and a dictionary of parameters `params`. The method is intended to execute th... | ```python
def exec_cmd_with_hash_param(self, cmd, params):
"""
execute cmd with one hash param
"""
if cmd in RPCConsole.functions["one_hash"]:
# Assuming execute_command is a method to execute the command with the hash parameter
result = self.execute_command(cmd, params)
return r... | magicoder | python |
You are tasked with implementing a PHP class method that renders a template with data. The method should take an array of data as input and return a string representing the rendered template. Your task is to complete the implementation of the `render` method in the given PHP class.
```php
class TemplateRenderer
{
... | ```php
public function render($data_array = [])
{
if (file_exists($this->_template)) {
// Extract the data_array to make its keys accessible as variables in the template
extract($data_array);
// Start output buffering to capture the rendered template
ob_start();
include $thi... | magicoder | php |
You are tasked with implementing a C++ template meta-programming problem that involves merging two sorted lists at compile time. Your goal is to create a meta-function that takes two sorted lists as template parameters and merges them into a single sorted list. The input lists are represented as template parameter pack... | ```cpp
#include <type_traits>
template<typename...>
struct list {};
template<typename T, typename U>
struct less : std::integral_constant<bool, sizeof(T) < sizeof(U)> {};
template<typename...>
struct _merge_impl;
template<typename... xs>
struct _merge_impl<list<xs...>, list<>, list<xs...>, less>
{};
template<typen... | magicoder | cpp |
You are tasked with creating a script to automate the packaging and distribution of a set of files. The script should create a compressed archive containing specific files, generate an executable file, and calculate the MD5 checksum of the resulting archive.
Your task is to write a shell script that accomplishes the f... | ```bash
#!/bin/bash
temp=$(mktemp -d)
bin_name="archive.tar.gz"
pex . -v \
--disable-cache \
--platform current \
--console-script bm-instance-agent \
--output-file ${temp}/bm-instance-agent.pex
cp ./tools/shellinaboxd-x86_64 ./tools/shellinaboxd-aarch64 ${temp}
tar -C ${temp} -czf ${temp}/${bin_name... | magicoder | shell |
You are tasked with implementing a set of classes and methods for handling map rendering in a mapping application. The provided code snippet is part of a larger system and demonstrates the usage of various classes and methods. Your task is to create the necessary classes and methods to support the functionality indicat... | ```swift
// Define the MCreateSavePixelRange class
class MCreateSavePixelRange {
// Method to create a pixel range based on the specified zoom level
func factoryPixelRange(zoom: Int) -> MCreateSavePixelRange {
// Implementation logic to create and return the pixel range
}
}
// Define the MCreateSav... | magicoder | swift |
You are tasked with implementing a custom library in C# that includes a component for handling mathematical operations. The library is organized within the `MyLibrary` namespace, and the component is defined as a partial class named `MyComponent`. Your goal is to create a method within this component that calculates th... | ```csharp
namespace MyLibrary {
public partial class MyComponent {
public int CalculateFactorial(int n) {
if (n < 0) {
throw new ArgumentException("Input must be a non-negative integer.");
}
if (n == 0 || n == 1) {
return 1;
}
... | magicoder | csharp |
You are tasked with creating a form validation function for a user registration form. The form contains an input field for the username, and the validation function should check if the username meets certain criteria. The code snippet provided is a part of the HTML input element for the username field, and it includes ... | ```javascript
function validateUsername(username) {
if (!username || username.length < 5 || username[0] === '_') {
return false;
}
return /^[a-zA-Z0-9_]+$/.test(username);
}
``` | magicoder | javascript |
You are tasked with creating a Python function that constructs a transaction for a decentralized finance (DeFi) application on the Algorand blockchain. The function takes in various parameters related to the transaction and returns the constructed transaction object.
You are given the following code snippet as a refer... | ```python
import algosdk
from algosdk.future.transaction import ApplicationCallTxn
def construct_defi_transaction(suggested_params, storage_account, manager_app_id, market_app_id, oracle_app_id, foreign_assets):
txn = ApplicationCallTxn(
sender=storage_account,
sp=suggested_params,
index=ma... | magicoder | python |
You are tasked with implementing a data conversion function that takes in a nested dictionary and converts it into a flattened dictionary based on certain conditions. The input dictionary contains various types of data, including nested dictionaries and other data types. The conversion process involves handling differe... | ```python
def convert_data(data):
output = {}
def convert_building_use(key, value, data):
# Implementation of convert_building_use method
pass
def convert_address_fields(key, value, output):
# Implementation of convert_address_fields method
pass
for key in data:
... | magicoder | python |
You are given a Python code snippet that involves sorting a list of tuples based on the second element of each tuple. Your task is to implement a function that achieves the same sorting behavior as demonstrated in the code snippet.
Write a function `sort_by_second_element` that takes a list of tuples as input and retu... | ```python
from typing import List, Tuple, Any
def sort_by_second_element(lst: List[Tuple[Any, Any]]) -> List[Tuple[Any, Any]]:
return sorted(lst, key=lambda x: x[1])
```
The `sort_by_second_element` function takes a list of tuples as input and uses the `sorted` function with a custom sorting key. The key is define... | magicoder | python |
You are tasked with implementing a password reset feature for a mobile application. The `ResetPassword` class is responsible for handling the user interface and logic related to resetting a user's password. The class inherits from `UIViewController`, indicating that it is a view controller in an iOS application.
Your ... | ```swift
import UIKit
class ResetPassword: UIViewController {
// UI elements
let emailTextField = UITextField()
let submitButton = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
private func setupUI() {
// Configure email text field
em... | magicoder | swift |
You are tasked with writing a script to synchronize files between two directories. The script should compare files in the two directories and copy over any files that have been modified or are missing in the destination directory.
You are given a code snippet that partially implements this synchronization process. The... | ```bash
#!/bin/bash
# Complete the synchronization script
RUNPATH=(${RUNPATH//bin/ })
RUNPATH="${RUNPATH[0]}"bin
echo $WORKSPACE_ROOT
echo $RUNPATH
while read original formatted; do
if [[ ! -z "$original" ]] && [[ ! -z "$formatted" ]]; then
if [[ -f "$WORKSPACE_ROOT/$original" ]] && [[ -f "$RUNPATH/$form... | magicoder | shell |
You are tasked with implementing a 3D transformation library in C++ using the OpenGL Mathematics (GLM) library. Your goal is to create a class that provides functions for rotating objects around the x, y, and z axes. The class should include methods for rotating by both degrees and radians. You need to implement the fo... | ```cpp
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
class TransformationLibrary {
public:
glm::mat4 transformationMatrix;
void rotateXDeg(float degrees) {
transformationMatrix = glm::rotate(transformationMatrix, glm::radians(degrees), glm::vec3(1.0f, 0.0f, 0.0f));
}
void rot... | magicoder | cpp |
You are tasked with creating a custom warning system for a Python application. Your goal is to implement a class that can issue warnings with different severity levels and messages. The warning system should be able to handle different types of warnings, such as DeprecationWarning, UserWarning, and RuntimeWarning. Addi... | ```python
import warnings
import unittest
class CustomWarningSystem:
def issue_warning(self, message, warning_type):
if warning_type not in {"DeprecationWarning", "UserWarning", "RuntimeWarning"}:
raise ValueError("Invalid warning type")
warnings.warn(message, eval(warning_type))
class... | magicoder | python |
You are tasked with implementing a signal processing function that calculates the cross-correlation scores between a given signal and a template. The cross-correlation score at each position indicates the similarity between the signal and the template at that position.
You need to implement the `conv` function, which ... | ```python
def conv(signal, template):
scores = []
signal_length = len(signal)
template_length = len(template)
for i in range(signal_length - template_length + 1):
score = 0
for j in range(template_length):
score += signal[i + j] * template[j]
scores.append(score)
... | magicoder | python |
You are tasked with creating a Python command-line tool that generates instances of random mathematical problems for educational purposes. The tool should allow users to specify the number of variables for the problem instances. The instances can be of two types: uniform and power instances. A uniform instance generate... | ```python
import click
from instance import UniformInstance, PowerInstance
@click.command()
@click.option('--variables', '-n', default=5, type=int, help='Number of variables.')
@click.option('--uniform', 'instance_type', flag_value='uniform', default=True, help='Generate uniform instance.')
@click.option('--power', 'i... | magicoder | python |
You are tasked with creating a Python function that simulates a simple request handler for making HTTP requests. The request handler function should be able to make GET and POST requests to a specified URL and return the response. Additionally, you need to write a unit test for the request handler function to ensure th... | ```python
import requests
def request_handler(method, url):
if method.upper() == 'GET':
response = requests.get(url)
elif method.upper() == 'POST':
response = requests.post(url)
else:
raise ValueError("Invalid HTTP method. Only 'GET' and 'POST' are supported.")
return response
... | magicoder | python |
You are tasked with writing a Bash script that takes a target number and a list of integers as input, and finds the integer in the list that is closest to the target. Your script should output the nearest integer.
Your script should adhere to the following requirements:
- The script should be named `find_nearest.sh`.
... | ```bash
#!/bin/bash
declare -r target="$1"
declare -ar list="($2)"
declare nearest
declare -r regex="^(-{0,1}[0-9]+\s*)+$"
declare abs_diff
declare diff
# Input validation using regular expression
if [[ ! $target =~ $regex || ! $2 =~ $regex ]]; then
echo "Invalid input. Please provide a valid target number and a ... | magicoder | shell |
You are tasked with implementing a custom Angular pipe that filters an array of objects based on a given condition. The pipe should take an array of objects and a filter condition as input and return a filtered array based on the condition. Your task is to complete the implementation of the `FilterPipe` in Angular.
Th... | ```typescript
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filter'
})
export class FilterPipe implements PipeTransform {
transform(items: any[], filter: any): any {
if (!items || !filter) {
return items;
}
if (Array.isArray(items) && filter) {
return items.filter(it... | magicoder | typescript |
You are tasked with writing a script to automate the process of bundling a server certificate and a CA (Certificate Authority) certificate into a single file, and then moving the server's private key to a designated location. The script should handle these operations in a secure and efficient manner.
Write a shell scr... | ```bash
#!/bin/bash
# Concatenate server.pem and ca.pem into a single file and save it to the bundle destination
cat server.pem ca.pem > "${bundle_destination}"
# Move the server's private key to the designated location
mv server-key.pem "${key_destination}"
```
The provided shell script accomplishes the required ta... | magicoder | shell |
You are tasked with implementing a generic memory-mapped I/O (MMIO) structure in Rust. The MMIO structure should support reading and writing to a memory-mapped register. Additionally, you need to implement the `Debug` trait for the MMIO structure to allow for debugging and visualization of the register's value.
Your t... | ```rust
use std::fmt::{Debug, Formatter, Error};
struct Mmio<T> {
value: T,
}
impl<T> Mmio<T> {
fn read(&self) -> T {
self.value
}
fn write(&mut self, value: T) {
self.value = value;
}
}
impl<T> Debug for Mmio<T> where T: Copy + Debug {
fn fmt(&self, fmt: &mut Formatter) -> R... | magicoder | rust |
You are tasked with creating a Rust macro that generates a custom logging macro for a specific use case. The macro should take in a message and additional key-value pairs, and it should output a formatted log message with the provided information. The log message should include the version of the cargo package from whi... | ```rust
// Define the custom_log macro
macro_rules! custom_log {
(info, $msg:expr, $($key:ident : $value:expr),*) => {
println!("[{}] info: {} - {}", env!("CARGO_PKG_VERSION"), $msg, $(concat!(stringify!($key), ": ", $value, ", "))*);
};
(warn, $msg:expr, $($key:ident : $value:expr),*) => {
... | magicoder | rust |
You are tasked with creating a Python function that preprocesses image data for a machine learning model. The function should take in the training and testing image datasets, perform specific preprocessing steps, and return the preprocessed datasets. The preprocessing steps include reshaping the images and converting t... | ```python
import tensorflow as tf
from tensorflow import keras
def preprocess_image_data(x_train, y_train, x_test, y_test):
# Reshape the images and convert data type
x_train = x_train.reshape(60000, 784).astype("float32") / 255
x_test = x_test.reshape(10000, 784).astype("float32") / 255
return x_train... | magicoder | python |
You are tasked with creating a Python class that acts as a wrapper for a RESTCONF session using the YDK library. RESTCONF is a protocol used to provide a programmatic interface for accessing data defined in YANG models, and the YDK library is a Python SDK that provides bindings for YANG data models.
Your task is to im... | ```python
import logging
from ydk.ext.path import RestconfSession
class RestconfError(Exception):
pass
class CustomRestconfSession(RestconfSession):
def __init__(self, host, port, username, password):
super().__init__(host, port, username, password)
def send(self, request):
try:
... | magicoder | python |
You are tasked with creating a program to analyze the average age of a population based on a given set of age data. The program should prompt the user to input the ages of individuals in the population and then calculate the average age. Additionally, the program should provide the option to visualize the age distribut... | ```python
import matplotlib.pyplot as plt
import streamlit as st
def calculate_average_age(age_list):
return sum(age_list) / len(age_list)
def main():
# Prompt user to input ages
ages = st.text_input("Enter the ages of individuals separated by commas (e.g., 25,30,22): ")
# Convert input to list of in... | magicoder | python |
You are tasked with implementing a feature detection system for a natural language processing application. The system should take a dictionary of functions as input and return a feature detector that applies the supplied functions to each token in a given text.
Your task is to complete the implementation of the `featu... | ```python
def feature(functions):
"""
Return a feature detector that applies the supplied functions
to each token.
@type functions: dictionary of functions
@param functions: a dictionary of functions to compute the features.
"""
def feature_detector(text):
features = {}
toke... | magicoder | python |
You are tasked with creating a Python program that processes incoming data packets and extracts relevant information from them. The program should handle two types of data packets: one containing information about a visual effect and another containing an error message.
The data packets are received in the following f... | ```python
def process_data_packet(data):
try:
# Split the data packet based on the presence of colons or commas
if ':' in data:
addr, effect, elapsed, beat, hue_med, hue_dev = data.split()[1].split(':'), data.split()[2], int(data.split()[4].split(':')[1]), int(data.split()[5].split(':')[... | magicoder | python |
You are tasked with creating a script to retrieve weather data from a specific URL using the `curl` command in a Unix-like environment. The script should download an XML file containing weather information for a specific date and save it with a specific filename.
Your script should take the following inputs:
- `$certi... | ```bash
#!/bin/bash
# Input variables
certificate="/path/to/certificate.pem"
ua="MyUserAgent"
tanggal="10"
bulan="09"
tahun="2023"
# Construct the URL
url="http://data.bmkg.go.id/propinsi_${tanggal}_${bulan}.xml"
# Download the XML file using curl
curl --cacert "$certificate" -A "$ua" "$url" -so "temp/cuaca_besok_${... | magicoder | shell |
You are working on a computer vision project and need to process image masks using Python and the PyTorch library. You have a 4-dimensional tensor `img_masks` representing a batch of image masks, and you need to apply a thresholding operation to the masks. The thresholding operation involves comparing each element of t... | ```python
import torch
def apply_threshold(img_masks: torch.Tensor, mask_thr_binary: float) -> torch.Tensor:
mask = img_masks[0, 0, :, :] # Extract the first element of the batch
thresholded_mask = (mask >= mask_thr_binary).to(dtype=torch.uint8) # Apply thresholding operation
return thresholded_mask
```
... | magicoder | python |
You are tasked with implementing a dependency resolution algorithm for a software package manager. The package manager needs to resolve dependencies for a given package based on the provided dependency list. Each package can have dependencies on other packages, forming a directed acyclic graph (DAG). Your task is to wr... | ```python
def resolve_dependencies(initial, dependencies):
graph = {}
for dep in dependencies:
if dep[0] not in graph:
graph[dep[0]] = []
graph[dep[0]].append(dep[1])
visited = set()
result = []
def dfs(node):
if node in visited:
return
visit... | magicoder | python |
You are tasked with implementing a custom attribute in C# that enforces a non-null constraint on a property. The attribute should be applied to a property, and if the property's value is null, an exception should be thrown at runtime.
Your task is to create a custom attribute called "NotNull" and apply it to a propert... | ```csharp
using System;
[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
sealed class NotNullAttribute : Attribute
{
// No additional logic is needed for this custom attribute
}
class CustomClass
{
private string _objectName;
[NotNull]
public string ObjectName
... | magicoder | csharp |
You are tasked with creating a script that automates the execution of a Java application in a Unix-like environment. The script should handle the conversion of file paths from Cygwin format to Windows format if the script is running on Cygwin. The script should also pass the `DALMA_HOME` environment variable to the Jav... | ```bash
#!/bin/bash
# Check if running on Cygwin
if [[ "$OSTYPE" == cygwin* ]]; then
# Convert DALMA_HOME to Windows format using cygpath
DALMA_HOME=$(cygpath -w "$DALMA_HOME")
fi
# Execute the Java application with DALMA_HOME environment variable and additional arguments
exec java "-DDALMA_HOME=$DALMA_HOME" -jar... | magicoder | shell |
You are tasked with creating a script to automate the installation of Java Development Kit (JDK) version 9.0.4 on a Linux system. The script should also update the system's package repository and install the `wget` utility if not already present. The script should be designed to be run on a Debian-based system.
Write ... | ```bash
#!/bin/bash
# Function to check GitHub stars
check_github_stars() {
stars=$(curl -s https://api.github.com/repos/<gh_stars> | grep -o '"stargazers_count":[0-9]*' | grep -o '[0-9]*')
echo "The repository <gh_stars> has $stars stars."
}
# Update system package repository and install wget
update_and_install(... | magicoder | shell |
You are given a sequence of integers representing the heights of a series of buildings. Your task is to find the maximum area of a rectangle that can be formed by a subset of these buildings. The width of the rectangle is the number of buildings it covers, and the height of the rectangle is the minimum height among the... | ```python
def maxRectangleArea(heights):
stack = []
max_area = 0
i = 0
while i < len(heights):
if not stack or heights[i] >= heights[stack[-1]]:
stack.append(i)
i += 1
else:
top = stack.pop()
width = i if not stack else i - stack[-1] - 1
... | magicoder | python |
You are tasked with creating a role-based access control system for a web application. The system should allow the creation of roles with specific names and guard names. The guard name is used to specify the "area" or "section" of the application to which the role pertains.
Your task is to implement a function or met... | ```php
function createRole($name, $guardName) {
// Check if the role already exists for the given guard name
$existingRole = Role::where('name', $name)->where('guard_name', $guardName)->first();
if ($existingRole) {
return "Role '$name' already exists for guard '$guardName'";
} else {
/... | magicoder | php |
You are tasked with implementing a method to reverse the order of words in a given string. A word is defined as a sequence of non-space characters. Your task is to write a function `reverseWords` that takes a string as input and returns the string with the order of words reversed.
For example, given the input string "... | ```java
public String reverseWords(String s) {
String[] words = s.split(" "); // Split the input string by space to get individual words
StringBuilder reversed = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--) {
reversed.append(words[i]); // Append each word in reverse order
... | magicoder | java |
You are tasked with implementing a Python function that processes a list of tuples representing database query conditions and returns a dictionary containing the processed conditions. Each tuple in the input list represents a condition in the format (field, operator, value). The function should handle the following ope... | ```python
def process_conditions(conditions: list) -> dict:
processed_conditions = {}
for field, operator, value in conditions:
if operator == '=':
processed_conditions[field] = value
elif operator in ['>', '<', '>=', '<=']:
processed_conditions[field] = {operator: value}... | magicoder | python |
You are given a Python code snippet that involves elliptic curve cryptography. Your task is to implement the Hensel lift algorithm to compute the x and y coordinates of a point on an elliptic curve over a finite field.
The Hensel lift algorithm is used to lift a point on an elliptic curve modulo a prime to a point on ... | ```python
class E:
def __init__(self, x, y):
self.x = x
self.y = y
@staticmethod
def a4():
return 0 # Replace with the actual coefficient A
@staticmethod
def a6():
return 0 # Replace with the actual coefficient B
def hensel_lift(curve, p, point):
A, B = map(l... | magicoder | python |
You are tasked with creating a program that extracts the text content within HTML tags from a given input string. Specifically, you need to extract the text within the `<p>` tags and output it in a specific format.
Write a function `extractParagraphContent(inputString: str) -> List[str]` that takes an input string con... | ```python
from typing import List
import re
def extractParagraphContent(inputString: str) -> List[str]:
pattern = r'<p>(.*?)</p>'
matches = re.findall(pattern, inputString)
return matches
```
The `extractParagraphContent` function uses the `re.findall` method to extract the text content within the `<p>` t... | magicoder | python |
You are tasked with creating a Python program that uses the dlib library to detect and track frontal faces in a video file. The dlib library provides a pre-trained facial detection model that can be used to identify faces in images and videos. Your program should read frames from a video file, detect frontal faces in e... | ```python
import dlib
import cv2
# Load the pre-trained frontal face detection model
detector = dlib.get_frontal_face_detector()
# Open the video file
video_file = 'path_to_video_file.mp4' # Replace with the actual path to the video file
cap = cv2.VideoCapture(video_file)
# Check if the video file was successfully ... | magicoder | python |
You are tasked with implementing a Python class that handles batch requests and returns the count of elements in each batch. The provided code snippet demonstrates the setup of a backend service using the `serve` library, which is designed for serving machine learning models. Your task is to create a class that can han... | ```python
import serve
class NoListReturned:
def __init__(self):
self.count = 0
@serve.accept_batch
def __call__(self, requests):
return [len(batch) for batch in requests]
# Set the max batch size.
config = serve.BackendConfig(max_batch_size=5)
client.create_backend("exception:v1", NoList... | magicoder | python |
You are tasked with implementing a first-person camera controller in a 3D game. The camera should be able to rotate horizontally and vertically in response to mouse movement. The provided code snippet includes the initialization of a variable `xRotation` and the `Update` method, which handles the mouse input and update... | ```csharp
float xRotation = 0f;
float mouseSensitivity = 100f; // Adjust the sensitivity as needed
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
void Update()
{
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitiv... | magicoder | csharp |
You are tasked with implementing a function that performs a specific data transformation on a given input. The input is a vector of boolean values, and the transformation involves grouping consecutive occurrences of the same value and then dropping elements from the beginning of each group until a certain condition is ... | ```cpp
#include <vector>
#include <iter/iter.h>
std::vector<bool> transform_data(const std::vector<bool>& input) {
std::vector<bool> result;
auto grouped = iter::groupby(input, [](bool b) { return b; });
for (auto& group : grouped) {
auto dropwhile_true = iter::dropwhile(group.second, [](bool b) { return !b;... | magicoder | cpp |
You are tasked with implementing a feature for a document storage system. The system uses a session to store documents, and each document has an ID associated with it. The requirement is to automatically assign a new ID to a document if the provided ID is 0.
You are given a code snippet from a unit test that demonstra... | ```csharp
public class DocumentStorage
{
private int nextId = 1; // Initialize the next available ID
public void StoreDocument<T>(T document) where T : IDocument
{
if (document.Id == 0)
{
document.Id = nextId; // Assign the next available ID
nextId++; // Increment th... | magicoder | csharp |
You are working on a deployment script for a microservices architecture using Docker Compose. Your task is to implement a function that will stop and remove all services defined in a specific Docker Compose file, or alternatively, delete all services forcefully without stopping them.
You are given the following code s... | ```bash
function manageServices() {
local composeFile=$1
local stopServices=$2
if [ "$stopServices" = true ]; then
echo 'Stopping all services...'
docker-compose -f "$composeFile" stop
docker-compose -f "$composeFile" rm
else
echo 'Deleting all services forcefully...'
... | magicoder | shell |
You are tasked with implementing a Book class in Python that keeps track of the number of pages read by a reader. The Book class should have the following functionalities:
- A constructor that takes the book's title and total page count as parameters and initializes the pages_read to 0.
- A read method that takes the n... | ```python
class TooManyPagesReadError(Exception):
def __init__(self, message):
super().__init__(message)
class Book:
def __init__(self, title, page_count):
self.title = title
self.page_count = page_count
self.pages_read = 0
def read(self, pages):
if self.pages_read... | magicoder | python |
You are tasked with implementing a Java class to handle encryption and decryption of sensitive data using the AES-256 algorithm. Your class should provide methods for encrypting and decrypting strings using a secret key. The encryption and decryption methods should be secure and efficient, ensuring that sensitive infor... | ```java
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.util.Base64;
public class AES256 {
private static final String SECRET_KEY = "your_secret_key_here"; // Replace with your secret key
public static String encrypt(String plaintext) {
try {
... | magicoder | java |
You are tasked with creating a Python class to manage employee leave requests. The class should have the following functionalities:
1. Add a new leave request with the following attributes: employee name, type of leave, start date, end date, and any additional notes.
2. Retrieve all leave requests for a specific employ... | ```python
from datetime import datetime
class LeaveRequest:
def __init__(self, employee_name, leave_type, start_date, end_date, notes):
self.employee_name = employee_name
self.leave_type = leave_type
self.start_date = start_date
self.end_date = end_date
self.notes = notes
c... | magicoder | python |
You are tasked with implementing a benchmarking system for two different cryptographic signature schemes: threshold_crypto and ECDSA. The code snippet provided initializes a `SignatureIdentifier` and a data payload, and then proceeds to benchmark the signing process for both signature schemes using the Rust Criterion l... | ```rust
use criterion::{Criterion, BenchmarkId};
fn compare_signature_schemes(signer_pairing: &SignerPairing, signer_ecdsa: &SignerEcdsa, data: &[u8]) -> String {
let mut criterion = Criterion::default();
criterion.bench_function("threshold_crypto Sign Share", |b| {
b.iter(|| signer_pairing.sign(data,... | magicoder | rust |
You are tasked with creating a Python class that implements a simple strategy for a game. The game involves moving through a grid and collecting rewards at each cell. The strategy class should determine the next move based on the current position and the rewards at neighboring cells.
Your task is to complete the imple... | ```python
class SimpleStrategy(Strategy):
def next_move(self, grid, position):
row, col = position
max_reward = -1
next_position = position
# Check neighboring cells for the highest reward
for dr, dc in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
new_row, new_col = row +... | magicoder | python |
You are tasked with implementing a function that calculates the total number of unique ways to reach the top of a staircase. You can climb the staircase by either taking one step or two steps at a time. The function should take the total number of steps in the staircase as input and return the total number of unique wa... | ```swift
func climbStairs(_ n: Int) -> Int {
if n <= 2 {
return n
}
var dp = Array(repeating: 0, count: n + 1)
dp[1] = 1
dp[2] = 2
for i in 3...n {
dp[i] = dp[i - 1] + dp[i - 2]
}
return dp[n]
}
```
The `climbStairs` function uses dynamic programming to ef... | magicoder | swift |
You are tasked with creating a custom annotation processor for a Java application that uses Jackson XML library for serialization and deserialization. Your goal is to implement a processor that generates XML element names based on the field names of a Java class.
Given the provided code snippet, you need to create a c... | ```java
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
impor... | magicoder | java |
You are tasked with creating a Python program that processes a given directory and its subdirectories to identify and list all files that have been modified within a specified time range. You will need to utilize the `os` module to traverse the directory structure and obtain file information, as well as the `time` modu... | ```python
import os
import time
from plaso.parsers import manager
def list_modified_files(directory_path, start_time, end_time):
modified_files = []
for root, _, files in os.walk(directory_path):
for file in files:
file_path = os.path.join(root, file)
modification_time = os.pat... | magicoder | python |
You are tasked with creating a Rust program to interact with a cryptocurrency exchange API. The API provides a method `time` to retrieve the current timestamp and a data structure `Status` to represent the status of the exchange.
Your task is to implement a Rust program that uses the provided code snippet as a startin... | ```rust
use serde::{Deserialize, Serialize};
use std::error::Error;
// Placeholder for the Time struct
struct Time;
// Placeholder for the API client
struct APIClient;
impl APIClient {
async fn get(&self, endpoint: &str, params: ()) -> Result<Time, Box<dyn Error>> {
// Placeholder for making the API requ... | magicoder | rust |
You are tasked with implementing a factory design pattern for creating different parts of a complex object. The given code snippet demonstrates the usage of the factory pattern to create parts for floating-point and integer numbers.
Your task is to create a generic factory class that can be used to produce various par... | ```java
import java.util.HashMap;
import java.util.Map;
// Interface for part factory
interface PartFactory<T> {
T createPart();
}
// Generic factory class
public class GenericPartFactory {
private Map<Class<?>, PartFactory<?>> factories = new HashMap<>();
// Register a part factory for the specified typ... | magicoder | java |
You are tasked with implementing a Python generator function that yields all possible paths in a given graph from a start node to an end node. The graph is represented as an adjacency list, where each key-value pair represents a node and its adjacent nodes. The graph is directed and acyclic.
Your task is to implement ... | ```python
def generate_paths(graph, start, end):
def dfs(current, path, visited):
visited.add(current)
path.append(current)
if current == end:
yield path
else:
for neighbor in graph[current]:
if neighbor not in visited:
yiel... | magicoder | python |
You are tasked with implementing a custom deformable convolutional layer in PyTorch for a computer vision project. Deformable convolutions are a type of convolutional layer that can adaptively adjust their sampling locations for each input position. This allows the network to better handle geometric transformations and... | ```python
import torch
import torch.nn as nn
import torch.nn.functional as F
class DeformableConv2D(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True):
super(DeformableConv2D, self).__init__()
self.offset_conv = nn.Conv2d(in_... | magicoder | python |
You are tasked with implementing a database connection manager for a Discord bot using Python. The `DB` class is a part of the `commands.Cog` module, which is used for organizing and grouping commands in a Discord bot. Your goal is to complete the `dbConnect` method within the `DB` class to establish a connection to a ... | ```python
import datetime as dt
import psycopg2 # Assuming PostgreSQL database, import the appropriate database library
class DB(commands.Cog):
def __init__(self, bot):
self.bot = bot
def dbConnect(self):
try:
# Database connection details
hostname = 'your_hostname'
... | magicoder | python |
You are tasked with implementing a call log processing system that can efficiently handle and analyze call records. Each call record contains the following information: caller_phone_number, destination_phone_number, record_timestamp, and duration. The call records are stored in a CSV file with the following format:
``... | ```python
import csv
from datetime import datetime
def total_duration_to_destination(csv_file: str, destination_number: str, start_time: str, end_time: str) -> int:
total_duration = 0
start_datetime = datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S")
end_datetime = datetime.strptime(end_time, "%Y-%m-%d %H... | magicoder | python |
You are tasked with implementing a Java method to serialize and deserialize a custom data structure into a JSON array. The data structure represents a position in a 3D space with additional orientation information. The provided code snippet demonstrates the serialization part of the process, where the position coordina... | ```java
import org.json.JSONArray;
public class PositionDataSerializer {
public static JSONArray serializePositionData(PositionData positionData) {
JSONArray json = new JSONArray();
if (positionData.getDimensionType() != null) {
json.put(positionData.getX());
json.put(positi... | magicoder | java |
You are tasked with implementing a custom table view cell for displaying order information in an iOS app. The provided code snippet is a part of the custom table view cell class `NotPayOrderTableViewCell`. The cell has a property `order` of type `Order`, and a method `upDataUi()` is called whenever the `order` property... | ```swift
class NotPayOrderTableViewCell: UITableViewCell {
// ... (other properties and methods)
var order: Order! {
didSet {
upDataUi()
}
}
func upDataUi() {
// Assuming there are outlets for labels in the cell for displaying order information
... | magicoder | swift |
You are tasked with implementing a method for collecting and resolving subtypes in a Java application. The method should take in an annotated member or class, a mapper configuration, and an annotation introspector, and return a collection of named types representing the resolved subtypes.
Your task is to implement the... | ```java
import com.fasterxml.jackson.databind.introspect.AnnotatedMember;
import com.fasterxml.jackson.databind.introspect.AnnotatedClass;
import com.fasterxml.jackson.databind.cfg.MapperConfig;
import com.fasterxml.jackson.databind.introspect.AnnotationIntrospector;
import com.fasterxml.jackson.databind.introspect.Nam... | magicoder | java |
You are tasked with creating a Python function that simulates the creation of a new superuser in a web application. The function should take in the email address of the superuser and return a string indicating the success or failure of the creation process.
The function signature should be:
```python
def create_new_su... | ```python
from django.contrib.auth import get_user_model
def create_new_superuser(email: str) -> str:
try:
get_user_model().objects.create_superuser(email, '<password>') # Replace '<password>' with the desired password
return "Superuser created successfully"
except Exception as e:
retu... | magicoder | python |
You are given a file containing a list of coordinates in the format "x, y -> x, y". Each line in the file represents a pair of coordinates. Your task is to read the file, parse the coordinates, and then calculate the distance between each pair of coordinates. The distance between two points (x1, y1) and (x2, y2) is giv... | ```python
import math
def calculate_distance(coord1, coord2):
x1, y1 = coord1
x2, y2 = coord2
return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
inputFile = open(FILENAME, 'r')
Coords = []
for line in inputFile:
coords = [int(y) for x in line.strip().split(' -> ') for y in x.split(',')]
Coords.append([... | magicoder | python |
You are tasked with implementing a function to process and manipulate geographical coordinates for a navigation application. The function should take a list of latitude and longitude coordinates and return the total distance traveled along the path defined by these coordinates. The distance should be calculated using t... | ```java
import java.util.List;
public class DistanceCalculator {
private static final double EARTH_RADIUS = 6371; // in kilometers
public double calculateTotalDistance(List<Double> latitudes, List<Double> longitudes) {
double totalDistance = 0;
for (int i = 0; i < latitudes.size() - 1; i++) {
... | magicoder | java |
You are tasked with creating a Python function that processes a given application name and version to generate a unique identifier. The unique identifier should be created by removing spaces from the application name and appending the application version. The function should handle any input errors and return the uniqu... | ```python
def generate_unique_identifier(app_name: str, app_version: str) -> str:
# Remove leading/trailing spaces from app_name
app_name = app_name.strip()
# Validate app_version format
if not all(part.isdigit() for part in app_version.split('.')):
raise ValueError("Invalid app version for... | magicoder | python |
You are tasked with implementing a text classification system using various machine learning algorithms. The given code snippet shows a part of the training process for different classifiers. Your task is to create a function that evaluates the performance of these classifiers and selects the best one based on the accu... | ```python
from sklearn import metrics
def select_best_classifier(X_train, y_train, X_test, y_test) -> str:
classifiers = [
"svm_unigram",
"svm_bigram",
"top_tfidf",
"naive_bayes_unigram",
"svm_gridsearch"
]
best_accuracy = 0.0
best_classifier = ""
for classi... | magicoder | python |
You are tasked with designing a task scheduling system for a library management application. The system needs to manage various tasks related to resetting the library, updating recently opened libraries, loading tags, and asynchronously loading authors. Each task is represented as a lambda expression that enqueues a sp... | To implement the task scheduling system, you can use a combination of asynchronous programming constructs such as async/await and Task Parallel Library (TPL) to manage the execution of tasks in the specified sequence. Below is a sample solution using C#:
```csharp
using System;
using System.Collections.Generic;
using ... | magicoder | csharp |
You are tasked with implementing a class to manage a collection of amino acids. An amino acid is represented by a single-letter code according to the IUPAC-IUBMB Joint Commission on Biochemical Nomenclature (JCBN) standard. Your task is to create a class `AminoAcidFactory` with the following requirements:
1. Implement... | ```java
import java.util.HashMap;
import java.util.Map;
public class AminoAcidFactory {
private Map<Character, AminoAcid> letterToAminoAcid;
private Map<String, AminoAcid> abbreviationToAminoAcid;
public AminoAcidFactory() {
letterToAminoAcid = new HashMap<>();
abbreviationToAminoAcid = ne... | magicoder | java |
You are tasked with implementing a custom `InstantiationAwareBeanPostProcessor` in a Spring application. The `InstantiationAwareBeanPostProcessor` interface provides callback methods that allow for custom modification of new bean instances before and after instantiation. Your task is to create a class that implements t... | ```java
import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBean... | magicoder | java |
You are tasked with implementing a class that represents a simple shopping cart. The shopping cart should be able to store items, calculate the total cost of all items, and apply discounts based on the quantity of specific items.
Create a class `ShoppingCart` with the following requirements:
- It should have a method ... | ```csharp
using System;
using System.Collections.Generic;
using System.Linq;
public class ShoppingCart
{
private List<(string itemName, double price, int quantity)> items;
public ShoppingCart()
{
items = new List<(string itemName, double price, int quantity)>();
}
public void AddItem(stri... | magicoder | csharp |
You are tasked with creating a program that reads a PDF file and extracts specific information from it. The PDF file contains a list of products with their names, prices, and quantities. Your program needs to extract this information and calculate the total value of the products in the PDF.
You are given a code snippe... | ```csharp
using Spire.Pdf;
using System;
using System.Linq;
namespace PDFProductExtractor
{
class Program
{
static void Main(string[] args)
{
string pdfFilePath = "path_to_your_pdf_file.pdf"; // Replace with the actual path to the PDF file
// Load the PDF document
... | magicoder | csharp |
You are tasked with creating a command-line utility that checks for the existence of a specific command and returns a status code based on its presence. Your program should take the command name as input and return 0 if the command exists, and 1 if it does not. You are not allowed to use any built-in functions or libra... | ```python
import subprocess
def checkCommandExistence(commandName):
try:
subprocess.check_output(['which', commandName])
return 0 # Command exists
except subprocess.CalledProcessError:
return 1 # Command does not exist
```
The `checkCommandExistence` function uses the `subprocess` mo... | magicoder | python |
You are tasked with implementing a program to simulate a game board for a two-player game. The game board consists of a grid of cells, each of which can be in one of two states: white or black. The initial state of the board is determined by a series of commands that specify the color and arrangement of cells.
The pro... | ```python
def initialize_board(commands):
def draw_rect(command):
count, color, direction = int(command[0]), command[1], command[-1]
if direction == 'h':
return [(color * count), (color * count)]
else:
return [color * count] * count
board = []
for cmd in comm... | magicoder | python |
You are working on a file manipulation script that involves creating and populating files with specific content. The script snippet provided below demonstrates the creation and population of files using the `echo` and `cat` commands.
Your task is to write a Bash script that automates the creation and population of the... | ```bash
#!/bin/bash
# Define the variables
FILE_04="file-04"
FILE_05="file-05"
FILE_06="file-06"
FILE_08="file-08"
FILE_09="file-09"
TESTDIR="/path/to/testdir"
# Create and populate file-04
echo -n "ABCDEFGHIJKLMNOPQRSTUVWXYZ" > "$FILE_04"
# Create and populate file-05
echo "0123456789" > "$FILE_05"
# Create and po... | magicoder | shell |
You are tasked with writing a script to automate the setup of build environments for different programming languages on a Cray supercomputer. The script should parse a configuration file and set the appropriate environment variables based on the specified modules and compiler paths.
The configuration file contains a s... | ```bash
#!/bin/bash
# Execute the "module list" command to display the currently loaded modules
run "module list"
# Set the environment variables CC, CXX, and FC to the paths of the C, C++, and Fortran compilers
CC=$(which cc)
CXX=$(which CC)
FC=$(which ftn)
export CC CXX FC
# Handle the case where no build environm... | magicoder | shell |
You are tasked with implementing a Python function that processes a JSON request and updates a resource using the provided data. The function receives a JSON request containing a data transformation, and it is expected to update the resource with the provided transformation. The code snippet provided is a part of the f... | ```python
def update_resource(id, user, data_transformation):
"""
Update the resource with the provided data transformation.
:param id: The ID of the resource to be updated.
:param user: The user performing the update.
:param data_transformation: The data transformation to be applied to the resourc... | magicoder | python |
You are working on a project that involves converting Russian street addresses from their abbreviated form to their full form. In Russian addresses, street types are often abbreviated, such as "пер" for "переулок" (lane) and "пл" for "площадь" (square). Your task is to write a function that takes a dictionary of abbrev... | ```python
def convert_addresses(abbreviations: dict, addresses: list) -> list:
full_addresses = []
for address in addresses:
full_address = abbreviations.get(address, address) # If the address is not in the dictionary, use the original address
full_addresses.append(full_address)
return full... | magicoder | python |
You are tasked with creating a Python function that simulates a simplified file system and tests the functionality of a given command execution. The function will take in a username and user ID and execute a command to retrieve the user's ID, current working directory, and username. The function should then validate th... | ```python
import os
import subprocess
import tempfile
def validate_user_info(username: str, userid: str) -> bool:
try:
# Create a temporary directory
tmpdir = tempfile.mkdtemp()
# Execute command to retrieve user info and store output in files
subprocess.run(['bash', '-c', 'id -u >... | magicoder | python |
You are tasked with creating a program to manage alarms in a control system. The program should allow users to add, remove, and display alarms. Each alarm has a unique name and a corresponding time at which it is set to go off. The program should also provide the functionality to check if a specific alarm is currently ... | ```python
class AlarmManager:
def __init__(self):
self.alarms = {}
def add_alarm(self, name, time):
self.alarms[name] = time
def remove_alarm(self, name):
if name in self.alarms:
del self.alarms[name]
def display_alarms(self):
print("Alarms:")
for n... | magicoder | python |
You are tasked with creating a custom error handling module in Rust. Your goal is to implement a custom error type and a result type that can be used throughout a larger Rust project. The provided code snippet is the beginning of the module, which includes the definition of the module, the error module, and the re-expo... | ```rust
pub mod error {
use std::fmt;
#[derive(Debug)]
pub enum CustomError {
FileError(String),
NetworkError(String),
}
impl fmt::Display for CustomError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
CustomError::FileErro... | magicoder | rust |
You are tasked with creating a program that simulates a simple banking system. The program should be able to handle basic banking operations such as account creation, depositing funds, withdrawing funds, and checking the account balance.
Your task is to implement a class `BankAccount` with the following specifications... | ```python
class BankAccount:
def __init__(self, account_holder):
self._account_holder = account_holder
self._balance = 0
def deposit(self, amount):
self._balance += amount
def withdraw(self, amount):
if self._balance >= amount:
self._balance -= amount
el... | magicoder | python |
You are tasked with implementing a program to parse and analyze server access log files. The log files contain entries for each request made to the server, including details such as the request method, requested URL, response status code, and timestamp. Your program needs to extract and process this information to gene... | ```python
import re
def parse_log_entry(log_entry: str) -> dict:
pattern = r'^(?P<remote_host>\S+) - (?P<user_name>\S+) \[(?P<timestamp>.*?)\] "(?P<request_method>\S+) (?P<request_url>\S+) (?P<request_protocol>.*?)" (?P<response_status_code>\d+) (?P<response_size>\S+)$'
match = re.match(pattern, log_entry)
... | magicoder | python |
You are tasked with implementing a simple snake game using Python. The game will be played on a grid, and the snake will move around the grid, consuming food to grow longer. The objective is to implement the logic for the snake's movement, food generation, and collision detection.
Your task is to implement the `SnakeG... | ```python
import matplotlib.pyplot as plt
import random
class SnakeGame:
def __init__(self, width, height):
self.width = width
self.height = height
self.grid = [[0 for _ in range(width)] for _ in range(height)]
self.snake = [(0, 0)] # Snake starts at the top-left corner
sel... | magicoder | python |
You are tasked with implementing a simplified version of a RESTful API framework in Python. The framework should support adding resources, retrieving available resources, and getting all objects of a specific resource.
You are provided with a basic code snippet that demonstrates the usage of the API framework. Your ta... | ```python
class APIFramework:
def __init__(self):
self.resources = {}
def add_resource(self, resource_name):
if resource_name not in self.resources:
self.resources[resource_name] = []
def resources(self):
return list(self.resources.keys())
def get(self, resource_na... | magicoder | python |
You are tasked with creating a Python function that processes a list of filenames and returns a dictionary containing the count of unique file extensions present in the list. The function should ignore case sensitivity when comparing file extensions.
The function should be named `count_file_extensions` and should take... | ```python
import os
def count_file_extensions(filenames):
extension_counts = {}
for filename in filenames:
_, ext = os.path.splitext(filename)
ext = ext.lower() # Convert the extension to lowercase for case-insensitive comparison
if ext:
ext = ext[1:] # Remove the leading ... | magicoder | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.