query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with creating a Django admin interface for managing teachers and their associated courses. The provided code snippet is a part of the Django application and demonstrates the use of `xadmin` to create an admin interface for managing courses related to teachers.
Your task is to implement a feature that al... | To solve this problem, you can create a custom admin interface for the `Teacheres` model in the `adminx.py` file. You can use the `InlineModelAdmin` class provided by Django to allow the admin to add multiple courses for each teacher.
Here's a possible solution:
```python
# apps/teacheres/adminx.py
# _*_ coding:utf-8... | magicoder | python |
You are tasked with implementing a training loop for a modified VGG16 model using PyTorch. The provided code snippet initializes a VGG16 model, modifies its classifier layer, sets up a loss function, optimizer, and learning rate scheduler, and moves the model to a specified device. Your task is to complete the training... | ```python
# Assuming the dataset and dataloader are already defined
for epoch in range(num_epochs):
temp_vgg_model.train() # Set the model to training mode
running_loss = 0.0
for inputs, labels in dataloader:
inputs, labels = inputs.to(device), labels.to(device) # Move data to the specified device... | magicoder | python |
You are tasked with implementing a Java class that utilizes nested generic types. Your task is to create a class with a specific nested generic type structure and provide a method to set and retrieve a value of the innermost generic type.
Create a Java class called `NestedGenericClass` with the following nested generi... | ```java
public class NestedGenericClass<T1, T2> {
public class Inner<T3> {
public class Bar {
public class Fuz<T4> {
private T4 value;
public void setValue(T4 value) {
this.value = value;
}
public T4 getValue()... | magicoder | java |
You are tasked with creating a program that analyzes a given software license text to extract and count the occurrences of specific keywords related to warranties and liabilities. The keywords to be searched for are "warranties", "merchantability", "fitness for a particular purpose", "disclaimed", "liability", "direct"... | ```python
import re
def analyze_license_text(license_text: str) -> dict:
keywords = [
"warranties", "merchantability", "fitness for a particular purpose",
"disclaimed", "liability", "direct", "indirect", "incidental",
"special", "exemplary", "consequential"
]
keyword_counts = {keywo... | magicoder | python |
You are given a code snippet that performs a specific operation on a variable `value`. Your task is to understand the code and implement a function that achieves the same functionality in a different programming language.
The code snippet performs a variable-length encoding of a non-negative integer `value` into a byt... | ```python
def encodeVariableLength(value):
byte_stream = bytearray()
while value >= 0x80:
byte_stream.append((value & 0x7F) | 0x80)
value >>= 7
byte_stream.append(value & 0x7F)
return byte_stream
```
The `encodeVariableLength` function takes a non-negative integer `value` as input and r... | magicoder | python |
You are tasked with implementing a simplified image processing pipeline in Swift. The pipeline consists of a series of image processing steps that are applied sequentially to an input image. Each processing step is represented by a `ImageProcessing` protocol, and the pipeline is responsible for applying these processin... | ```swift
private func _process(_ response: ImageResponse, isCompleted: Bool, processors: [ImageProcessing]) {
guard let processor = processors.last else {
self.decompressImage(response, isCompleted: isCompleted)
return
}
var remainingProcessors = processors
remainingProcessors.remov... | magicoder | swift |
You are given a string containing a series of opening and closing parentheses. Your task is to write a function to determine if the parentheses are balanced. A string of parentheses is considered balanced if every opening parenthesis has a corresponding closing parenthesis and they are properly nested.
Write a functio... | ```javascript
function isBalancedParentheses(s) {
const stack = [];
const opening = ['(', '{', '['];
const closing = [')', '}', ']'];
const pairs = {
')': '(',
'}': '{',
']': '['
};
for (let char of s) {
if (opening.includes(char)) {
stack.push(char);
} else if (closing.includes(c... | magicoder | javascript |
You are tasked with implementing a Python class that handles a configuration flow for a home automation system. The provided code snippet is a starting point for the class, but it lacks essential functionality. Your task is to extend the class by adding methods to handle the configuration flow and ensure that the confi... | ```python
class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a config flow for gs_alarm."""
VERSION = 1
async def async_step_user(self, user_input=None):
"""Handle the initial step of the configuration flow."""
# Prompt the user for necessary configuration details
... | magicoder | python |
You are tasked with implementing a DepthToSpace operation for a neural network framework. The DepthToSpace operation reorganizes data from depth into spatial dimensions. The operation takes an input tensor of shape (batch, height, width, channels) and rearranges the data into a tensor of shape (batch, height * block_si... | ```cpp
#include <memory>
#include <vector>
class Shape {
public:
Shape(int batch, int height, int width, int channels) : batch_(batch), height_(height), width_(width), channels_(channels) {}
int batch() const { return batch_; }
int height() const { return height_; }
int width() const { return width_; ... | magicoder | cpp |
You are given a dictionary containing key-value pairs where the keys are strings representing characters or combinations of characters, and the values are strings representing the corresponding replacements. Each key may consist of one or more characters, and the replacements may also vary in length. Additionally, some... | ```python
def replace_with_dict(input_string, replacements):
result = input_string
sorted_replacements = sorted(replacements, key=len, reverse=True) # Sort keys by length in descending order
for key in sorted_replacements:
if key in result:
value = replacements[key]
key_len... | magicoder | python |
You are tasked with creating a Python function that processes and validates data from a CRM (Customer Relationship Management) system. The CRM data is serialized using the Django REST framework. Your function will take a serialized CRM project as input and perform specific validations on the data.
The serialized CRM p... | ```python
import json
def validate_crm_project(serialized_crm_project: dict) -> dict:
validated_data = serialized_crm_project.copy()
# Validation 1: Ensure slug_field is not empty
if not validated_data['slug_field']:
raise ValueError("Slug field cannot be empty")
# Validation 2: Validate and ... | magicoder | python |
You are tasked with creating a neural network model to classify the Iris dataset using the Keras library with TensorFlow backend. The Iris dataset contains 150 samples of iris flowers, each with four features: sepal length, sepal width, petal length, and petal width. The dataset is divided into three classes: setosa, v... | ```python
import tensorflow_datasets as tfds
from keras.models import Sequential
from keras.layers import Dense
# Construct a tf.data.Dataset
iris_ds = tfds.load('iris', split='train', shuffle_files=True, as_supervised=True).repeat()
iris_model = Sequential([
Dense(40, input_shape=(4,), activation='relu'),
De... | magicoder | python |
You are tasked with implementing a function to find the second largest element in a given list of integers. You are provided with a code snippet that initializes a constant iterator `ite` to the beginning of the list.
Your task is to write a function `findSecondLargest` that takes a reference to the list and returns t... | ```cpp
#include <list>
#include <iostream>
int findSecondLargest(const std::list<int>& lst) {
if (lst.size() < 2) {
return -1; // Error value for lists with less than two elements
}
int firstMax = std::numeric_limits<int>::min();
int secondMax = std::numeric_limits<int>::min();
for (int n... | magicoder | cpp |
You are tasked with creating a Python program that simulates a simple game of rock-paper-scissors. The program should allow a user to play against the computer. The game should consist of a series of rounds, and the winner of each round should be determined based on the classic rules of rock-paper-scissors: rock beats ... | ```python
import random
def get_user_choice():
while True:
user_input = input("Enter your choice (rock, paper, scissors) or 'q' to quit: ").lower()
if user_input in ['rock', 'paper', 'scissors', 'q', 'quit']:
return user_input
else:
print("Invalid input. Please enter... | magicoder | python |
You are tasked with implementing a Python class that manages network settings for a custom communication protocol. The class should handle timeout and buffer size configurations for network operations. The provided code snippet outlines the initial configuration values for timeout and buffer size.
Your task is to crea... | ```python
class NetworkSettings:
__TIMEOUT = 4.0 # seconds
__BUFFER_SIZE = 1024 # bytes
@classmethod
def get_timeout(cls):
return cls.__TIMEOUT
@classmethod
def set_timeout(cls, new_timeout):
if new_timeout >= 0:
cls.__TIMEOUT = new_timeout
else:
... | magicoder | python |
You are tasked with implementing a function to perform a rollout in a reinforcement learning environment. A rollout involves running an agent in an environment for a certain number of time steps and collecting the observations, actions, rewards, and other information generated during this process.
You are given a Pyth... | ```python
def rollout(env, agent, max_path_length=np.inf, animated=False, speedup=1,
always_return_paths=False):
observations = []
actions = []
rewards = []
agent_infos = []
env_infos = []
o = env.reset()
path_length = 0
animated_this_time = False
while path_length ... | magicoder | python |
You are tasked with implementing a function to calculate the ordinal loss for a given input and target in a machine learning context. The ordinal loss measures the difference between the predicted ordinal values and the target ordinal values.
You are given a code snippet that initializes the ranges and mask for the c... | ```python
import torch
def ordinal_loss(input, target):
N, C = input.shape
ranges = torch.arange(C, dtype=torch.int32).cuda()
mask = ranges[None, :] < target[:, None]
# Calculate the ordinal loss using the mask and input tensor
loss = torch.sum((input[:, :-1] - input[:, 1:]).clamp(min=0) * mask.... | magicoder | python |
You are tasked with implementing a function that calculates the maximum sum of a subarray within a given array of integers. The subarray must contain at least one element. For example, given the array `[-2, 1, -3, 4, -1, 2, 1, -5, 4]`, the contiguous subarray with the largest sum is `[4, -1, 2, 1]`, with a sum of 6.
W... | ```python
from typing import List
def maxSubarraySum(arr: List[int]) -> int:
max_sum = arr[0]
current_sum = arr[0]
for num in arr[1:]:
current_sum = max(num, current_sum + num)
max_sum = max(max_sum, current_sum)
return max_sum
``` | magicoder | python |
You are tasked with implementing a feature for a web-based code submission system. The system has a task pane with various components for managing submissions. The code snippet provided is from a TypeScript file (`SubmissionsView.tsx`) that imports two components: `UploadSubmissionsButton` and `AddSubmissionButton`.
Y... | ```typescript
import React from "react";
interface Submission {
id: string;
score: number;
}
interface SubmissionStatisticsProps {
submissions: Submission[];
}
const SubmissionStatistics: React.FC<SubmissionStatisticsProps> = ({ submissions }) => {
const totalSubmissions = submissions.length;
const totalS... | magicoder | typescript |
You are tasked with implementing a function to validate a set of options based on a given set of validation functions. The function `validateOptions` takes two parameters: `options` and `validationRules`. The `options` parameter is an object containing various options to be validated, while the `validationRules` parame... | ```javascript
async function validateOptions(options, validationRules) {
const reasons = [];
for (const option in options) {
if (Object.prototype.hasOwnProperty.call(options, option)) {
const validationFunction = validationRules[option];
if (validationFunction && !validationFunction(options[option])... | magicoder | javascript |
You are tasked with implementing a Java class that utilizes the Apache Lucene and Spatial4j libraries to perform spatial indexing and querying. The code snippet provided is the beginning of a class named `SpatialPointVectorStrategyFieldTypeDefinition` that extends `BaseSpatialFieldTypeDefinition`. Your task is to compl... | ```java
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.spatial.query.SpatialArgs;
import org.apache.lucene.spatial.query.Spatia... | magicoder | java |
You are tasked with implementing a function to efficiently calculate the modular exponentiation of a base number raised to a power with respect to a given modulus. Modular exponentiation is a fundamental operation in number theory and cryptography, and it involves computing (base^power) % modulus. This operation is par... | ```c
unsigned long long modularExponentiation(unsigned long long base, unsigned long long power, unsigned long long modulus) {
unsigned long long res = 1;
base = base % modulus; // Ensure base is within the range of modulus
while (power > 0) {
if (power & 1) {
res = (res * base) % modul... | magicoder | c |
You are tasked with implementing a function to calculate the duration of an animation based on the flick velocity and panel dimensions. The function should take into account whether the panel is hidden or revealed and adjust the duration accordingly. The relevant variables and logic are provided in the code snippet bel... | ```swift
func calculateAnimationDuration(hidden: Bool, flickVelocity: CGFloat, sidePanel: UIView, _preferences: Preferences) -> TimeInterval {
var duration = hidden ? _preferences.animating.hideDuration : _preferences.animating.revealDuration
if abs(flickVelocity) > 0 {
let newDuration = TimeInterv... | magicoder | swift |
You are tasked with implementing a custom CSV logger for monitoring the progress of an optimization algorithm. The provided code snippet is a partial implementation of the `PathmindCSVLogger` class, which is intended to extend the functionality of the `CSVLogger` class from the `ray.tune.result` module. Your task is to... | ```python
import os
from ray.tune.result import EXPR_PROGRESS_FILE
from ray.tune.logger import CSVLogger
class PathmindCSVLogger(CSVLogger):
def __init__(self, logdir):
"""Initialize the PathmindCSVLogger.
Args:
logdir (str): The directory where the log file will be created or appende... | magicoder | python |
You are working on a machine learning project that involves sentiment analysis on different datasets. You have been provided with a code snippet that imports various machine learning models and datasets. Your task is to create a function that takes a dataset and a machine learning model as input, trains the model on th... | ```python
def train_and_evaluate_model(dataset, model):
# Load the specified dataset
if dataset == "IMDB":
data = IMDB()
elif dataset == "Sentiment140":
data = Sentiment140()
elif dataset == "AmazonReviews":
data = AmazonReviews()
else:
raise ValueError("Invalid datas... | magicoder | python |
You are tasked with creating a neural network model using PyTorch to classify images of handwritten digits from the MNIST dataset. The model should consist of a convolutional neural network (CNN) followed by a fully connected layer. Your goal is to define the architecture of the CNN and implement the forward pass funct... | ```python
# The provided code snippet defines a CNN model class for image classification using PyTorch. The CNN architecture consists of two convolutional layers followed by max pooling, a fully connected layer, and an output layer.
# The CNNModel class inherits from nn.Module and defines the layers in the __init__ me... | magicoder | python |
You are tasked with creating a program that processes image data to extract relevant tags from a given URL. The program should retrieve the image data from a URL, analyze the image, and extract tags related to the content of the image. The tags should then be formatted and presented as output.
You are provided with a ... | ```python
import requests
from lxml import html
from bs4 import BeautifulSoup
# Retrieve image data from a given URL
url = 'https://example.com/image.jpg' # Replace with the actual image URL
response = requests.get(url)
image_data = response.content
# Analyze the image data to extract relevant tags
index = html.from... | magicoder | python |
You are tasked with implementing a custom `Pool` data structure in Rust. The `Pool` should support the installation of closures and provide a method to find the last installed closure that satisfies a given predicate.
Your task is to implement the `Pool` data structure and its associated methods. The `install` method ... | ```rust
use std::collections::HashMap;
struct Pool<T> {
closures: HashMap<usize, T>,
next_id: usize,
}
impl<T> Pool<T> {
fn new() -> Self {
Pool {
closures: HashMap::new(),
next_id: 0,
}
}
fn install<F>(&mut self, closure: F) -> usize
where
F: F... | magicoder | rust |
You are given a positive integer `n`. Your task is to write a program to find all the prime factors of `n` and print them in ascending order.
For example, if `n = 60`, the prime factors are `2, 2, 3, 5`. Therefore, the output should be `2 2 3 5`.
Your program should be able to handle large numbers efficiently. | ```python
def prime_factors(n):
factors = []
while n % 2 == 0:
factors.append(2)
n = n // 2
for i in range(3, int(n**0.5) + 1, 2):
while n % i == 0:
factors.append(i)
n = n // i
if n > 2:
factors.append(n)
return factors
n = int(input("Enter a... | magicoder | python |
You are tasked with creating a Python script that manages user profiles for an application using the `typer` library and the `pathlib` module. The script should allow users to create, update, and delete profiles stored in a specific directory. The profiles will be stored as individual files within the application direc... | ```python
import os
from pathlib import Path
import typer
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
app_dir = Path(typer.get_app_dir('pacu'))
profile_path = app_dir / 'profile'
app = typer.Typer()
@app.command()
def create_profile(profile_name: str):
"""Create a new profile."""
profile_file = pr... | magicoder | python |
You are tasked with implementing a custom error handling system in Java. The system should include an `Error` class with specific attributes and methods for handling and displaying error information. Your task is to create the `Error` class and a `handleError` method that demonstrates the usage of this custom error han... | ```java
// Custom Error class
class Error {
private String mDescription;
private String mLocation;
public Error(String description, String location) {
this.mDescription = description;
this.mLocation = location;
}
public String toString() {
return "Error: " + mDescription + ... | magicoder | java |
You are tasked with implementing a Python class that manages a library of various media segments for a video streaming service. The class should handle serving rules, tags, variations, and variation maps for each segment.
Your task is to create a `MediaSegment` class with the following functionalities:
1. Initialize t... | ```python
# Sample usage of the MediaSegment class
# Create serving rules, tags, and a variation map
serving_rules = [Serve("rule1"), Serve("rule2")]
tags = [Tag("tag1"), Tag("tag2")]
variation_map = VariationMap()
# Create a MediaSegment instance
segment = MediaSegment("segment1", serving_rules, tags, variation_map)
... | magicoder | python |
You are tasked with implementing a custom `BondType` class in Python to represent different types of bonds in a molecular simulation. The `BondType` class should have the following attributes: `bond_type_index`, `label`, `spring_coeff_1`, and `spring_coeff_2`. Additionally, the class should have a method to calculate t... | ```python
class BondType:
def __init__(self, bond_type_index, label, spring_coeff_1, spring_coeff_2):
self.bond_type_index = bond_type_index
self.label = label
self.spring_coeff_1 = spring_coeff_1
self.spring_coeff_2 = spring_coeff_2
def calculate_potential_energy(self, bond_len... | magicoder | python |
You are tasked with creating a Python function that simulates the behavior of `tf.contrib.learn.learn_runner.run` for running a training job in a machine learning environment. The function should take in an experiment function and a directory for output, and then execute the training job based on the provided experimen... | ```python
import tensorflow as tf
def run_training_job(experiment_fn, arguments, output_dir):
# Call the experiment function with the provided arguments
experiment = experiment_fn(**arguments)
# Create a run configuration for the training job
run_config = tf.contrib.learn.RunConfig(model_dir=outpu... | magicoder | python |
You are tasked with implementing a function to parse a custom binary protocol used for communication between a client and a server. The protocol specifies that the first 4 bytes of a message represent the length of the payload that follows. Your task is to write a function that takes a `Stream` of bytes as input and re... | ```rust
use tokio::io::{AsyncReadExt, Error};
async fn parse_payload(mut stream: impl tokio::io::AsyncRead + Unpin) -> Result<Vec<u8>, Error> {
let mut buffer = [0; 4];
let mut payload_length = 0;
parse_request_meta!(stream, buffer, payload_length);
let mut payload = vec![0; payload_length];
matc... | magicoder | rust |
You are tasked with implementing a Python function that takes a dictionary as input and returns a new dictionary where the keys and values of the original dictionary are swapped. For example, if the input dictionary is `{'a': 1, 'b': 2, 'c': 3}`, the output should be `{1: 'a', 2: 'b', 3: 'c'}`.
Write a function `swap_... | ```python
def swap_keys_values(input_dict):
return {v: k for k, v in input_dict.items()}
```
The `swap_keys_values` function takes the input dictionary and uses a dictionary comprehension to create a new dictionary where the keys and values are swapped. It iterates through the items of the input dictionary, using ... | magicoder | python |
You are tasked with creating a Python function that simulates a simple stack data structure using a list. The stack should support the following operations:
1. `push(item)`: Add an item to the top of the stack.
2. `pop()`: Remove and return the item at the top of the stack.
3. `peek()`: Return the item at the top of th... | ```python
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
if not self.is_empty():
return self.items.pop()
else:
raise IndexError("Cannot pop from an empty stack")
def peek(self):
... | magicoder | python |
You are tasked with implementing a JavaScript module for generating and iterating over a sequence of numbers. The module provides a function `generate` to create the sequence and a function `iterate` to traverse the sequence. Your goal is to understand the provided code snippet and implement the required functionality.... | ```javascript
// Solution for the generate function
export function generate(size = 0, start = 0, offset = 0, step = 1) {
const sequence = [];
for (let i = 0; i < size; i++) {
sequence.push(start + i * step + offset);
}
return sequence;
}
// Solution for the iterate function
export function iterate({ start... | magicoder | javascript |
You are tasked with implementing a Rust program to manage heroic characters and their weapons. The program should define a `Hero` struct with two fields: `hero_class` of type `u64` representing the class of the hero, and `weapon` of type `Option<HeroicWeapon>` representing the hero's equipped weapon. The `HeroicWeapon`... | ```rust
// Define the HeroicWeapon struct
struct HeroicWeapon {
name: String,
damage: u32,
}
// Define the Hero struct
struct Hero {
hero_class: u64,
weapon: Option<HeroicWeapon>,
}
impl Hero {
// Implement the associated function new for the Hero struct
fn new(hero_class: u64) -> Hero {
... | magicoder | rust |
You are tasked with creating a Rust library for managing software builds. The library will have several modules and public interfaces for external use. Your goal is to design the module structure and public interfaces based on the given code snippet and requirements.
Your library should have the following modules and ... | ```rust
// Module structure and public interfaces for the Rust library
// build.rs
mod build;
pub mod cmd;
mod crates;
pub mod logging;
mod native;
mod prepare;
pub mod toolchain;
mod tools;
pub mod utils;
mod workspace;
// build.rs
pub use crate::build::{Build, BuildDirectory};
// crates.rs
pub use crate::crates::C... | magicoder | rust |
You are tasked with implementing a class in Python to represent a geometric shape called a "Cone." The class should have the following properties and methods:
Properties:
- `height`: a float representing the height of the cone.
- `radius`: a float representing the radius of the base of the cone.
- `side`: a boolean in... | ```python
import math
class Cone:
def __init__(self, height, radius, side, top):
self.height = height
self.radius = radius
self.side = side
self.top = top
def calculate_surface_area(self):
total_surface_area = math.pi * self.radius * (self.radius + math.sqrt(self.height... | magicoder | python |
You are tasked with implementing a Python class to manage a Bluetooth Low Energy (BLE) adapter for a smart device. The class should handle the subscription and unsubscription of GATT (Generic Attribute Profile) characteristics, as well as the reading of properties from a Digital Twin (DT) in the DCD (Data Context Diagr... | ```python
from dcd.entities.thing import Thing
class BLEManager:
def __init__(self, thing_id, token):
self.thing = Thing(thing_id=thing_id, token=token)
self.ble_adapter_started = False
def subscribe(self, characteristic):
# Implement subscription to GATT characteristic
# Examp... | magicoder | python |
You are tasked with implementing a class that manages a collection of implementations for a given interface. The class should ensure that there are no conflicts between implementations and that all required overrides and implementations exist.
You are provided with a partial code snippet for the class:
```java
public... | ```java
private void checkOverridesImplementationsConflict() {
Set<String> keys = new HashSet<>();
for (String key : implementations.keySet()) {
if (!keys.add(key)) {
throw new IllegalStateException("Conflict: Multiple implementations for key " + key);
}
}
}
private void checkAl... | magicoder | java |
You are working on a Python package that dynamically patches client classes to add shim implementations for all inherited methods. This is necessary to generate accurate online documentation without impacting the functionality of the methods themselves. Your task is to implement a function that dynamically adds shims t... | ```python
class Client:
def __init__(self):
pass
def method1(self):
print("Original method1 called")
def method2(self):
print("Original method2 called")
def add_shims(client_class, shim_methods):
for method_name in shim_methods:
original_method = getattr(client_class, ... | magicoder | python |
You are tasked with implementing a lazy property in Swift. A lazy property is a property whose initial value is not calculated until the first time it is accessed. This can be useful for delaying the initialization of a property until it is actually needed, potentially saving resources and improving performance.
Your ... | ```swift
class LazyPropertyExample {
lazy var detailTextLabel: UILabel = {
let label = UILabel()
label.textColor = .red
label.font = UIFont.systemFont(ofSize: 14)
label.textAlignment = .center
return label
}()
init() {
setupDetailTextLabel()
}
... | magicoder | swift |
You are working on a search engine evaluation system that calculates the Mean Average Precision (MAP) for search results from two different sources: CodeCatch and Google. The MAP is a measure of the quality of search results, considering both the relevance and the ranking of the retrieved documents. The MAP is calculat... | ```python
import numpy as np
# Function to calculate average precision
def average_precision(results, cutoff):
relevant_count = 0
precision_sum = 0.0
for i, result in enumerate(results):
if result.is_relevant: # Assuming the result object has an "is_relevant" attribute
relevant_count +... | magicoder | python |
You are tasked with implementing a Java method that calculates the size of a directory after applying a filter to exclude certain files. The method should take a directory path and a file filter as input and return the total size of the filtered directory in bytes. You are provided with a code snippet that includes a t... | ```java
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.FileVisitOption;
import java.nio.file.FileVisitResult;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.at... | magicoder | java |
You are tasked with implementing a Python class that handles document processing. The class has a method that sets the document class based on user input. However, the given code snippet contains an incomplete method that needs to be filled in. Your task is to complete the `finish_handle` method to properly handle the ... | ```python
import sys
class DocumentProcessor:
def __init__(self):
self.doc_class_str = None
self.doc_class = None
def to_function(self, class_name):
# Implement the to_function method to convert class_name to a function
pass
def finish_handle(self):
if self.doc_cla... | magicoder | python |
You are tasked with implementing a dual blob store system that writes to two blob stores concurrently. The primary blob store processes read and write requests immediately, while the secondary blob store asynchronously writes blobs in the background. If the secondary store processes blobs slower than the primary, write... | ```python
import threading
import queue
import blob_store
class DualBlobStore(blob_store.BlobStore):
def __init__(self, primary_store, secondary_store, max_queue_size):
super().__init__()
self.primary_store = primary_store
self.secondary_store = secondary_store
self.max_queue_size =... | magicoder | python |
You are tasked with designing a URL routing system for a social media platform. The platform has endpoints for retrieving and creating posts and comments, as well as for retrieving posts by a specific author. The code snippet provided is a part of the URL configuration for the platform's API.
Your task is to create a ... | ```python
from typing import Union, Tuple, Callable, Dict
import re
def match_url_to_view(url_path: str) -> Union[Tuple[Callable, Dict[str, str]], None]:
patterns = [
(r'^author/posts$', PostViewSet.visible_posts, {}),
(r'^author/(?P<user_id>.+)/posts$', PostViewSet.visible_user_posts, {}),
... | magicoder | python |
You are tasked with implementing a custom stack view component in a mobile application. The stack view is a UI element that arranges its subviews in a vertical stack. The provided code snippet is a part of the implementation of this custom stack view. The `stackView` is an instance of the custom stack view, and `row` i... | ```swift
class StackView {
private var rows: [UIView] = []
func addRow(_ row: UIView) {
rows.append(row)
// Add the row to the stack view UI and update the layout
}
func setInset(forRow row: UIView, inset: UIEdgeInsets) {
// Set the inset for the specified row within the stack ... | magicoder | swift |
You are tasked with creating a Laravel Eloquent model for managing products in an e-commerce application. The model should include relationships with other models to represent the associations between different entities. Below is a code snippet for the initial implementation of the product model:
```php
protected $fil... | ```php
protected $fillable = [
'id_kategori', 'kode_barang','nama_barang','harga','foto'
];
public function kategori()
{
return $this->belongsTo('App\Models\Category', 'id_kategori');
}
public function barangmasuk()
{
return $this->hasMany('App\Models\BarangMasuk', 'id_kode_barang');
}
public function tr... | magicoder | php |
You are tasked with implementing a class that performs XML transformations using the provided code snippet as a reference. Your task is to create a class called `XmlTransformer` that encapsulates the functionality of loading an XML document, applying an XML transformation, and saving the transformed document to a speci... | ```csharp
using System;
using System.IO;
using System.Xml;
public class XmlTransformer : IDisposable
{
private XmlTransformableDocument _document;
public void LoadXmlDocument(string filePath)
{
_document = new XmlTransformableDocument();
_document.PreserveWhitespace = true;
using ... | magicoder | csharp |
You are tasked with implementing a function that checks whether a given string is a valid HTML tag. In HTML, a tag is considered valid if it follows the syntax rules for opening and closing tags. An opening tag starts with `<` followed by the tag name and ends with `>`, while a closing tag starts with `</` followed by ... | ```python
def isValidHTMLTag(tag):
if tag.startswith("</") and tag.endswith(">"):
tag_name = tag[2:-1]
if tag_name.isalnum() and tag_name[0].isalpha() and all(char.isalnum() or char == '-' for char in tag_name):
return True
elif tag.startswith("<") and tag.endswith(">"):
tag_... | magicoder | python |
You are tasked with creating a Python function that verifies the authenticity of a blob of signed data using a given signature and optional key information. The function `verifyBlob` takes in the following parameters:
- `signedData`: A byte string representing the data that has been signed.
- `signature`: A byte string... | ```python
from typing import Optional
from pathlib import Path
import gnupg
def verifyBlob(signedData: bytes, signature: bytes, *, keyFingerprint: str = None, keyFile: Path = None, subkeyFingerprint: str = None) -> bool:
gpg = gnupg.GPG()
if keyFile:
with open(keyFile, 'rb') as key:
im... | magicoder | python |
You are tasked with implementing a Python class that manages file paths and ignores specific directories. Your task is to complete the implementation of the `PathManager` class by adding a method that lists all the directories within the specified path, excluding the directories listed in the `ignore` attribute.
The `... | ```python
import os
class PathManager:
def __init__(self, default):
self.path = default.path + "/system/library/"
self.ignore = ['__pycache__', '__init__.py']
def get(self):
return self
def list_directories(self):
directories = [d for d in os.listdir(self.path) if os.path.... | magicoder | python |
You are tasked with implementing a function to calculate the number of self-intersection points in a given polygon. A self-intersection point occurs when a line segment within the polygon intersects with another line segment within the same polygon.
You are provided with the following function signature:
```cpp
size_t... | ```cpp
#include <vector>
#include <cmath>
struct Point {
double x, y;
};
struct Line {
Point start, end;
};
bool onSegment(const Point& p, const Point& q, const Point& r) {
if (q.x <= std::max(p.x, r.x) && q.x >= std::min(p.x, r.x) &&
q.y <= std::max(p.y, r.y) && q.y >= std::min(p.y, r.y)) {
... | magicoder | cpp |
You are tasked with creating a program that can analyze a given piece of code and identify any syntax errors present. Your program should be able to detect and report any syntax errors found in the code snippet. For the purpose of this problem, a syntax error is defined as any violation of the rules of a programming la... | ```python
import ast
def detect_syntax_errors(code: str) -> List[str]:
try:
ast.parse(code)
except SyntaxError as e:
return [f"SyntaxError: {e.msg}"]
return []
```
The `detect_syntax_errors` function uses Python's `ast` module to parse the code snippet. If a syntax error is encountered dur... | magicoder | python |
You are given a Python function `matchNames(ID_name, ID, data)` that takes in three parameters:
- `ID_name`: A string representing the name of the ID to be matched.
- `ID`: Either a string or an integer representing the ID to look for. If it is an integer, it will be considered as the ID to look for, except for sizes a... | ```python
def matchNames(ID_name, ID, data):
matched_ids = []
for item in data:
if isinstance(ID, int):
if item.get(ID_name) == ID:
matched_ids.append(item.get('ID'))
elif isinstance(ID, str):
if item.get(ID_name) == ID:
matched_ids.append(... | magicoder | python |
You are given a list of integers representing a puzzle input. Your task is to calculate the sum of the products of adjacent pairs of integers in the list. If the last integer is reached, the "next" integer will be the first integer in the list. Write a function to compute this sum.
For example, given the input list [2... | ```python
def sum_of_adjacent_products(puzzle_input):
total = 0
for cur_index in range(len(puzzle_input)):
next_index = cur_index + 1 if not cur_index == len(puzzle_input) - 1 else 0
puz_cur = puzzle_input[cur_index]
pnext = puzzle_input[next_index]
total += puz_cur * pnext
r... | magicoder | python |
You are tasked with implementing a custom callback class for a deep learning framework. The callback, named `CVAELossCallback`, is intended to be used in the context of training a Conditional Variational Autoencoder (CVAE) model. The CVAE model is a type of neural network architecture used for generative modeling, part... | ```python
class CVAELossCallback(Callback):
def __init__(self, model, conditional_data):
super(CVAELossCallback, self).__init__()
self.model = model
self.conditional_data = conditional_data
def on_epoch_begin(self, epoch, logs=None):
self.total_loss = 0
self.batch_count ... | magicoder | python |
You are tasked with implementing a simplified version of a shell interface for a graphical user interface (GUI) toolkit. The shell interface is responsible for managing the creation and manipulation of surfaces within the GUI. Your goal is to create a class that represents the global interface for a specific version of... | ```csharp
public interface ZxdgShellV6Global
{
// Define the interface methods and properties for managing surfaces
void RegisterSurface(Surface surface);
void UnregisterSurface(Surface surface);
void MaximizeSurface(Surface surface);
void MinimizeSurface(Surface surface);
void ResizeSurface(Sur... | magicoder | csharp |
You are tasked with implementing a graph serialization and deserialization system. The graph is represented by a class `Graph` with the following methods:
```python
class Graph:
def __init__(self, id, inp, weights):
self.id = id
self.inp = inp
self.weights = weights
def serialize(self)... | ```python
class Graph:
# ... (previous methods remain unchanged)
def serialize_edges(self):
"""
Returns a list of serialized edges in the format: [source_id,DESTINATION,weight]
"""
serialized_edges = []
for edge in self.edges:
serialized_edges.append(f"{self.... | magicoder | python |
You are tasked with implementing a Python decorator that serializes the specified fields of a class instance into a JSON object. The decorator should take a list of field names as an argument and serialize only those fields when the class instance is converted to JSON.
Your task is to complete the implementation of th... | ```python
import json
def json_serialize(json_fields):
def decorator(cls):
def to_json(self):
serialized_data = {}
for field in json_fields:
if hasattr(self, field):
serialized_data[field] = getattr(self, field)
return serialized_data
... | magicoder | python |
You are tasked with implementing a Python class to simulate an Ornstein–Uhlenbeck process, a stochastic process used in physics, finance, and other fields. The process is described by the stochastic differential equation:
dx = -θx*dt + σ*dW
Where:
- dx is the change in the process variable x
- θ is the rate of revers... | ```python
from random import gauss
class OrnsteinUhlenbeck:
def __init__(self, dt=1, theta=.15, sigma=1, nums=1):
# Initialize class properties
self.x = [0] * nums
self.dt = dt
self.theta = theta
self.sigma = sigma
self.nums = nums
def __call__(self):
# ... | magicoder | python |
You are tasked with implementing a Python function that processes a given string to extract and count the occurrences of specific substrings. The function should take in a string and a list of substrings as input and return a dictionary containing the count of each substring found in the input string. The substrings ma... | ```python
from typing import List, Dict
def count_substrings(input_string: str, substrings: List[str]) -> Dict[str, int]:
substring_counts = {substring: input_string.count(substring) for substring in substrings}
return substring_counts
```
The `count_substrings` function takes the input string and the list of... | magicoder | python |
You are tasked with creating a CSS variable resolver function that can handle cascading variable references. Cascading variables are defined as a fallback mechanism where a variable references another variable, and if the referenced variable is not defined, it falls back to a default value.
Given the following CSS var... | ```javascript
function resolveCSSVariables(variableName) {
const variableRegex = /var\(([^)]+)\)/; // Regex to match var(--variable-name)
let currentVariable = `var(${variableName})`; // Start with the input variable
while (variableRegex.test(currentVariable)) {
const matches = currentVariable.match(variable... | magicoder | javascript |
You are tasked with implementing a custom extension for the `UIApplication` class in Swift. The extension should provide a method to retrieve the launch options dictionary and return a specific value from it. The launch options dictionary is of type `[UIApplication.LaunchOptionsKey: Any]?` and contains information abou... | ```swift
// MARK: - Extensions
extension UIApplication {
func getLaunchOptionValue<T>(for key: UIApplication.LaunchOptionsKey) -> T? {
guard let launchOptions = delegate?.window??.rootViewController?.view.window?.windowScene?.session.stateRestorationActivity?.userInfo as? [UIApplication.LaunchOptionsKey: A... | magicoder | swift |
You are tasked with creating a script to automate the versioning and iteration of a software project. The version number is stored in a file named `build.sbt` in the format `version := "x.y.z"`, where `x.y.z` represents the major, minor, and patch version numbers. The iteration number is a combination of the Jenkins bu... | ```bash
#!/bin/bash
# Step 1: Read the version number from the build.sbt file
VERSION=$(grep ^version build.sbt | sed 's/version := "\([0-9.]*\)"/\1/g')
# Step 2: Extract the major, minor, and patch version numbers
MAJOR=$(echo $VERSION | cut -d. -f1)
MINOR=$(echo $VERSION | cut -d. -f2)
PATCH=$(echo $VERSION | cut -... | magicoder | shell |
You are working on a logging system for a software application. The code snippet provided is a part of a Python class that represents a log entry. The class has an `__init__` method to initialize the log entry with a timestamp, format string, log kind, and additional arguments. It also has a `fmt` method to format the ... | ```python
class LogKind:
# Assume LogKind is an enum-like class with predefined log kinds
class LogData:
# Assume LogData is a class representing the log data
class LogEntry:
def __init__(self, timestamp: float, fmt: str, kind: LogKind, *args, **kwargs) -> None:
self._timestamp = timestamp
... | magicoder | python |
You are tasked with implementing a custom stream class in C++ that supports pushing different types of data onto the stream. The provided code snippet shows a part of the implementation for the `push` method of the `Stream` class. The `push` method is overloaded to accept both `long` and `int` data types. The `checkedN... | ```cpp
#include <iostream>
#include <sstream>
class Stream {
private:
std::stringstream ss_;
void checkedNext(Stream& stream) {
// Perform validation logic here
// For example, check if the stream is in a valid state
// This is a placeholder for actual validation logic
std::cou... | magicoder | cpp |
You are tasked with implementing a C++ class for handling Bitcoin transactions. The class `Bitcoin` contains a nested struct `TxIn` representing a transaction input. Your goal is to implement the `operator<<` and `operator>>` overloads for the `TxIn` struct to enable serialization and deserialization of transaction inp... | ```cpp
#include <iostream>
#include <iomanip>
#include <sstream>
class Bitcoin {
public:
struct TxIn {
uint32_t nSequence;
// Other members not shown for brevity
};
friend std::ostream& operator<<(std::ostream& os, const TxIn& v) {
os.write(reinterpret_cast<const char*>(&v.nSequenc... | magicoder | cpp |
You are tasked with implementing a function to parse a release candidate number from a given string and update a variable with the parsed number. If the string is not a valid integer, the function should not fail but instead handle the error gracefully.
Write a function `parseReleaseCandidate` that takes a string as ... | ```swift
func parseReleaseCandidate(_ input: String, _ rcNumber: inout Int?) {
if let parsedFlag = Int(input) {
print("Parsed release candidate version number \(parsedFlag).")
rcNumber = parsedFlag
} else {
print("Did not parse a release candidate version number.")
rcNumber = nil... | magicoder | swift |
You are tasked with implementing a camera system for a 3D environment. The camera has a position and a rotation, and the view matrix needs to be updated based on certain constraints.
You are given the following code snippet as a starting point:
```cpp
rotation.x = std::clamp(rotation.x, Maths::Radians(90.0f), Maths::... | ```cpp
Matrix4 Matrix4::ViewMatrix(const Vector3& position, const Vector3& rotation) {
Matrix4 viewMatrix;
// Calculate the camera's forward, right, and up vectors based on the rotation
Vector3 forward = Vector3(
cos(rotation.y) * cos(rotation.x),
sin(rotation.x),
sin(rotation.y) * ... | magicoder | cpp |
You are tasked with creating a Swift program to interact with an Azure Automation job using the Azure Management Libraries for Swift. Your program should be able to execute a job within an Azure Automation account by making a request to the Azure Management API.
You are provided with the following code snippet as a st... | ```swift
import AzureManagementLibraries // Import the Azure Management Libraries for Swift
func execute(client: RuntimeClient) {
// Authenticate and authorize with Azure Management API using client credentials or other suitable method
// For example, using Azure Active Directory authentication
// Con... | magicoder | swift |
You are tasked with creating a language detection program using Python. Your program should take a text input and determine the language in which the text is written. To achieve this, you will utilize the `jinja2` and `langdetect` libraries. The `jinja2` library will be used to create a simple user interface for inputt... | ```python
import jinja2
from flask import Flask, request
from langdetect import detect
from jinja2 import Template
app = Flask(__name__)
html_form = """
<!DOCTYPE html>
<html>
<head>
<title>Language Detection</title>
</head>
<body>
<h2>Language Detection</h2>
<form method="post" action="/detect">
... | magicoder | python |
You are tasked with creating a function that calculates the required height for a UILabel based on its attributed text and the number of lines it should display. The function should take into account the label's font, attributed text, and the specified number of lines. Your task is to implement the `requiredAttributedH... | ```swift
func requiredAttributedHeight(numberOfLines: Int = 0) -> CGFloat {
let label: UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.frame.width, height: CGFloat.greatestFiniteMagnitude))
label.numberOfLines = numberOfLines
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.font = self... | magicoder | swift |
You are working on a computer vision project and need to implement a function to visualize input images and their corresponding target labels using Python's matplotlib library. The function should take a list of input images and their corresponding target labels, and display them side by side in a grid layout.
You are... | ```python
import matplotlib.pyplot as plt
import torch
from torchvision.transforms.functional import to_pil_image
def visualize_images_targets(images, targets, ignore_index=None):
num_images = len(images)
fig, axes = plt.subplots(2, num_images, figsize=(10, 5))
for idx in range(num_images):
img = ... | magicoder | python |
You are tasked with implementing a custom validation attribute for a .NET Core web application. The attribute should ensure that the input string meets specific length requirements. Your task is to create a custom validation attribute called `CustomLengthAttribute` that can be applied to properties in model classes. Th... | ```csharp
using System;
using System.ComponentModel.DataAnnotations;
public class CustomLengthAttribute : ValidationAttribute
{
private readonly int _minLength;
private readonly int _maxLength;
public CustomLengthAttribute(int minLength, int maxLength)
{
_minLength = minLength;
_maxLen... | magicoder | csharp |
You are tasked with implementing a secure communication protocol using a shared key encryption and decryption algorithm. The algorithm is provided in the form of a function `shared_key_enc_dec_assert_eq`, which takes two parameters: a message `msg` and a shared key `shared_key`. The function encrypts the message using ... | ```rust
use ring::{aead, rand};
fn shared_key_enc_dec_assert_eq(msg: &[u8], shared_key: &[u8]) -> Result<(), &'static str> {
// Define the algorithm and key length
let algorithm = &aead::AES_256_GCM;
let key_len = algorithm.key_len();
// Ensure the shared key length matches the required key length for... | magicoder | rust |
You are given a list of paths and a number of classes. Your task is to write a Python function that initializes a list of lists based on the given paths and number of classes.
The function should take two parameters:
- `path`: A list of paths, where each path is represented as a string.
- `ncls`: An integer representi... | ```python
def initialize_fname(path, ncls):
fname = [[] for _ in path] # Initialize fname as a list of empty lists based on the number of paths
for i in range(len(fname)): # Iterate over the paths
fname[i] = [[] for _ in range(ncls)] # Initialize each inner list with ncls empty sublists
return fn... | magicoder | python |
You are tasked with implementing a function to calculate the kernel differentials for an equirectangular projection. The equirectangular projection is a simple map projection that maps meridians to equally spaced vertical lines and parallels to equally spaced horizontal lines. The kernel differentials are used in image... | ```python
import numpy as np
def equirectangular_kernel(shape, kernel_size, dilation):
height, width = shape
dlon = np.zeros((height, width))
dlat = np.zeros((height, width))
for i in range(height):
for j in range(width):
dlon[i, j] = (i - height // 2) / (height * dilation)
... | magicoder | python |
You are tasked with creating a JavaScript function that processes specifications, handles any unhandled specifications, and appends them to an error log file. The function should utilize asynchronous operations and promises to ensure efficient processing and error handling.
You are given the following code snippet as ... | ```javascript
function processSpecifications(specifications, configuration, helper) {
let tasks = [];
specifications.forEach(specification => {
tasks.push(processSpecification(specification));
});
return Promise.all(tasks)
.then(() => {
if (this.unhandledSpecifications.length > 0) {
this... | magicoder | javascript |
You are tasked with creating a web page that displays a list of activities and allows users to edit the details of a specific activity. The provided code snippet is a part of the HTML code for the page heading and navigation.
Your task is to implement the functionality to edit the details of a specific activity. You n... | HTML:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>Edit Jenis Kegiatan</title>
</head>
<body>
<div class="clearfix">
<h1 class="h3 mb-4 float-left text-gray-800... | magicoder | html |
You are tasked with simulating a simple banner animation and dismissal mechanism in a Swift-based iOS application. The given code snippet is a part of a view controller that manages a banner display. The `UIView.animate` method is used to animate the banner's appearance with a spring effect, and upon completion, it sch... | ```swift
func dismiss(_ statusBarStyle: UIStatusBarStyle?) {
// Dismiss the banner
UIView.animate(withDuration: 0.3, animations: {
self.bannerState = .hidden
})
// Adjust the status bar style if needed
if let statusBarStyle = statusBarStyle {
UIApplication.shared.setStatusBarStyle(s... | magicoder | swift |
You are tasked with implementing a 3D thinning algorithm for voxelized point cloud data. Voxelization is a process that converts a continuous 3D space into a discrete grid of voxels, where each voxel represents a small volume element. The input to your algorithm is a voxel set representing a point cloud, and your goal ... | To perform 3D thinning on the given voxel set, we can use the iterative thinning algorithm. This algorithm iteratively removes voxels from the input set until no further changes occur. The following is a high-level overview of the thinning process:
1. Initialize a flag to track changes in the voxel set.
2. Repeat the ... | magicoder | python |
You are tasked with implementing a custom data structure called `IndexedDict` that combines the features of a dictionary and a list. The `IndexedDict` class should allow for accessing elements by both key and index. The class should have a method `index(self, i)` that takes an index `i` as input and returns the key-val... | ```python
class IndexedDict:
def __init__(self):
self.dict = {}
def add(self, key, value):
self.dict[key] = value
def index(self, i):
keys = list(self.dict.keys())
try:
return keys[i], self.dict[keys[i]]
except IndexError:
raise IndexError("O... | magicoder | python |
You are tasked with creating a Java class that simulates a simple banking system. The system should allow users to create accounts, deposit and withdraw funds, and check their balance. Additionally, the system should support transferring funds between accounts.
Your task is to implement the `BankingSystem` class with ... | ```java
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
class BankAccount {
private final String accountNumber;
private double balance;
public BankAccount(String accountNumber, double initialBalance) {
this.accountNumber = accountNumber;
this.balance = initialBalance;
... | magicoder | java |
You are tasked with implementing a function that serializes a binary tree into a string representation. The binary tree is represented as a collection of nodes, each containing a value and pointers to its left and right children. The serialization process should convert the binary tree into a string format that preserv... | ```python
class TreeNode:
def __init__(self, value=0, left=None, right=None):
self.value = value
self.left = left
self.right = right
def serialize_binary_tree(root):
"""
Serialize the given binary tree into a string representation.
Args:
root: TreeNode - The root node of th... | magicoder | python |
You are tasked with creating a command-line tool that can parse and execute a series of commands. The commands will be provided as a string, and each command will have a specific format. Your task is to write a function that can parse the input string and execute the commands accordingly.
The command format is as foll... | ```javascript
function executeCommands(input) {
const commands = input.split(' ');
for (let i = 0; i < commands.length; i++) {
const command = commands[i];
switch (command) {
case 'npm':
console.log(`Executing npm command with arguments: ${commands[i + 1]}`);
i++; // Skip the next argu... | magicoder | javascript |
You are given a list of integers representing the prices of a stock on different days. Your task is to write a function that finds the maximum profit that can be made by buying and selling the stock once. If there are multiple solutions with the same maximum profit, return the one with the earliest buying date.
Functi... | ```python
from typing import List, Tuple
def max_profit(prices: List[int]) -> Tuple[int, Tuple[int, int]]:
max_profit = 0
buy_date = 1
sell_date = 1
for i in range(len(prices)):
for j in range(i+1, len(prices)):
if prices[j] - prices[i] > max_profit:
max_profit = pr... | magicoder | python |
You are tasked with creating a Python program that processes a PDF file and extracts specific information from it. Your program should read a PDF file, check if it's encrypted, decrypt it if necessary, and then extract and print the text content of a specific page.
Write a Python function `extract_pdf_content` that ta... | ```python
from PyPDF2 import PdfFileReader
def extract_pdf_content(file_path: str) -> None:
with open(file_path, 'rb') as f:
reader = PdfFileReader(f, strict=False)
total_pages = reader.numPages
print(f"Total number of pages in the PDF: {total_pages}")
if reader.isEncrypted... | magicoder | python |
You are tasked with creating a Python class that processes and validates email addresses using regular expressions. Your class should have the following functionalities:
1. A method to set an email address.
2. A method to validate the email address using a regular expression.
3. A method to log information using the `l... | ```python
import re
import logging
class EmailValidator:
def __init__(self):
self.email = None
def set_email(self, email: str) -> None:
self.email = email
def validate_email(self) -> bool:
if self.email:
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
... | magicoder | python |
You are tasked with implementing a class hierarchy for managing author roles in a publishing system. The provided code snippet serves as a starting point for the implementation. Your task is to extend and implement the necessary classes and interfaces to create a robust author role management system.
The `any` class i... | ```php
// Implementing the author\role interface
interface role
{
public function getRole(): string;
}
// Implementing the fromString class
class fromString
{
protected $role;
public function __construct(string $role)
{
$this->role = $role;
}
public function getRole(): string
{
... | magicoder | php |
You are tasked with creating a program that can parse and extract attribute names and values from a given input string. The input string will contain lines of text, and each line may contain one or more attribute-value pairs in the format `@attr name value`. The attribute name and value are separated by a colon, and th... | ```python
def extract_attributes(input_string):
attributes = {}
lines = input_string.split('\n')
for line in lines:
if line.startswith('@attr'):
parts = line.split()
if len(parts) >= 4:
attr_name = parts[2]
attr_value = ' '.join(parts[3:])
... | magicoder | python |
You are tasked with implementing a function that validates a set of parameters passed to a function. The function takes three arguments: `args`, a slice of optional rational numbers; `kind`, a string representing the kind of parameters being validated; and `with_kind`, a string representing the kind of parameters that ... | ```rust
use num::rational::Rational;
use std::error::Error;
fn validate_parameters(
args: &[Option<Rational>],
kind: &str,
with_kind: &str,
) -> Result<(), Error> {
if args.iter().all(|v| v.is_none()) {
Ok(())
} else {
Err(Error::error(format!(
"{} parameters may not be ... | magicoder | rust |
You are tasked with creating a unit test for a Python web application using the Django framework. The application includes a feature that sends an email to users after they perform a certain action on the site. Your goal is to write a unit test to verify that the email sent contains the correct information.
The code s... | ```python
from django.test import TestCase
from django.core import mail
from yourapp.models import Site # Import the Site model from your Django app
class EmailTestCase(TestCase):
def test_email_content(self):
# Create a test site
test_site = Site.objects.create(name="Test Site")
# Perfor... | magicoder | python |
You are working on a project that involves implementing a neural network using PyTorch. As part of this project, you need to create a custom loss function that incorporates both the mean squared error (MSE) and a regularization term. To achieve this, you decide to use PyTorch's autograd functionality to define a custom... | ```python
import torch
from torch.autograd import Variable
def custom_loss(predicted, target):
mse_loss = torch.mean((predicted - target) ** 2) # Compute mean squared error
regularization_term = torch.norm(predicted, p=2) # Compute L2 norm of predicted tensor
combined_loss = mse_loss + regularization_ter... | magicoder | python |
You are tasked with implementing a language detection function that takes a text input and determines the language in which the text is written. The function should utilize the provided code snippet as a starting point and extend it to support multiple languages using a language detection library.
Your task is to comp... | ```python
import langdetect
def detect_language(text, result_language=None):
try:
detected_lang = langdetect.detect(text)
if result_language and detected_lang != result_language:
return translate_text(text, detected_lang, result_language)
return detected_lang
except langdete... | magicoder | python |
You are tasked with creating a custom error handling system for a Rust application. Your goal is to define a custom error type and implement the necessary traits to enable error propagation and conversion from other error types.
Define a custom error type called `AppError` using the `thiserror` crate, which provides a... | ```rust
use thiserror::Error;
// Define a custom error type using the thiserror crate
#[derive(Error, Debug)]
pub enum AppError {
#[error("Git {0}")]
Git(#[from] git2::Error),
#[error("")]
Editor,
#[error("Fail to build plugin: {0}")]
Build(String),
#[error("Plugin is not installed")]
P... | magicoder | rust |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.