query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with creating a program to manage a collection of websites. Each website is represented by a `Website` struct with the following properties:
- `title`: a string representing the title of the website
- `originalURL`: a URL object representing the original URL of the website
- `resolvedURL`: a URL object r... | ```swift
class WebsiteController {
func createWebsite(_ website: Website) -> Result<Website, Error> {
// Simulate the creation of the website (replace with actual implementation)
// For demonstration purposes, assume the website creation is successful
return .success(website)
}
}
```
In... | magicoder | swift |
You are tasked with creating a script to handle the generation and validation of signed certificates for a secure communication system. The script should take a certificate name as input and perform the following steps:
1. Check if the certificate name is valid.
2. If the certificate name is valid, generate a signed c... | ```bash
#!/bin/bash
# Function to generate a signed certificate for the given certificate name
generate_signed_certificate() {
local cert_name=$1
# Check if the certificate name is valid
if is_valid_certificate_name "${cert_name}"; then
# Generate the signed certificate
# Replace the follo... | magicoder | shell |
You are tasked with creating a shell script that reads environment variables from a file and performs specific operations based on the values of those variables. The script should be able to handle various scenarios and provide appropriate feedback to the user.
Write a shell script named `env_processor.sh` that accomp... | ```bash
#!/bin/sh
ME=$(basename $0)
# Check if .env file exists
if [ ! -f .env ]; then
echo "Error: .env file not found"
exit 1
fi
# Read environment variables from .env file
. ./.env
# Check for required variables and perform actions
if [ -z "$DB_HOST" ]; then
echo "Error: DB_HOST is missing or empty"
... | magicoder | shell |
You are tasked with implementing a function that parses a given JSON-like string and extracts specific information based on the provided keys. The JSON-like string contains key-value pairs, where the keys are enclosed in double quotes and followed by a colon, and the values can be strings, numbers, objects, or arrays. ... | ```python
from typing import List, Dict, Union
import json
def parseJSON(json_string: str, keys: List[str]) -> Dict[str, Union[str, int, bool, Dict[str, Union[str, int, bool]]]]:
result = {}
try:
parsed_json = json.loads(json_string)
for key in keys:
if key in parsed_json:
... | magicoder | python |
You are tasked with implementing a version comparison function that takes two version strings as input and returns whether the first version is greater than, equal to, or less than the second version. A version string is a series of numbers separated by periods, such as "1.2.3". The function should follow the semantic ... | ```python
def compare_versions(version1: str, version2: str) -> str:
v1 = list(map(int, version1.split('.')))
v2 = list(map(int, version2.split('.')))
for i in range(max(len(v1), len(v2))):
num1 = v1[i] if i < len(v1) else 0
num2 = v2[i] if i < len(v2) else 0
if num1 > ... | magicoder | python |
You are tasked with implementing a custom iterator class in JavaScript. The iterator should be able to iterate over a given array and provide the functionality to subscribe and unsubscribe from the iteration process.
Your task is to complete the implementation of the `CustomIterator` class, which should have the follo... | ```javascript
// Test the CustomIterator class
const array = [1, 2, 3, 4, 5];
const iterator = new CustomIterator(array);
// Subscribe to the iterator
const callback1 = item => console.log(`Subscriber 1 received: ${item}`);
const callback2 = item => console.log(`Subscriber 2 received: ${item}`);
iterator.subscribe(cal... | magicoder | javascript |
You are tasked with creating a Python command-line tool for processing RINEX (Receiver Independent Exchange Format) navigation and observation files. The tool should support various functionalities such as file conversion, data visualization, and data filtering based on user-defined criteria.
Your task is to implement... | ```python
import argparse
import georinex as gr
def process_rinex_files():
parser = argparse.ArgumentParser(description="Example of reading RINEX 2/3 Navigation/Observation file")
parser.add_argument("indir", help="Path to RINEX 2 or RINEX 3 files to convert")
parser.add_argument("glob", help="File glob pa... | magicoder | python |
You are tasked with implementing a method to read test coverage data from a file and calculate the total coverage percentage. The test coverage data is stored in a binary file in the following format:
- The first 4 bytes represent an integer indicating the number of elements in the coverage array.
- The subsequent byte... | ```java
import java.io.*;
public class TestCoverageReader {
public static double CalculateCoveragePercentage(String filePath) throws IOException {
try (FileInputStream fis = new FileInputStream(filePath);
DataInputStream dis = new DataInputStream(fis)) {
int numElements = dis.readI... | magicoder | java |
You are tasked with creating a Python function that calculates the total number of possible connections between buses in an electrical network. The network is represented using the `pandapower` library, which provides functions for creating and managing power systems.
You are given a code snippet that creates an empty... | ```python
import pandapower as pp
def calculate_total_connections(net):
num_buses = len(net.bus)
total_connections = num_buses * (num_buses - 1) # Total possible connections between buses
for i in range(num_buses):
for j in range(i + 1, num_buses):
if pp.get_connected_elements(net, ele... | magicoder | python |
You are given a code snippet that defines constants in a Rust program related to finite field arithmetic. Your task is to implement a function that performs a specific operation on elements of the finite field.
You are provided with the following information:
- `Fq` represents an element of a finite field.
- `Fq3` rep... | ```rust
fn frobenius_map(a: Fq3) -> Fq3 {
let mut result = Fq3::default();
result.c0 = a.c0.pow(Fq::char());
result.c1 = a.c1.pow(Fq::char());
result.c2 = a.c2.pow(Fq::char());
result
}
```
In the solution, we define the `frobenius_map` function that takes an element `a` of the extension field `Fq3... | magicoder | rust |
You are tasked with implementing a Python function that calculates the area of a circle using numerical integration. The function should take the radius of the circle as an input and return the area.
You are provided with the following code snippet as a reference for the integration process:
```python
{"type":"eq","f... | ```python
import numpy as np
from scipy.integrate import quad
def func_radius(x, radius):
return np.sqrt(radius**2 - x**2)
def calculate_circle_area(radius):
area, _ = quad(func_radius, -radius, radius, args=(radius))
return 2 * area # Multiply by 2 to account for the area in both halves of the circle
#... | magicoder | python |
You are tasked with creating a program that automates the process of generating unique usernames for a given service. The usernames should be retrieved from a secure vault using an API call and should follow a specific format. Your program should allow for a maximum number of retries and a sleep time between retries to... | ```python
import requests
import time
def generate_username(service_name, max_retries, sleep_time):
vault_url = "https://vault:8200/v1/sys/tools/random/32"
token = open('/run/secrets/token', 'r').read().strip()
ca_cert = '/run/secrets/ca'
for _ in range(max_retries):
try:
respo... | magicoder | python |
You are tasked with implementing a function to perform round trip sanity checks on incomplete gamma values. The incomplete gamma function, denoted as Γ(a, x), is a special function used in mathematics and statistics to calculate the integral of the gamma probability density function. The function takes two parameters, ... | ```cpp
#include <iostream>
#include <cmath>
#include "igamma_small_data.ipp"
#include "igamma_big_data.ipp"
template <typename T>
void do_test_gamma_2(const std::vector<std::pair<T, T>>& data, const std::string& name, const std::string& description) {
std::cout << "Performing round trip sanity checks for " << name... | magicoder | cpp |
You are working on a project that involves processing and organizing datasets for a machine learning application. The given code snippet is part of a larger program that handles the storage and manipulation of datasets. The code snippet is responsible for updating and managing various data structures related to the dat... | ```python
def update_datasets(datasets_f, datasets_l, cont, progress_cams, datasets_s, cam_video_count, amount_datas, predictions, truth, nb_datas, cam, classe):
datasets_f[classe][cam][cont[classe][cam]:cont[classe][cam]+amount_datas, :] = predictions
datasets_l[classe][cam][cont[classe][cam]:cont[classe][cam]... | magicoder | python |
You are tasked with implementing a sparse reshape operation for a neural network framework. The sparse reshape operation takes three inputs: `input_indices`, `input_shape`, and `new_shape`. The `input_indices` is a 2D array representing the indices of the sparse tensor, `input_shape` is a 1D array representing the orig... | ```python
import numpy as np
class SparseReshape:
@staticmethod
def infer(sparse_reshape_node):
input_indices = sparse_reshape_node.in_node(0).value
input_shape = sparse_reshape_node.in_node(1).value
new_shape = sparse_reshape_node.in_node(2).value
if -1 in new_shape:
... | magicoder | python |
You are tasked with creating a class to manage IT certification artifacts. The class, named `ITCC`, should have a method `generate_artifact` that takes in a certification name and returns the artifact in the format "Certification: [certification_name] Artifact". Additionally, the class should have a method `validate_ar... | ```python
class ITCC:
def generate_artifact(self, certification_name):
return f"Certification: {certification_name} Artifact"
def validate_artifact(self, artifact):
return artifact.startswith("Certification:")
# Test case for the generate_artifact method
def test_generate_artifact(self):
i... | magicoder | python |
You are tasked with implementing a ProviderFactory class that can dynamically create instances of different provider classes based on the provider name passed to it. The ProviderFactory class should have a method called provider, which takes a string parameter representing the provider name and returns an instance of t... | ```php
// Define the ProviderContract interface
interface ProviderContract {
public function send(string $message): bool;
}
// Implement the EmailProvider class
class EmailProvider implements ProviderContract {
public function send(string $message): bool {
// Implement email sending logic here
... | magicoder | php |
You are tasked with creating a web application form for users to input server details. The form should include fields for the server's IP address and port number. Additionally, the form should include validation to ensure that both fields are required and cannot be left empty. You are provided with a code snippet that ... | ```python
from wtforms import Form, StringField, SubmitField
from wtforms.validators import InputRequired
from flask import Flask, render_template, request
class ServiceForm(Form):
server = StringField(label="IP server", validators=[InputRequired(message='IP server is required')])
port = StringField(label="Por... | magicoder | python |
You are tasked with implementing a function that reads data from program memory in an embedded system using the AVR architecture. The AVR architecture, commonly used in microcontrollers, provides a special memory space called program memory, which stores the program code and read-only data. In AVR programming, the `avr... | ```c
#include <stdint.h>
#ifdef __AVR__
#include <avr/pgmspace.h>
#endif
uint8_t readFromProgramMemory(const uint8_t* address) {
#ifdef __AVR__
return pgm_read_byte(address);
#else
return *address;
#endif
}
```
The solution defines the function `readFromProgramMemory` that takes a pointer to `uint8_t` as its... | magicoder | c |
You are tasked with implementing a configuration parser for a data transformation pipeline. The configuration file contains a set of rules for transforming input data into a desired output format. Each rule consists of a transformation function and its associated parameters. Your task is to write a Python function that... | ```python
def parse_config_file(config_file_path: str) -> dict:
with open(config_file_path, 'r') as file:
lines = file.readlines()
config_dict = {}
current_rule = None
for line in lines:
line = line.strip()
if line.startswith('[') and line.endswith(']'):
current_rule... | magicoder | python |
You are tasked with implementing a custom transformer encoder for natural language processing using PyTorch. The transformer encoder will be used to process input sequences and generate contextualized representations for each token in the sequence. Your task is to create a class that inherits from the `TransformerTorch... | ```python
import torch
from .transform_encoder import TransformerTorchEncoder
class CustomTransformerEncoder(TransformerTorchEncoder):
def __init__(self, input_dim, hidden_dim, num_layers, num_heads, dropout_prob):
super(CustomTransformerEncoder, self).__init__()
self.transformer_layer = torch.nn.T... | magicoder | python |
You are tasked with implementing a simple application framework for a model-view-controller (MVC) architecture. The provided code snippet is a part of the application's entry point, where the `App::start` function is called with four arguments: the application name, the model initialization function `model::init`, the ... | ```python
# App class for MVC architecture
class App:
@staticmethod
def start(app_name, init_model, update_model, render_view):
model = init_model() # Initialize the model
updated_model = update_model(model) # Update the model
render_view(updated_model, app_name) # Render the view
# ... | magicoder | python |
You are tasked with implementing a function that calculates the total number of occurrences of a specific word in a given string. The function should be case-insensitive and should consider only whole word matches. A word is defined as a sequence of alphanumeric characters, delimited by non-alphanumeric characters or t... | ```typescript
export const countWordOccurrences = (text: string, word: string): number => {
const regex = new RegExp(`\\b${word}\\b`, 'gi');
const matches = text.match(regex);
return matches ? matches.length : 0;
};
```
In the solution, a regular expression is used to match the whole word occurrences of the spec... | magicoder | typescript |
You are tasked with creating a script to automate the packaging of a software application for the Debian package manager. The script should take various parameters and generate a Debian package (.deb) with the specified metadata and dependencies.
Your task is to write a Python function that takes the necessary paramet... | ```python
def generate_fpm_command(prefix, package_name, version, description, email, local_path):
fpm_command = f"fpm -s dir -t deb -n hifi-{prefix}{package_name} -v {version} -d hifiqt5.12.3 --vendor 'High Fidelity Inc' -m '{email}' " \
f"--url 'https://highfidelity.com' --license 'Apache Licens... | magicoder | python |
You are tasked with implementing a custom activity type provider and bookmark provider for a workflow management system. The system uses the `elsaOptions` and `services` objects to configure various activities and services. The `AddActivitiesFrom` method is used to add activities to the `elsaOptions`, while the `AddCon... | ```csharp
// Custom activity type provider for notifications.
public class NotificationActivityTypeProvider : IActivityTypeProvider
{
public void GetActivityTypes(ICollection<Type> activityTypes)
{
// Add the notification activity type to the collection.
activityTypes.Add(typeof(NotificationActi... | magicoder | csharp |
You are tasked with creating a function to remove a player from a space-themed game database. The function should also have an option to remove any associated planets. The game's database contains information about various resources, such as ore, organics, goods, and energy. The function should set the production of th... | ```php
function db_kill_player($ship_id, $remove_planets = false)
{
global $default_prod_ore;
global $default_prod_organics;
global $default_prod_goods;
global $default_prod_energy;
// Remove player from the database
// Implementation details depend on the database system used (e.g., SQL query)... | magicoder | php |
You are tasked with creating a Python script to manage the submission of Gaussian jobs for a set of molecular conformers. The script should handle the generation of input files for Gaussian, submission of jobs to a high-performance computing (HPC) cluster using SLURM, and potential restarts for failed jobs. Your task i... | To handle job restarts in Gaussian for missing conformers, you can use the following logic within the Python script:
```python
# TODO see if conditions are right to restart in Gaussian:
for cf_idx in missing_conformers:
restart_required = check_restart_conditions(cf_idx) # Check if restart is required for the cur... | magicoder | python |
You are tasked with implementing a Python function that processes a list of arguments and performs specific operations based on the type and content of each argument. The function should handle various data types and callable objects, and return the result of the operations as a list.
You are given a partial code snip... | ```python
import numpy as np
from astropy import coordinates as coord
def process_arguments(_args):
result = []
for arg in _args:
if isinstance(arg, (int, float)):
result.append(arg ** 2)
elif callable(arg):
result.append(arg())
elif isinstance(arg, list) and not... | magicoder | python |
You are tasked with implementing a function to load and compile a shader from a file using the given `Shader` struct and associated methods. The `Shader` struct has a method `new` that takes a reference to the OpenGL context (`gl::Gl`), a mutable reference to a file stream (`T: Read`), and the type of shader to create ... | ```rust
impl Shader {
pub fn new<T: Read>(gl: &gl::Gl, stream: &mut T, kind: ShaderType) -> Result<Self, GlError> {
// Read the entire file into the string
let mut source = String::new();
stream.read_to_string(&mut source).map_err(|e| GlError::IoError(e))?;
let source = CString::new(... | magicoder | rust |
You are tasked with implementing a method to generate an SQL query for adding a new record to a table called `UserFeedback`. The table has the following schema:
- `FeedbackID`: An unsigned integer of 11 digits, serves as the primary key and auto-increments.
- `UserID`: An unsigned integer of 11 digits, not null.
- `Fe... | ```java
@Override
protected String createAddSQL(String tableName, int userID, String name, String email, String subject, String feedbackText) {
String sql = "INSERT INTO " + tableName + " (UserID, FeedbackTimestamp, Name, Email, Subject, FeedbackText) VALUES (" +
userID + ", CURRENT_TIMESTAMP, " +
... | magicoder | java |
You are tasked with implementing a custom exception class for handling labeling operations on read replica nodes in a database system. The provided code snippet is a Java class definition for the exception `ReadReplicaNodeLabelingOperationException`. This exception is thrown when a labeling operation on a read replica ... | ```java
package com.atlassian.db.replica.internal.aurora;
public class ReadReplicaNodeLabelingOperationException extends RuntimeException {
public ReadReplicaNodeLabelingOperationException(String replicaId, Throwable cause) {
super("Failed to label a replica connection with replica id: " + replicaId, caus... | magicoder | java |
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. Additionally, users should be able to search for a book by its title or author. To implement this system, you need to define a... | ```java
import java.util.ArrayList;
import java.util.List;
class Book {
private String title;
private String author;
private boolean available;
public Book(String title, String author) {
this.title = title;
this.author = author;
this.available = true; // By default, a new book ... | magicoder | java |
You are tasked with creating a Python script to evaluate a machine learning model and generate an output CSV file. The script will take command-line arguments for the model file to be evaluated and the name of the output CSV file. The model file is usually of the form "model_X.pth", where X is a placeholder for the mod... | ```python
import torch
import argparse
import pandas as pd
# Argument parsing
parser = argparse.ArgumentParser(description='Model Evaluation Script')
parser.add_argument('--model', type=str, metavar='M',
help="the model file to be evaluated. Usually it is of the form model_X.pth")
parser.add_argume... | magicoder | python |
You are given a script and a corresponding voice recording. The script is represented as a list of strings `script_table`, where each element represents a segment of the script. Similarly, the voice recording is represented as a list of strings `voice_table`, where each element represents a segment of the voice recordi... | ```python
from typing import List
def reconstruct_voice(script_table: List[str], voice_table: List[str]) -> List[str]:
s_idx = 0
v_idx = 0
while s_idx < len(script_table) and v_idx < len(voice_table):
if len(script_table[s_idx]) > len(voice_table[v_idx]):
diff = len(script_table[s_idx])... | magicoder | python |
You are tasked with creating a script to calculate the checksum of multiple files and then sort the checksums in ascending order. You are given a code snippet as a starting point:
```bash
for FILE in ${FILES[@]}; do
echo $(checksum_file $FILE) >> $RESULT_FILE
done
# Now sort the file so that it is
sort $RESULT_FILE -... | ```bash
#!/bin/bash
# Function to calculate the checksum of a file
checksum_file() {
local file="$1"
md5sum "$file" | awk '{print $1}'
}
# Array of files
FILES=("file1.txt" "file2.txt" "file3.txt")
# Result file to store checksums
RESULT_FILE="checksums.txt"
# Calculate and store checksums
for FILE in "${FILES[... | magicoder | shell |
You are working on a project involving a device that utilizes a radio frequency (RF) module for communication. The code snippet provided is part of the firmware for this device. The snippet includes a function call, a configuration setting, and a debug print statement. Your task is to understand the context and purpose... | The code snippet provided is a part of the firmware for a device utilizing an RF module for communication. Let's analyze the different aspects of the code snippet:
1. `RxChainCalibration()`: This function call likely pertains to calibrating the receive chain of the RF module. It could involve adjusting parameters to o... | magicoder | python |
You are tasked with creating a program to validate and process mapping data for a software update. The mapping data consists of three JSON objects: `var1`, `var2`, and `var3`. The program should load a JSON file containing the mapping differences between two versions of the software and then perform validation and proc... | ```java
import com.google.gson.JsonObject;
public class MappingProcessor {
private int oldVersion;
private int newVersion;
public MappingProcessor(int oldVersion, int newVersion) {
this.oldVersion = oldVersion;
this.newVersion = newVersion;
}
public Mappings processMappingData() {... | magicoder | java |
You are given an array `arr` of length 2, where `arr[0]` represents a constant multiplier and `arr[1]` represents a threshold value. Additionally, you are given a positive integer `i`. Your task is to write a function or program that calculates the result based on the following logic:
1. Calculate the sum as the produ... | ```python
def calculate_result(arr, i):
sum_value = arr[0] * i
if sum_value <= arr[1]:
return 0
else:
return sum_value - arr[1]
# Example usage
arr = [3, 10]
i = 4
result = calculate_result(arr, i)
print(result) # Output: 2
``` | magicoder | python |
You are tasked with creating a script to automate the process of building and updating a software package. The script should perform the following steps:
1. Extract the contents of the `net-tools-CVS_20101030.tar.gz` file into a directory named `net-tools-CVS_20101030`.
2. Apply a patch named `net-tools-CVS_20101030-r... | ```bash
#!/bin/bash
# Step 1: Extract the contents of the net-tools-CVS_20101030.tar.gz file
rm -rf net-tools-CVS_20101030
tar xf net-tools-CVS_20101030.tar.gz
pushd net-tools-CVS_20101030
# Step 2: Apply the patch net-tools-CVS_20101030-remove_dups-1.patch
patch -Np1 -i ../net-tools-CVS_20101030-remove_dups-1.patch
... | magicoder | shell |
You are tasked with creating a program that processes HTML table data. Your program should read an HTML table from a file and extract specific information from it. The table will contain rows and columns, and you need to extract the content of a specific cell based on its row and column index.
You are given a sample H... | ```python
from bs4 import BeautifulSoup
def extractTableCell(file, row, column):
try:
with open(file, 'r') as html_file:
soup = BeautifulSoup(html_file, 'html.parser')
table = soup.find('table')
rows = table.find_all('tr')
if row < len(rows):
... | magicoder | python |
You are tasked with creating a Python function that simulates a simple game of dice. The game involves rolling two dice and summing the values obtained. The function should take an integer `n` as input and simulate rolling the dice `n` times. It should then return the frequency of each possible sum from 2 to 12 as a di... | ```python
import numpy as np
def simulate_dice_rolls(n: int) -> dict:
np.random.seed(19680801) # Set the random seed for reproducibility
results = np.random.randint(1, 7, size=(n, 2)) # Simulate rolling two dice 'n' times
sums = np.sum(results, axis=1) # Calculate the sum of each pair of dice
freque... | magicoder | python |
You are tasked with implementing a program to encrypt and decrypt messages using the Affine cipher. The Affine cipher is a type of monoalphabetic substitution cipher, where each letter in an alphabet is mapped to its numeric equivalent, encrypted using a simple mathematical function, and then converted back to a letter... | ```rust
fn modular_inverse(a: i32) -> Option<i32> {
for x in 1..26 {
if (a * x) % 26 == 1 {
return Some(x);
}
}
None
}
fn affine_encrypt(plaintext: &str, a: i32, b: i32) -> String {
let ciphertext: String = plaintext
.chars()
.filter(|&c| c.is_ascii_alphabeti... | magicoder | rust |
You are tasked with implementing a function that parses and processes a given CSS code snippet to extract and count the unique CSS properties used within it. Each property is defined as a key-value pair within the CSS code. The function should return a dictionary mapping each unique property to the number of times it a... | ```python
def count_css_properties(css_code: str) -> dict:
properties = {}
lines = css_code.split('\n')
for line in lines:
if ':' in line:
property_name = line.split(':')[0].strip()
if property_name in properties:
properties[property_name] += 1
els... | magicoder | python |
You are working on a static analysis tool that performs abstract interpretation on programs to infer properties about their behavior. In this context, you are given a code snippet that defines operations on linear expressions and intervals. Your task is to implement a specific operation for the static analysis tool.
Y... | ```cpp
static void apply(dom_t &dom, arith_operation_t op, varname_t x, varname_t y,
varname_t z) {
switch (op) {
case ADDITION: {
linexp_t x_expr = linexp_t(var_t(y)) + linexp_t(var_t(z)) - var_t(x);
dom += lincst_t(x_expr, lincst_t::EQUALITY);
break;
}
case SUBTRACTIO... | magicoder | cpp |
You are tasked with implementing a user management system for a web application. The system should allow for the retrieval and removal of user information from a session-based user database. The user information is stored as a dictionary in the session under the key 'user_db', with the user ID as the key and a dictiona... | ```python
class User:
@classmethod
def get(cls, user_id):
if 'user_db' in session:
if user_id in session['user_db']:
user = session['user_db'].get(user_id)
return User(user['id'], user['token'], user['email'], user['name'])
@classmethod
def clear(cls,... | magicoder | python |
You are tasked with implementing a function to process and analyze text data. The function will take in three parameters: `data`, `text`, and `height`. The `data` parameter represents an image, and the `text` parameter represents the text to be analyzed. The `height` parameter represents the height of the glyphs used i... | ```rust
use std::collections::HashMap;
// Function to prepare glyphs
fn prepare_glyphs(data: Data, text: &str, height: u32) -> (Image, Vec<Glyph>, (u32, u32)) {
// Implementation of prepare_glyphs function
// ...
// Return image, glyphs, glyphs_width, and glyphs_height
}
// Function to process and analyze... | magicoder | rust |
You are tasked with implementing a function that processes audio data and performs specific operations on it. The function takes in a list of WavData objects, a list of DsData objects, a directory path for the audio files, optional custom hyperparameters, and a callback function for saving processed data. The function ... | ```python
from typing import List, Optional, Dict, Callable
from pathlib import Path
class WavData:
wav_relative_path: str
class DsData:
pass
class WavDataList:
def items(self, flag: bool):
pass
class DsDataList:
def items(self, flag: bool):
pass
class TSTFTHParams:
pass
class ... | magicoder | python |
You are tasked with implementing a side effect detector in Java. A side effect is any modification of state that is observable outside the called function other than its return value. Your goal is to create a class `NoopSideEffectDetector` that implements the `SideEffectDetector` interface. The `SideEffectDetector` int... | ```java
import java.util.List;
public class NoopSideEffectDetector implements SideEffectDetector {
@Override
public boolean detectSideEffect(List<Runnable> runnables) {
for (Runnable runnable : runnables) {
SideEffectObserver observer = new SideEffectObserver();
runnable.run();
... | magicoder | java |
You are tasked with implementing a class that performs a full sort operation on a given tensor. The class should take in a tensor containing indices, a tensor containing values, and an axis along which to perform the sorting operation. Your task is to implement the `FullSortResult` class with the following specificatio... | ```cpp
#include <iostream>
#include <vector>
#include <algorithm>
// Define the snap::Tensor class for demonstration purposes
namespace snap {
class Tensor {
// Implementation of snap::Tensor class
};
}
class FullSortResult {
private:
snap::Tensor indices;
snap::Tensor values;
int axis;
p... | magicoder | cpp |
You are given a dataset `dt` containing information about black holes, including their masses and times. The dataset has the following columns: `GWtime`, `BWorldtime`, `Mass_0`, and `Mass_1`. Additionally, there are boolean index arrays `idxb0` and `idxb1` representing the indices of black holes, and boolean index arra... | ```python
import pandas as pd
def calculate_total_masses(dt, idxb0, idxb1, idxm0, idxm1):
all_bh_mass = pd.concat([dt[idxb0].Mass_0, dt[idxb1].Mass_1]).sum()
bound_bh_mass = pd.concat([dt[idxb0].Mass_0, dt[idxb1].Mass_1]).sum()
merging_bh_mass = pd.concat([dt[idxm0].Mass_0, dt[idxm1].Mass_1]).sum()
ret... | magicoder | python |
You are tasked with implementing a generic method for writing a value to a stack in a memory-efficient and performant manner. The method should utilize unsafe code to achieve this functionality. Your task is to write the implementation for the `WriteToStack` method, which takes a generic type `T` and a value of type `T... | ```csharp
using System;
using BenchmarkDotNet.Attributes;
using System.Runtime.CompilerServices;
public class StackWriterBenchmark<T>
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void WriteToStack(T value)
{
var stackPtr = stackalloc byte[Unsafe.SizeOf<T>()];
Unsafe.Wr... | magicoder | csharp |
You are tasked with implementing a simple command-line argument parser in C++ to handle the input arguments for a server gateway application. The gateway application is responsible for routing incoming requests to the appropriate server functions. The code snippet provided is the entry point of the application, where t... | ```cpp
#include <iostream>
#include <string>
#include <cstdlib>
namespace faas {
void GatewayMain(int argc, char* argv[]) {
int port = 0;
bool helpRequested = false;
for (int i = 1; i < argc; ++i) {
std::string arg = argv[i];
if (arg == "-p" || arg == "--port") {
... | magicoder | cpp |
You are tasked with implementing a binary tree data structure in Python. Your task is to create a method that populates a list with the IDs of all the leaf nodes in the binary tree.
You are given the following code snippet as a starting point:
```python
class TreeNode:
def __init__(self, value):
self.valu... | ```python
class TreeNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
self.leaf_node_ids = []
def add_leaf_node_ids(self):
if self.left is None and self.right is None:
self.leaf_node_ids.append(self.value)
if self.... | magicoder | python |
You are tasked with creating a program that performs a basic search of xkcd comics based on user input. The program should take a search string as input and then fetch and display the relevant xkcd comic links.
Your task is to implement a function `search_xkcd_comics(search_string)` that takes a search string as input... | ```python
import requests
import bs4
def search_xkcd_comics(search_string):
response = requests.get("http://derp.co.uk/xkcd/page?q=" + search_string + "&search=Search")
soup = bs4.BeautifulSoup(response.text, 'html.parser')
links = soup.select('a[target="_blank"]')
comic_links = [link['href'] for link ... | magicoder | python |
You are tasked with implementing a custom data structure that simulates a queue with additional functionality. The queue should support the standard enqueue and dequeue operations, as well as a method to get the minimum element currently in the queue. The minimum method should run in constant time, O(1).
You need to i... | ```python
from dataclasses import dataclass
from typing import Any, Deque
from collections import deque
@dataclass
class MinQueue:
elements: Deque[int] = field(default_factory=deque)
minimums: Deque[int] = field(default_factory=deque)
def enqueue(self, val: int) -> None:
self.elements.append(val)
... | magicoder | python |
You are tasked with implementing a function to calculate the dimensions and position of objects placed on a road. The function takes a list of objects, the road area, and a vector to store the calculated object dimensions. The function returns a boolean indicating success or failure. If successful and only one object d... | ```cpp
#include <vector>
struct ObjectDimensions {
// Define the structure to hold the dimensions of an object
// (e.g., width, height, depth, position, etc.)
};
bool calculateObjectDimensions(const std::vector<Object>& objects, const Area& roadArea, std::vector<ObjectDimensions>& objectDimensions) {
// I... | magicoder | cpp |
You are tasked with creating a Python function that processes a given image using TensorFlow and Keras. The function should load a pre-trained deep learning model, perform image preprocessing, make predictions on the image, and return the top predicted classes along with their probabilities.
You are provided with the ... | ```python
import os
import numpy as np
import tensorflow as tf
from tensorflow import keras
def process_image(image_path, model_path):
# Load the pre-trained model
model = keras.models.load_model(model_path)
# Load and preprocess the image
img = keras.preprocessing.image.load_img(image_path, target_si... | magicoder | python |
You are tasked with implementing a class to manage a set of data streams. The class, named `StreamManager`, should provide methods for acquiring and releasing streams, as well as retrieving pending items from the streams.
The `StreamManager` class has the following methods:
1. `acquire(max_streams)`: A method to acqui... | ```cpp
#include <vector>
#include <algorithm>
class StreamManager {
private:
std::vector<bool> streamAvailability;
std::vector<int> pendingItems;
public:
StreamManager(size_t numStreams) : streamAvailability(numStreams, true), pendingItems(numStreams, -1) {}
int acquire(size_t maxStreams) {
a... | magicoder | cpp |
You are working on a game development project where you need to implement a function to determine the color tint for different types of blocks based on their properties. The function takes in the block ID and the y-coordinate as input and returns the corresponding color tint for the block. The color tint is represented... | ```python
def get_color_tint(block_id, y, block_ignore):
tints = []
if block_id == 'grass':
if y > 0:
tints.append({'h':93, 's':39, 'l':10}) # Birch Leaves
else:
tints.append({'h':114, 's':64, 'l':22}) # Normal Leaves
elif block_id == 'ice':
tints.append({'h... | magicoder | python |
You are tasked with implementing a camera struct in C++ that supports both perspective and orthographic projections. The camera should have methods to initialize the perspective and orthographic projections, reset the camera, and modify the viewport size, zoom, and aspect ratio.
Your task is to complete the implementa... | ```cpp
#include <iostream>
struct Camera {
float near_plane;
float far_plane;
float fov_y;
float aspect_ratio;
float viewport_width;
float viewport_height;
float zoom;
bool is_perspective;
void init_perspective(float near_plane, float far_plane, float fov_y, float aspect_ratio) {
... | magicoder | cpp |
You are tasked with implementing a Python function that serves as a wrapper script for command-line R visualizations. The function takes in several parameters, including `whichway`, `name`, `id`, `target_onto`, `width`, `height`, `tabfile`, `feature_cluster_size`, and `sample_cluster_size`. Your goal is to create a fun... | ```python
import subprocess
def visualize_data(whichway=None, name=None, id=None, target_onto=None, width='5', height='5', tabfile=None, feature_cluster_size=2, sample_cluster_size=2):
# Construct the command for R visualization
command = f"Rscript visualize.R --whichway {whichway} --name {name} --id {id} --ta... | magicoder | python |
You are tasked with creating a Rust function that interacts with the Wasmtime runtime to execute WebAssembly (Wasm) code. Your goal is to implement a function that takes a list of arguments, runs the Wasmtime runtime with those arguments, and returns the output of the execution.
You are provided with a code snippet th... | ```rust
use std::path::Path;
use std::process::Command;
use tempfile::NamedTempFile;
fn run_wasmtime(args: &[&str]) -> Result<String, Box<dyn std::error::Error>> {
let mut me = std::env::current_exe()?;
me.pop(); // chop off the file name
// Create a temporary file to store the Wasm code
let wasm_file... | magicoder | rust |
You are tasked with creating a text-based adventure game using Python. The game will involve combat encounters, shields with different durability, and various events such as encountering a wizard or stumbling into a trap.
Your task is to implement a class called `Player` that represents the game's protagonist. The `Pl... | ```python
import random
class Player:
def __init__(self, shield_type, shield_durability):
self.shield_type = shield_type
self.shield_durability = shield_durability
def shield_type(self):
return self.shield_type
def shield_dur(self):
return self.shield_durability
def conti... | magicoder | python |
You are tasked with implementing a simulated annealing algorithm for optimizing a given search space. Simulated annealing is a probabilistic technique used for finding an approximate solution to an optimization problem. In this problem, you will need to complete the implementation of the `SimulatedAnnealingOptimizer` c... | ```python
import numpy as np
class SimulatedAnnealingOptimizer:
def __init__(self, search_space, rand_rest_p):
self.search_space = search_space
self.rand_rest_p = rand_rest_p
self.systems = []
def acceptance_probability(self, _p1_, _p2_, denom):
if denom == 0:
retur... | magicoder | python |
You are tasked with implementing a method in the `RemotesQueue` class that manages pending connections. The `RemotesQueue` class has a property `pendingConnections` which is a dictionary mapping connection IDs to `PendingConnection` objects. Each `PendingConnection` object has a `readyPromise` property, which is a prom... | ```typescript
import { EventEmitter } from 'events';
interface PendingConnection {
readyPromise: Promise<void>;
}
interface Dictionary<T> {
[key: string]: T;
}
export default class RemotesQueue {
private readonly events: EventEmitter;
private shiftingTimeout: Promise<void>;
private readonly pendi... | magicoder | typescript |
You are tasked with implementing a custom attribute class in C# that can be used to store line numbers and program counter values for a given method. The attribute should be able to be applied to methods within a class and store the line number and program counter value for each method. Additionally, you need to create... | ```csharp
using System;
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class LineNumberAttribute : Attribute
{
public int LineNumber { get; set; }
public int ProgramCounter { get; set; }
}
public class SampleClass
{
[LineNumberAttribute(LineNumber = 10, ProgramCounter = 100)]
... | magicoder | csharp |
You are working on a software packaging system called Mininix, which involves creating a function to handle the installation of source code. The `mininix_step_make_install` function is responsible for copying the contents of the `source` directory to the appropriate location within the Mininix system. However, the code... | ```bash
mininix_step_make_install(){
if [ -d "source" ] && [ "$(ls -A source)" ]; then
if cp -r source/* $MININIX_PREFIX/include/; then
echo "Installation successful"
else
echo "Error: Failed to copy files to $MININIX_PREFIX/include/"
# Add additional error handling and cleanup code as neede... | magicoder | shell |
You are tasked with implementing a stream encryption function using the XOR operation. The function `stream_encrypt_xor` takes three parameters: `input`, `nonce`, and `key`, and returns the encrypted data as a vector of unsigned 8-bit integers (bytes).
The `input` parameter is a slice of bytes representing the data to... | ```rust
const NONCE_BYTES: usize = 8;
const KEY_BYTES: usize = 16;
pub fn stream_encrypt_xor(input: &[u8], nonce: &[u8; NONCE_BYTES], key: &[u8; KEY_BYTES]) -> Vec<u8> {
// Perform compile-time length check for nonce and key
// Replace the runtime length check with a compile-time check
// This is achieved ... | magicoder | rust |
You are tasked with implementing a color picker component in a graphical user interface (GUI) application. The color picker should allow users to select a color using sliders and up/down controls for different color channels (e.g., red, green, blue). Additionally, the color picker should raise an event whenever the sel... | ```csharp
using System;
internal sealed class ColorPicker : Base
{
public delegate void ColorChangedEventHandler(ColorPicker sender, Color color);
private bool updateSlidersValuesOnColorChanged = true;
private bool updateUpDownsValuesOnColorChanged = true;
public event ColorChangedEventHandler ColorC... | magicoder | csharp |
You are working for a retail company that sells various products. Your task is to write a Python function to analyze the sales data stored in a pandas DataFrame. The DataFrame, named `df`, contains the following columns: `ProductID`, `ProductName`, `Quantity`, and `UnitPrice`. The `Quantity` column represents the numbe... | ```python
import pandas as pd
def calculate_total_sales(df):
# Calculate the total sales for each product
df['TotalPrice'] = df['Quantity'] * df['UnitPrice']
# Create a new DataFrame with unique product names and their total sales
total_sales_df = df.groupby('ProductName')['TotalPrice'].sum().rese... | magicoder | python |
You are tasked with simulating the response of a control system to a given plant model. The plant model is defined by the parameters L, R, and M, and the control system will be designed to regulate the output of this plant. The control system will be a proportional-integral-derivative (PID) controller, and you are requ... | ```python
import numpy as np
import matplotlib.pyplot as plt
# Plant model parameters
L = 0.1 # Inductance (in Henry)
R = 10.0 # Resistance (in Ohms)
M = 2.0 # Mass (in kg)
# PID controller parameters
Kp = 1.0 # Proportional gain
Ki = 0.1 # Integral gain
Kd = 0.01 # Derivative gain
# Simulation parameters
dt =... | magicoder | python |
You are working on a blogging platform and need to implement a feature to allow users to create, view, and edit their posts. The platform uses Django and Django REST framework for the backend. You have been provided with a code snippet from the backend codebase that includes imports related to the blog functionality. Y... | ```python
from rest_framework import generics
from rest_framework.permissions import IsAuthenticated
from blog.models import Post
from blog.serializers import PostSerializer
from blog.permissions import IsAuthorOrReadOnly
class PostListCreateView(generics.ListCreateAPIView):
queryset = Post.objects.all()
seria... | magicoder | python |
You are tasked with creating a Python function that simulates a simple game of dice. The game involves rolling two dice and summing the values. The function should take the number of rounds to play as input and return the frequency of each possible sum from 2 to 12 after the specified number of rounds.
The function si... | ```python
import random
def simulate_dice_game(rounds: int) -> dict:
frequencies = {i: 0 for i in range(2, 13)} # Initialize frequencies for sums 2 to 12 to 0
for _ in range(rounds):
dice1 = random.randint(1, 6) # Simulate rolling the first dice
dice2 = random.randint(1, 6) # Simulate rollin... | magicoder | python |
You are tasked with creating a script to automate the installation of Go packages and their dependencies. The script should parse a given input file containing package names and execute the necessary `go get` and `go install` commands to fetch and build the packages and their dependencies.
The input file will contain ... | ```bash
#!/bin/bash
# Read input file line by line
while IFS= read -r package; do
echo "---- Loading $package"
go get "$package"
echo "-------- Loaded $package"
done < input.txt
# Create pkg builds
cd string-distance
go install -v -gcflags "-N -l" ./...
cd ..
```
In this solution, we use a Bash script to read... | magicoder | shell |
You are given a string `S` consisting of lowercase English letters. Your task is to find all non-overlapping substrings in `S` that consist of at least three identical consecutive characters. For each such substring found, you need to output the starting and ending indices of the substring within the original string `S... | ```cpp
#include <iostream>
#include <vector>
using namespace std;
vector<vector<int>> findConsecutiveSubstrings(const string& S) {
vector<vector<int>> answer;
int start = -1;
char last = '\0';
for (int i = 0; i < S.size(); i++) {
if (S[i] == last) {
continue;
}
if (... | magicoder | cpp |
You are tasked with creating a Python program that processes and sends email messages using the `EmailMessage` class from the `email.message` module. Your program should read a list of recipient email addresses from a file, construct an email message with a specified subject and body, and then send the email to each re... | ```python
import smtplib
from email.message import EmailMessage
def read_recipients(filename):
try:
with open(filename, 'r') as file:
recipients = file.read().splitlines()
return recipients
except FileNotFoundError:
print(f"Error: File '{filename}' not found.")
retur... | magicoder | python |
You are tasked with creating a Python class that dynamically generates a serializer for Kubernetes objects. The serializer should inherit from a base serializer class and include specific fields based on the Kubernetes object being serialized.
Your task is to implement the `KubernetesMetadataObjBaseSerializer` class a... | ```python
class KubernetesMetadataObjBaseSerializer:
class Meta:
model = None # Placeholder for the model attribute
fields = ["metadata"] # Default fields for the base serializer
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
if cls.Meta.model is Non... | magicoder | python |
You are tasked with creating a custom command-line prompt for a developer's environment. The prompt should display the current Git branch and status, the current directory, and the time in a specific format. Additionally, the prompt should include a custom theme provided by the "pure" package.
Your task is to write a ... | ```bash
#!/bin/zsh
# Set up aliases
alias gl="git log"
alias p="cd $HOME/Projects"
# Load pure theme
autoload -U promptinit; promptinit
prompt pure
# Configure custom prompt
prompt_dir() {
prompt_segment blue black '%~'
}
prompt_git() {
local ref dirty
if $(git rev-parse --is-inside-work-tree &>/dev/null); th... | magicoder | shell |
You are tasked with implementing a custom iterator for a collection of items. The iterator should support removing elements from the collection while iterating through it. Additionally, the iterator should skip over elements based on a specified condition.
Your task is to create a class `CustomIterator` that implement... | ```java
import java.util.Collection;
import java.util.Iterator;
public class CustomIterator<T> implements Iterator<T> {
private Collection<T> items;
private Iterator<T> iterator;
private Config config;
public CustomIterator(Collection<T> items, Config config) {
this.items = items;
this... | magicoder | java |
You are tasked with creating a custom pagination class for a Django REST framework viewset. The goal is to implement a pagination class that allows for large result sets to be paginated efficiently. The provided code snippet includes a `QuizFilter` class for filtering quizzes and a `QuizViewSet` class for handling quiz... | ```python
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
class LargeResultsSetPagination(PageNumberPagination):
page_size = 50
page_size_query_param = 'page_size'
max_page_size = 1000
def get_paginated_response(self, data):
return Respon... | magicoder | python |
You are tasked with implementing a route definition system for a web application framework. The route definition system should support different kinds of routes and provide a way to specify route configurations.
You need to create a TypeScript interface and a function that validates and processes route definitions bas... | ```typescript
export interface ConcreteRouteDef {
routeKind: "static" | "dynamic" | "redirect";
config: any; // The structure of this object depends on the value of routeKind
}
function processRoute(route: ConcreteRouteDef): any {
switch (route.routeKind) {
case "static":
return route.config;
case ... | magicoder | typescript |
You are tasked with creating a program to manage a leaderboard for an online gaming platform. The program should allow users to add their username and experience points (XP) to the leaderboard and display the top players based on their XP.
You are given the following code snippet as a starting point:
```python
print(... | ```python
class Leaderboard:
def __init__(self):
self.players = {}
def add_player(self, username, xp):
self.players[username] = xp
def top_players(self, k):
sorted_players = sorted(self.players.items(), key=lambda x: x[1], reverse=True)
top_k_players = [player[0] for player... | magicoder | python |
You are given a network represented by a collection of places and transitions. Each place in the network has a set of tokens, and transitions represent the flow of tokens between places. Your task is to implement a function that identifies pairs of places in the network that have similar characteristics.
You are given... | ```rust
use std::collections::HashMap;
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
struct Place {
consumed_by: Vec<TransitionId>,
produced_by: Vec<TransitionId>,
}
type PlaceId = String;
type TransitionId = String;
fn find_similar_places(net: &HashMap<PlaceId, Place>) -> Vec<(PlaceId, PlaceId)> {
let mu... | magicoder | rust |
You are tasked with implementing a memory manipulation function in C++ that involves interpreting a data buffer as an array of bytes and performing a specific operation on it. The function should take a data buffer, its size, and a data definition as input, and then allocate a new data buffer based on the provided data... | ```cpp
#include <cstdint>
class DataReader {
public:
DataReader(uint8_t* data, size_t size) {
// Constructor implementation
}
// Other member functions and data members
};
class DataWriter {
public:
DataWriter(uint8_t* data, size_t size) {
// Constructor implementation
}
// Oth... | magicoder | cpp |
You are tasked with creating a Python program that utilizes the `instabot` library to automate posting images to Instagram at scheduled intervals. The program should be able to upload images from a specified directory to a designated Instagram account using the `instabot` library and the `schedule` library for scheduli... | ```python
import os
import schedule
import time
from instabot import Bot
def schedule_instagram_posts(username, password, image_directory, post_times):
bot = Bot()
# Login to the Instagram account
try:
bot.login(username=username, password=password)
except Exception as e:
print(f"F... | magicoder | python |
You are tasked with implementing a function that takes an integer value and generates the corresponding IL (Intermediate Language) code to load that value onto the evaluation stack using the `System.Reflection.Emit` namespace in C#. The IL code should handle both small integer values within the range of -128 to 127 and... | ```csharp
using System;
using System.Reflection;
using System.Reflection.Emit;
public class ILCodeGenerator
{
public static string GenerateILCodeForValue(int value)
{
var dynamicMethod = new DynamicMethod("LoadValue", typeof(void), new Type[0]);
var iLGenerator = dynamicMethod.GetILGenerator();... | magicoder | csharp |
You are tasked with creating a script that automates the process of setting up a Python environment and running a specific Python script. Your script should handle the loading of necessary modules, setting environment variables, and executing the Python script with the specified arguments.
Write a shell script that ac... | ```bash
#!/bin/sh
# Load the gcc module
module load gcc-7.4.0-gcc-4.8.5-dan4vbm
# Load the sox module
module load sox
# Set the PYTHONPATH environment variable
export PYTHONPATH=${PYTHONPATH}:/home/dwa6259/grad_work/merkel/newnewLAS/fork/End-to-end-ASR-Pytorch/
# Execute the Python script with specified arguments
p... | magicoder | shell |
You are tasked with creating a Django REST framework API view for a project management system. The API view should handle various operations related to projects, including listing, creating, updating, and deleting projects. The view should also support filtering, searching, and ordering of projects. Additionally, the A... | ```python
from rest_framework.views import APIView
from ..models import Project
from ..serializers.project_serializer import ProjectSerializer, ProjectListSerializer
from common.custom import CommonPagination, RbacPermission
from rest_framework.filters import SearchFilter, OrderingFilter
from rest_framework_jwt.authent... | magicoder | python |
You are given the definition of a binary tree node and a function to check if the given binary tree is a complete tree.
Binary Tree Node Definition:
```python
class TreeNode:
def __init__(self, value=0, left=None, right=None):
self.value = value
self.left = left
self.right = right
```
Func... | ```python
class TreeNode:
def __init__(self, value=0, left=None, right=None):
self.value = value
self.left = left
self.right = right
def buildTree(nodes, index):
if index < len(nodes):
value = nodes[index]
if value is not None:
node = TreeNode(value)
... | magicoder | python |
You are working on a software project that involves creating and managing attribute definitions using the SMTK (Simulation Modeling Toolkit) library. The provided code snippet demonstrates the creation of attribute definitions using the SMTK API. Your task is to implement a function that can validate and manipulate the... | ```cpp
#include <iostream>
#include "smtk/attribute/Definition.h"
#include "smtk/attribute/StringItemDefinition.h"
void validateAndManipulateDefinitions(smtk::attribute::DefinitionPtr expDef, smtk::attribute::DefinitionPtr baseDef) {
// Validate that expDef and baseDef are not null
if (expDef && baseDef) {
... | magicoder | cpp |
You are working on a signal processing application that involves categorizing signal amplitudes based on their frequencies. You have been given a list of frequency-amplitude pairs and need to categorize the amplitudes into different buckets based on the frequency ranges. The frequency ranges and corresponding buckets a... | ```python
from typing import List, Tuple, Dict
def categorize_amplitudes(freq_amp_pairs: List[Tuple[int, float]]) -> Dict[str, List[float]]:
categorized_amplitudes = {
"mid1bucket": [],
"mid2bucket": [],
"mid3bucket": []
}
for freq, amp in freq_amp_pairs:
if freq >= 875 and... | magicoder | python |
You are tasked with creating a Rust function that processes image data and applies a specific image transformation using the glium library. The function should take in the image data and return the resulting transformed image.
The function signature should be:
```rust
fn apply_image_transformation(image_data: &[u8]) -... | ```rust
extern crate glium;
use glium::{Display, Surface, Program, VertexBuffer, IndexBuffer, uniform};
use glium::texture::srgb_texture2d::SrgbTexture2d;
use std::borrow::Cow;
fn apply_image_transformation(image_data: &[u8]) -> Vec<u8> {
// Create a display
let display = Display::new(/* your display paramete... | magicoder | rust |
You are tasked with creating a function to render and send email invitations to users. The function should handle the scenario where an invitation notification has already been sent and should not send duplicate notifications.
You are provided with a code snippet that includes a test case for the function. The test ca... | To solve this problem, you can create the `render_and_send_invite_email` function that takes the invite's primary key as a parameter. Within this function, you should first retrieve the invite object using the provided primary key. Then, check if the invite notification has already been sent. If it has not been sent, r... | magicoder | python |
You are tasked with creating a Python class that simulates a simple quiz application. The class should allow the user to add questions, take the quiz, and view the quiz results. Each question will have a prompt and an answer. The quiz will be scored based on the number of correct answers.
Your task is to implement the... | ```python
class Question:
def __init__(self, prompt, answer):
self.prompt = prompt
self.answer = answer
class Quiz:
def __init__(self):
self.questions = []
def add_question(self, prompt, answer):
self.questions.append(Question(prompt, answer))
def take_quiz(self):
... | magicoder | python |
You are tasked with implementing a method to parse a given file and return its content as a string. Additionally, you need to create a method to retrieve a resource as a URL. You are provided with a partial code snippet from a `FileUtils` class, which includes an incomplete `readFileAsString` method and an incomplete `... | ```java
import java.io.File;
import java.net.URL;
import java.util.Scanner;
public class FileUtils {
public static String readFileAsString(File file) {
try {
Scanner scanner = new Scanner(file);
scanner.useDelimiter("\\Z");
return scanner.next();
} catch (Except... | magicoder | java |
You are tasked with implementing a learning rate scheduler for a deep learning model training process. The learning rate scheduler should adjust the learning rate of the optimizer during training to improve model convergence and performance. You are provided with a code snippet that initializes a deep learning model, l... | To implement the learning rate scheduler and apply it to the optimizer, you can use the following code:
```python
import torch.nn as nn
import torch.optim as optim
import torch.optim.lr_scheduler as lr_scheduler
from torchvision.models import resnet9
# model
model = resnet9(in_channels=3, num_classes=10)
criterion = ... | magicoder | python |
You are tasked with creating a Python class that represents a media graph for a cloud infrastructure using Pulumi, a popular infrastructure as code tool. The media graph class should be able to manage various resources such as account name, description, media graph name, resource group name, sinks, and sources. Your ta... | ```python
import pulumi
from typing import Optional, Sequence
class MediaGraph(pulumi.CustomResource):
def __init__(self,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
account_name: Optional[pulumi.Input[str]] = None,
descript... | magicoder | python |
You are tasked with implementing a simplified version of a class for handling HTTP requests using the libcurl library. The provided code snippet outlines the basic structure of the class and its member functions. Your task is to complete the class implementation by adding the necessary member variables and implementing... | ```cpp
#include <iostream>
#include <string>
#include <curl/curl.h>
class Curl {
private:
CURL* curlHandle;
public:
Curl() {
curl_global_init(CURL_GLOBAL_ALL);
curlHandle = curl_easy_init();
}
~Curl() {
curl_easy_cleanup(curlHandle);
curl_global_cleanup();
}
s... | magicoder | cpp |
You are tasked with implementing a parameter parsing system for a command-line interface. The system should be able to parse different types of parameters, such as flags, options, and positional parameters. Each parameter has a name, a type, and an optional default value.
Your task is to create a class `Parameter` wit... | ```python
class Parameter:
def __init__(self, name, param_type, default=None):
self.name = name
self.type = param_type
self.default = default
def parse(self, args):
if self.type == bool:
return self.name in args
elif self.name in args:
index = arg... | magicoder | python |
You are tasked with creating a custom tabbed widget in a PyQt application. The given code snippet is a part of a larger PyQt application and is responsible for setting up a tabbed interface with a specific size policy for the log output widget. Your task is to complete the implementation of the tabbed widget by adding ... | ```python
from PyQt5.QtWidgets import QTabWidget, QFormLayout, QWidget, QVBoxLayout
from PyQt5.QtCore import pyqtSignal
class CustomTabWidget(QTabWidget):
tabChanged = pyqtSignal(int)
def __init__(self, parent=None):
super(CustomTabWidget, self).__init__(parent)
self.Layout = QVBoxLayout()
... | magicoder | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.