query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with implementing a simple key-value store using a Java class. The key-value store should support the following operations: `put(key, value)`, `get(key)`, and `remove(key)`. The `put` operation should add a new key-value pair or update the value for an existing key. The `get` operation should return the ... | ```java
import java.util.HashMap;
import java.util.Map;
public class KeyValueStore {
private Map<String, String> store;
public KeyValueStore() {
this.store = new HashMap<>();
}
public void put(String key, String value) {
store.put(key, value);
}
public String get(String key) ... | magicoder | java |
You are tasked with implementing a Python class that manages a queue of views for a chatbot application. The chatbot is designed to display different views to users based on their interactions. The provided code snippet imports the `ativaBotView` class from a module.
Your task is to create a `ViewQueue` class that all... | ```python
class ativaBotView:
def __init__(self, view_id, view_content):
self.view_id = view_id
self.view_content = view_content
def display_view(self):
print(self.view_content)
class ViewQueue:
def __init__(self):
self.queue = []
def add_view(self, view):
self... | magicoder | python |
You are tasked with implementing a singly linked list in Rust. The `list_node` module provides a skeleton for the `ListNode` struct, which represents a node in the linked list. Your goal is to complete the implementation of the `ListNode` struct and its associated methods to create a fully functional singly linked list... | ```rust
pub mod list_node {
pub struct ListNode {
pub val: i32,
pub next: Option<Box<ListNode>>,
}
impl ListNode {
pub fn new(val: i32) -> Self {
ListNode { val, next: None }
}
pub fn append(&mut self, val: i32) {
let mut current = self;
... | magicoder | rust |
You are tasked with simulating a simplified card game scoring system. The game consists of multiple rounds, and each round involves players selecting a card and voting on other players' cards. The provided code snippet is a part of the game logic, where players make their moves and the game state is updated.
Your task... | ```python
def calculate_final_scores(round_results, player_scores):
for result in round_results:
round_winner, round_card, story_card, voted_cards = result
player_scores[round_winner] += round_card # Add score for playing the highest card
max_voted_card = max(set(voted_cards), key=voted_car... | magicoder | python |
You are tasked with creating a program that generates a 3D plot of a mathematical function using Python's Matplotlib library. The function to be plotted is defined as:
\[ z = \sin(\sqrt{x^2 + y^2}) \]
Your program should take the following steps:
1. Define the range and resolution for the x and y values.
2. Calculate... | ```python
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Define the range and resolution for the x and y values
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
x, y = np.meshgrid(x, y)
# Calculate the corresponding z values using the given mathematical function
z ... | magicoder | python |
You are tasked with creating a function that extracts the text content within HTML tags. Given an HTML snippet as input, the function should return a list of all the text content within the tags.
Function Signature: `def extract_html_content(html: str) -> List[str]`
**Input**
- The input `html` (1 <= len(html) <= 100... | ```python
from typing import List
import re
def extract_html_content(html: str) -> List[str]:
# Use regular expression to find all text content within HTML tags
pattern = r'>([^<]+)<'
matches = re.findall(pattern, html)
return matches
``` | magicoder | python |
You are tasked with implementing a custom trait `Endian` for the `f64` type in Rust. The trait should provide methods to convert the endianness of the floating-point number from little-endian to big-endian and vice versa.
The `Endian` trait should have the following methods:
1. `get(&self) -> f64`: This method should ... | ```rust
use std::mem;
trait Endian {
fn get(&self) -> f64;
fn set(&mut self, value: f64);
}
impl Endian for f64 {
fn get(&self) -> f64 {
unsafe { mem::transmute(mem::transmute::<f64, u64>(*self).to_le()) }
}
fn set(&mut self, value: f64) {
*self = unsafe { mem::transmute(mem::tran... | magicoder | rust |
You are tasked with implementing a Python class called `Fraction` to represent fractions and perform basic arithmetic operations on them. The class should have the following functionalities:
- Initialize a fraction with a numerator and a non-zero denominator.
- Provide a string representation of the fraction in the for... | ```python
class Fraction:
def __init__(self, numerator, denominator):
if denominator == 0:
raise ValueError("Denominator cannot be zero")
self.numerator = numerator
self.denominator = denominator
def __str__(self):
return f"{self.numerator}/{self.denominator}"
d... | magicoder | python |
You are tasked with creating a function that parses a Content Security Policy (CSP) string and extracts specific directives and their values. A CSP string is a set of policies that controls the resources a web page is allowed to load. The directives in a CSP string specify the allowed sources for various types of conte... | ```javascript
function parseCSP(cspString) {
const directives = cspString.split(';').map(directive => directive.trim());
const parsedCSP = {};
directives.forEach(directive => {
const [name, valueString] = directive.split(' ');
const values = valueString.split(' ').filter(value => value !== '');
pars... | magicoder | javascript |
You are tasked with implementing a video streaming application using the GStreamer multimedia framework in C++. The application needs to read video frames from a source and stream them at a specified frame rate and resolution. You are provided with a code snippet that initializes the video streaming process and logs th... | ```cpp
// Initialize the video source and set it as the input for the streaming application
GstElement *source = gst_element_factory_make("filesrc", "source");
g_object_set(G_OBJECT(source), "location", "path_to_video_file", NULL);
// Configure the streaming parameters such as resolution and frame rate
GstCaps *caps =... | magicoder | cpp |
You are tasked with implementing a function to compare experimental results with expected values, taking into account a certain level of tolerance. The function should compare each experimental result with the corresponding expected value and determine if they are within the specified tolerance.
Write a function `comp... | ```python
def compare_results(experimental, expected, tolerance):
result = []
for exp, exp_val in zip(experimental, expected):
result.append(abs(exp - exp_val) <= tolerance)
return result
# Test the function with the given example
experimental = [3.14, 2.71, 1.618]
expected = [3.141, 2.718, 1.62]
t... | magicoder | python |
You are tasked with implementing a test builder for a hypothetical testing framework. The provided code snippet is a part of the test builder class, which is used to construct and execute test scenarios for a program called TCalamariProgram. The test builder allows users to define the arrangement of test actions, speci... | ```csharp
public class ActionHandlerTestBuilder<TCalamariProgram>
{
private readonly List<Action<TestActionHandlerContext<TCalamariProgram>>> arrangeActions = new List<Action<TestActionHandlerContext<TCalamariProgram>>>();
private Action<TestActionHandlerResult> assertAction;
private Action<TestActionHandle... | magicoder | csharp |
You are tasked with creating a function to encrypt a message using a modified Caesar cipher. The function `encrypt(message, key_one, key_two)` takes three parameters: `message` (a string), `key_one` (an integer), and `key_two` (an integer). The function should return the encrypted message based on the following rules:
... | ```python
def encrypt(message, key_one, key_two):
symbols = ' abcdefghjklmnopqrstuvwxyz'
new_message = ''
for char in message:
index = symbols.find(char)
encrypted_index = (index + key_one) * key_two % len(symbols)
new_message += symbols[encrypted_index]
return new_message
``` | magicoder | python |
You are working on a Django web application for an e-commerce platform. The application has a checkout process that involves selecting an address, choosing a payment method, and making the payment. The relevant URL patterns for this process are defined in the `urls.py` file as shown in the code snippet below:
```pytho... | ```python
# views.py
from django.shortcuts import render
from django.views import View
from django.http import HttpResponse
class CheckOut(View):
def get(self, request, address_pk):
# Retrieve the address details using address_pk
address = Address.objects.get(pk=address_pk)
# Render the ch... | magicoder | python |
You are tasked with creating a function that calculates the sum of all prime numbers within a given range. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Your function should take two integers, `start` and `end`, as input and return the sum of all prime numbers ... | ```python
def is_prime(num):
if num < 2:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
def sum_of_primes(start, end):
prime_sum = 0
for num in range(max(2, start), end + 1):
if is_prime(num):
prime_sum ... | magicoder | python |
You are tasked with implementing the quicksort algorithm in Python. Quicksort is a comparison-based sorting algorithm that uses a divide-and-conquer strategy to sort an array or list. The algorithm selects a "pivot" element from the array and partitions the other elements into two sub-arrays according to whether they a... | ```python
def quicksort(arr, l, r):
if l < r:
pivot = partition(arr, l, r)
quicksort(arr, l, pivot - 1)
quicksort(arr, pivot + 1, r)
return arr
def partition(arr, l, r):
pivot = arr[r] # Choosing the last element as the pivot
i = l - 1 # Index of smaller element
for j in r... | magicoder | python |
You are tasked with implementing a Python class that manages a collection of word vectors and provides functionality to perform operations on these vectors. The class should support adding new word vectors, searching for specific word vectors, and calculating the similarity between two word vectors.
You are given a co... | ```python
import math
class WordVectorCollection:
def __init__(self):
self.word_vectors = {}
def add_vector(self, word, vector):
self.word_vectors[word] = vector
def find_vector(self, word):
return self.word_vectors.get(word, None)
def calculate_similarity(self, word1, word2)... | magicoder | python |
You are tasked with implementing a Python class that represents a Protocol Buffers message definition. Protocol Buffers is a method of serializing structured data, and it allows you to define the structure of your data once and then use special generated source code to easily write and read your structured data to and ... | ```python
class MessageDefinition:
def __init__(self, is_extendable, syntax, extension_ranges, oneofs, serialized_start, serialized_end):
self.is_extendable = is_extendable
self.syntax = syntax
self.extension_ranges = extension_ranges
self.oneofs = oneofs
self.serialized_star... | magicoder | python |
You are tasked with creating a program that simulates a contact management system. The system should display a list of contacts and their details when a contact is selected. You are given a partial code snippet from a web application that displays contact details. The snippet uses Razor syntax, a server-side markup lan... | C# Class for Contact:
```csharp
public class Contact
{
public string Name { get; set; }
public string Email { get; set; }
public string PhoneNumber { get; set; }
}
```
Controller Action to Populate Contacts:
```csharp
public ActionResult Index()
{
List<Contact> contacts = new List<Contact>
{
... | magicoder | csharp |
You are working on a data processing algorithm that involves segmenting a time series signal into multiple segments. Your task is to implement a function that takes in a time series signal, the number of segments to divide it into, and a sample length, and then returns a list of segment indices. The segment indices rep... | ```python
def segment_indices(signal, num_segment, sample_length):
segment_indices = []
y_length = len(signal)
hopping = (y_length - sample_length) / (num_segment - 1) # Calculate the hopping step size
for i in range(num_segment):
segment_indices.append(int(i * hopping)) # Append the starting... | magicoder | python |
You are tasked with implementing a class for creating collision shapes in a physics engine. The class should support different types of collision shapes, such as cylinders, spheres, and boxes. Your task is to design a method that creates a collision shape based on the given parameters.
You are provided with a code sni... | ```cpp
#include <iostream>
enum class ECollisionShapeType {
ECST_CYLINDER,
ECST_SPHERE,
ECST_BOX
};
class Node {
// Define Node properties
};
class CollisionShape {
private:
Node node;
double mass;
ECollisionShapeType type;
public:
void createShape(double overrideMargin) {
sw... | magicoder | cpp |
You are tasked with implementing a simplified version of a Dependency Injection Container in PHP. A Dependency Injection Container is a design pattern used to manage the instantiation and injection of dependencies in an application. In this problem, you will create a class that can register and resolve dependencies.
Y... | ```php
class DependencyContainer {
private $dependencies = [];
public function register($name, $resolver) {
$this->dependencies[$name] = $resolver;
}
public function resolve($name) {
if (array_key_exists($name, $this->dependencies)) {
$resolver = $this->dependencies[$name];... | magicoder | php |
You are tasked with implementing a Deterministic Finite Automaton (DFA) class in C++. A DFA is a finite automaton that accepts or rejects strings of symbols and produces a unique computation for each input string. Your task is to complete the implementation of the DFA class by adding a method to check whether the DFA i... | ```cpp
#include <iostream>
#include <vector>
#include <set>
class DFA {
private:
std::vector<char> alphabet;
std::set<int> states;
int initialState;
std::set<int> finalStates;
std::vector<std::vector<int>> transitionFunction;
public:
DFA(const std::vector<char>& alph, const std::set<int>& sts,... | magicoder | cpp |
You are tasked with implementing a custom table model for a grammar checking application. The table model is responsible for managing and displaying a list of grammar checking results. The provided code snippet is a part of the custom table model class, and it includes a method to retrieve the selected grammar checking... | ```java
// GrammarResult class representing a single grammar checking result
public class GrammarResult {
private String errorMessage;
private int lineNumber;
public GrammarResult(String errorMessage, int lineNumber) {
this.errorMessage = errorMessage;
this.lineNumber = lineNumber;
}
... | magicoder | java |
You are working on a project that involves parsing an HTML file containing color information. The HTML file contains a table with color names and their corresponding RGB values. You need to write a Python function to extract this information and store it in a dictionary for further processing.
Write a function `parse_... | ```python
from bs4 import BeautifulSoup
def parse_colors_from_html(html_file_path):
color_map = {}
with open(html_file_path) as f:
text = f.read()
soup = BeautifulSoup(text, 'html.parser')
table = soup.find('table')
rows = table.find_all('tr')[1:] # Skip the header row
for row in rows:... | magicoder | python |
You are tasked with creating a function to analyze the spread of an epidemic. The function `get_epidemic` takes a list `result` as input, where each element represents the number of infected individuals for a specific day. Your task is to implement the function to determine the peak day of the epidemic and the total nu... | ```python
def get_epidemic(result):
peak_day = result.index(max(result)) + 1 # Find the peak day (1-indexed)
epidemic_duration = len(result) # Assume the epidemic lasts until the last day by default
for i in range(peak_day, len(result)):
if result[i] < result[i - 1]: # Check if the number of inf... | magicoder | python |
You are tasked with creating a build script for a web application using npm. The build script should perform several tasks, including transpiling code, bundling assets, and optimizing resources. Your goal is to write a custom npm build script that accomplishes these tasks efficiently.
Your build script should perform ... | To achieve the specified tasks, you can create a custom build script in the `package.json` file. Below is an example of how the build script can be defined:
```json
{
"scripts": {
"build": "babel src -d dist && webpack --mode production && npm run copy-assets"
"copy-assets": "cp -r src/assets dist/assets"
... | magicoder | json |
You are tasked with creating a Python function that interacts with a web browser using Selenium WebDriver. Your function should handle a specific exception and execute a JavaScript command to update the session status in a browser testing environment.
Write a function called `handle_timeout_exception` that takes two p... | ```python
from selenium.common.exceptions import TimeoutException
def handle_timeout_exception(driver, exception_type):
if exception_type == "TimeoutException":
js_command = 'browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed", "reason": "Title not matched"}}'
driv... | magicoder | python |
You are working on a secure data processing system that involves encrypting row data using a symmetric key. The system consists of a driver and multiple enclaves, and they share a common symmetric key for encryption. The key is initially set on the driver as a byte array and is securely sent to the enclaves if attestat... | ```c
#include <stdio.h>
#include <string.h>
#define CIPHER_KEY_SIZE 32
// Simulated enclave structure for demonstration purposes
typedef struct {
unsigned char enclave_key[CIPHER_KEY_SIZE];
} Enclave;
// Function to securely send the shared key to the enclaves after attestation succeeds
void sendSharedKeyToEncla... | magicoder | c |
You are tasked with implementing a function that processes an array of city objects and transforms them into a new array with specific properties. Each city object contains the following properties: `name` (string), `adminName1` (string), `countryName` (string), `countryCode` (string), `lat` (string), and `lng` (string... | ```javascript
function processCities(cities) {
return cities.map(city => ({
name: city.name,
region: city.adminName1,
countryName: city.countryName,
countryCode: city.countryCode,
coords: {
latitude: Number(city.lat),
longitude: Number(city.lng),
},
}));
}
``` | magicoder | javascript |
You are tasked with creating a function that simulates a simplified version of a task scheduler. The function should take in an array of tasks, each represented by a unique identifier and a time duration required to complete the task. The scheduler should execute the tasks in a way that minimizes the total time taken t... | ```javascript
function minimizeTaskCompletionTime(tasks) {
const taskMap = new Map();
for (const task of tasks) {
if (!taskMap.has(task.id)) {
taskMap.set(task.id, []);
}
taskMap.get(task.id).push(task.duration);
}
let totalTime = 0;
for (const durations of taskMap.values()) {
durations... | magicoder | javascript |
You are tasked with implementing a reinforcement learning agent using TensorFlow. The agent's neural network architecture consists of policy and value layers. The policy layers are responsible for outputting the probability distribution over the available actions, while the value layers estimate the expected cumulative... | ```python
import tensorflow as tf
class ReinforcementLearningAgent:
def __init__(self, action_size, use_softplus_activation):
self.action_size = action_size
self.use_softplus_activation = use_softplus_activation
# Policy layers
if self.use_softplus_activation:
self.poli... | magicoder | python |
You are working on a waste management system that uses sensors to detect the fill level of waste bins. Each bin has a sensor that periodically sends data about the fill level. The data is received in the form of a dictionary where the keys are the bin IDs and the values are tuples containing the current fill level and ... | ```python
def calculate_fill_percentage(data):
fill_percentages = {}
for bin_id, fill_data in data.items():
if fill_data[0] is not None and fill_data[1] is not None and fill_data[1] != 0:
fill_percentages[bin_id] = (fill_data[0] / fill_data[1]) * 100
else:
fill_percentage... | magicoder | python |
You are tasked with implementing a parallelized feature selection algorithm using the BaggingClassifier from scikit-learn. The goal is to create a program that efficiently selects the most important features from a given dataset using parallel processing.
Your task is to complete the function `parallel_feature_selecti... | ```python
import numpy as np
from sklearn.ensemble import BaggingClassifier
from joblib import Parallel, delayed
from sklearn.base import clone
def parallel_feature_selection(X_train, y_train, n_estimators, n_jobs):
def fit_and_get_feature_importances(estimator, X, y):
estimator.fit(X, y)
return es... | magicoder | python |
You are tasked with implementing a Python class that simulates a simple discriminator for a machine learning model. The discriminator is responsible for distinguishing between real and fake data. Your task is to complete the implementation of the `Discriminator` class by adding a method that calculates the accuracy of ... | ```python
class Discriminator:
def __init__(self, units):
super(Discriminator, self).__init__(name='discriminator_abc')
self.units = units
self.predictions = []
def train(self, data, labels):
# Your implementation for training the discriminator goes here
# For example, y... | magicoder | python |
You are tasked with implementing a multi-threaded counter using Rust's atomic operations. The counter should support two operations: `add` and `get_count`. The `add` operation should increment the counter by a given value, and the `get_count` operation should return the current value of the counter.
Your task is to im... | ```rust
use std::sync::Arc;
use std::thread;
fn main() {
let counter = Arc::new(Counter::new());
let mut handles = vec![];
for _ in 0..10 {
let counter = Arc::clone(&counter);
let handle = thread::spawn(move || {
counter.add(1);
});
handles.push(handle);
}
... | magicoder | rust |
You are tasked with implementing a TypeScript type that represents a named value. The type should be generic and handle both cases where the value is present and where it is not.
You need to define a TypeScript type `NamedValue<T>` that satisfies the following conditions:
- If the type `T` is `void`, the `NamedValue<T... | ```typescript
type NameIndicator = { name: string };
type NameIndicatorWithValue<T> = { name: string; value: T };
type NamedValue<T> = T extends void ? NameIndicator : NameIndicatorWithValue<T>;
```
In the solution, we define three types:
- `NameIndicator` represents a named value without a specific value, containing o... | magicoder | typescript |
You are tasked with implementing a simple neural network using PyTorch to perform binary classification on a synthetic dataset. The dataset consists of two features and a binary target variable. Your goal is to create a neural network model, train it on the given dataset, and evaluate its performance.
You are provided... | ```python
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
from sklearn.model_selection import train_test_split
# Set up word vectors and biases
embed_size = 2
l_embed, r_embed = [
[torch.nn.Parameter(torch.from_numpy(np.random.normal(0, 0.01, (embed_size, 1)))),
torch.nn.Param... | magicoder | python |
You are tasked with creating a Python class that performs Bayesian inference using the PyStan library. Your class should be able to handle data from multiple schools and perform sampling to estimate the parameters of a statistical model. Additionally, you need to implement a method for validating the sampled data.
You... | ```python
import pystan
class BayesianInference:
def __init__(self, sm, schools_dat):
self.sm = sm
self.schools_dat = schools_dat
def perform_sampling(self):
fit = self.sm.sampling(data=self.schools_dat, iter=1000, chains=4, n_jobs=-1)
return fit
def validate_data(self, fi... | magicoder | python |
You are tasked with implementing a custom size policy algorithm for a text browser widget in a graphical user interface (GUI) application. The size policy determines how the widget should be stretched or shrunk in a layout. The provided code snippet initializes the size policy for the text browser widget using the Qt f... | ```python
from PyQt5 import QtWidgets
def calculateCustomSizePolicy(currentWidth, currentHeight, maxWidth, maxHeight):
if currentWidth < maxWidth / 2 and currentHeight < maxHeight / 2:
return (QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding, 1, 1)
else:
return (QtWidgets.QSizeP... | magicoder | python |
You are tasked with simulating a game where the player's objective is to reach a target score by collecting points. As the player's total score reaches or exceeds the target score, the game's difficulty level increases, resulting in certain game elements being upgraded. The game has two specific upgrades: increasing th... | ```javascript
function upgradeGameElements(totalScore, targetScore) {
if (totalScore >= targetScore) {
// Increase difficulty level once target has been reached
const eggSpeed = calculateUpgradedSpeed(totalScore, 1);
const bladeSpeed = calculateUpgradedSpeed(totalScore, 1);
return [eggSpeed, bladeSpee... | magicoder | javascript |
You are tasked with implementing two functions for performing SIMD (Single Instruction, Multiple Data) operations: `simd_saturating_add` and `simd_saturating_sub`. These functions are designed to perform saturating arithmetic operations on SIMD vectors, ensuring that the results are clamped within the range of the data... | ```rust
use std::arch::x86_64::*;
pub(crate) fn simd_saturating_add<T>(x: T, y: T) -> T
where
T: SimdVector,
{
unsafe { x.add_saturate(y) }
}
pub(crate) fn simd_saturating_sub<T>(x: T, y: T) -> T
where
T: SimdVector,
{
unsafe { x.sub_saturate(y) }
}
```
In the solution, we use the `std::arch::x86_64::... | magicoder | rust |
You are tasked with implementing a Python class for controlling a Fixed Focus Kirkpatrick-Baez Mirror. The mirror is part of the 1st gen Toyama designs with LCLS-II Beckhoff motion architecture. Your task is to create a class called `FFMirror` that inherits from `BaseInterface` and `GroupDevice`. The class should have ... | ```python
class FFMirror(BaseInterface, GroupDevice):
"""
Fixed Focus Kirkpatrick-Baez Mirror.
1st gen Toyama designs with LCLS-II Beckhoff motion architecture.
Parameters
----------
prefix : str
Base PV for the mirror.
Attributes
----------
prefix : str
Base PV fo... | magicoder | python |
You are tasked with creating a Python program that utilizes asynchronous I/O to read and process data from multiple files concurrently. Your program should read the contents of each file, perform a specific operation on the data, and then aggregate the results.
Your program should use the `aiofiles` library for asynch... | ```python
import aiofiles
import asyncio
from typing import List
async def count_word_occurrences(file_path: str, word: str) -> int:
try:
async with aiofiles.open(file_path, mode='r') as file:
contents = await file.read()
return contents.count(word)
except FileNotFoundError:
... | magicoder | python |
You are tasked with implementing a function to parse a custom language syntax and extract specific information from it. The syntax consists of a series of operations and names separated by pipes and commas. Each operation is denoted by the keyword `op` followed by a pair of parentheses containing the operation's argume... | ```python
import re
def parse_syntax(syntax):
operations = re.findall(r'op\|\'([^\']*)\'', syntax)
names = re.findall(r'name\|\'([^\']*)\'', syntax)
newlines = syntax.count('nl|\'\\n\'')
strings = re.findall(r'string\|\'([^\']*)\'', syntax)
return {
"operations": operations,
"n... | magicoder | python |
You are tasked with implementing a function that loads a Keras model from a file and returns the model object. The function takes two parameters: `extension`, a string representing the extension of the file where the model is saved, and `custom_objects`, a dictionary containing any custom objects (such as custom loss f... | ```python
from keras.models import load_model
def load_keras_model(extension: str, custom_objects: dict) -> Any:
if extension == 'h5':
model = load_model('saved_model.h5', custom_objects=custom_objects)
return model
else:
raise ValueError("Unsupported file extension. Only .h5 files are ... | magicoder | python |
You are tasked with implementing a generator function that resolves values based on certain criteria. The function should take in a value, an array of arguments, and a ResolveInfo object, and yield specific values based on the type of the input value.
You are given the following code snippet as a starting point:
```p... | ```php
public function resolveValues($value, array $args, ResolveInfo $info) {
if ($value['type'] === 'string') {
yield strlen($value);
} elseif ($value['type'] === 'array') {
yield count($value);
} elseif ($value['type'] === 'integer') {
yield $value * $value;
}
}
``` | magicoder | php |
You are working on a bioinformatics pipeline to analyze DNA sequencing data. As part of this pipeline, you need to download and process several input files. The provided code snippet is a part of a shell script used in this pipeline. It prints the values of four variables (`bam_to_call`, `chrom_sizes`, `hotspot_mappabl... | ```bash
#!/bin/bash
# Print the values of the variables
echo "* Value of bam_to_call: '$bam_to_call'"
echo "* Value of chrom_sizes: '$chrom_sizes'"
echo "* Value of hotspot_mappable: '$hotspot_mappable'"
echo "* Include minor chromsosomes: '$minor_chroms'"
# Download and process the files
bam_root=$(dx describe "$... | magicoder | shell |
You are tasked with creating a Python program that utilizes the YouTube Transcript API to retrieve and process the transcript of a given YouTube video. The YouTube Transcript API allows you to fetch the transcript of a video by providing its unique video ID. Your program should be able to handle the retrieval of the tr... | ```python
from typing import List, Dict
from youtube_transcript_api import YouTubeTranscriptApi
def count_word_occurrences(video_id: str, words: List[str]) -> Dict[str, int]:
# Retrieve the transcript for the given video ID
transcript = YouTubeTranscriptApi.get_transcript(video_id)
# Initialize a dict... | magicoder | python |
You are tasked with implementing a custom sorting algorithm for a list of objects based on specific attributes. The objects are represented as dictionaries, and the sorting criteria are defined in a separate dictionary called `options`. The `options` dictionary contains a key-value pair where the key is `'ordering'` an... | ```python
def custom_sort(objects, options):
ordering = options.get('ordering', [])
def custom_key(obj):
return tuple(obj[attr] for attr in ordering)
return sorted(objects, key=custom_key)
```
The `custom_sort` function first retrieves the list of attributes to be used for sorting from th... | magicoder | python |
You are required to implement a function `remove_all` that takes in two parameters: a string `s` and a character `c`. The function should remove all occurrences of the character `c` from the string `s` and return the modified string. You are not allowed to use any built-in string manipulation functions for this task.
... | ```python
def remove_all(s, c):
result = ''
for char in s:
if char != c:
result += char
return result
# Test the function
if __name__ == '__main__':
print(remove_all('hello world', 'l')) # Output: 'heo word'
``` | magicoder | python |
You are tasked with writing a Python unit test for a network extension driver called `NuageSubnetExtensionDriver`. The test should ensure that the `initialize` method of the driver is called with the correct configuration settings. The code snippet provided is a partial test case using the `mock` library to patch certa... | ```python
import unittest
from unittest import mock
from your_module import NuageSubnetExtensionDriver, RESTProxyServer, VsdClientImpl
class TestNuageSubnetExtensionDriver(unittest.TestCase):
@mock.patch.object(RESTProxyServer, 'raise_rest_error')
@mock.patch.object(VsdClientImpl, 'verify_cms')
def test_in... | magicoder | python |
You are tasked with creating a web application using the Yii PHP framework. Your goal is to implement a feature that allows users to submit data through a form and then process that data on the server side. The provided code snippet is a part of the server-side processing logic. Your task is to complete the implementat... | ```php
// Define the model class to represent the form data
class FormData extends \yii\db\ActiveRecord
{
// Define attributes to represent the form fields
public $field1;
public $field2;
// Add validation rules for the form fields
public function rules()
{
return [
[['field1... | magicoder | php |
You are working on a Python library for managing default and validation settings for various objects. The code snippet provided is a part of a class that handles setting default and validation kinds for attributes. The `set_default_kind` and `set_validate_kind` methods are used to set the default and validation kinds, ... | ```python
class AttributeManager:
DEFAULT_FACTORY = 1
USER_DEFAULT = 2
DEFAULT_VALUE = 3
USER_VALIDATE = 4
def __init__(self):
self.default_kinds = {}
self.validate_kind = None
def set_default_kind(self, kind, value):
self.default_kinds[kind] = value
def set_valida... | magicoder | python |
You are working on a medical imaging project and need to process diffusion MRI data using Python libraries. Your task is to write a Python function that takes a diffusion MRI image file as input and performs a specific processing step using the `numpy`, `nibabel`, and `dipy` libraries.
Write a function `process_diffus... | ```python
import numpy as np
import nibabel as nib
from dipy.reconst.shm import sh_to_sf_matrix
def process_diffusion_mri(input_file_path, output_file_path):
"""
Process the diffusion MRI image and save the processed image to the output file path.
Args:
input_file_path (str): File path to the input di... | magicoder | python |
You are tasked with implementing a Python class that manages settings for an image processing widget. The class should handle the initialization of these settings and provide a method to update them. Additionally, you need to create a function that calculates the total size of JavaScript files required for the widget's... | ```python
class ImgerWidget:
def __init__(self, attrs=None, **kwargs):
self.imger_settings = attrs['imger_settings'] if attrs and 'imger_settings' in attrs else []
super(ImgerWidget, self).__init__(**kwargs)
def update_settings(self, new_settings):
self.imger_settings = new_settings
de... | magicoder | python |
You are given a list of integers representing the scores of a game. The game has a rule that a player's score is the sum of the scores of the last two turns. However, if the player's score is greater than or equal to 100, the player is eliminated from the game. Your task is to write a function to determine the maximum ... | ```swift
func maxPossibleScore(_ scores: [Int]) -> Int {
var maxScore = 0
var dp = Array(repeating: 0, count: scores.count + 2)
for i in 2..<scores.count + 2 {
dp[i] = max(dp[i - 1], dp[i - 2]) + scores[i - 2]
if dp[i] >= 100 {
break
}
maxScore = dp[i]
}
... | magicoder | swift |
You are tasked with implementing a simple version of a geographical screen display system. The `GeoScreen` class is provided as a starting point, and you need to extend its functionality by adding methods to display geographical information.
The `GeoScreen` class has the following attributes and methods:
- `width` and... | ```python
class GeoScreen:
def __init__(self, width, height):
self.width = width
self.height = height
def set_width(self, new_width):
self.width = new_width
def set_height(self, new_height):
self.height = new_height
def display(self, message):
print(message)
... | magicoder | python |
You are working on a user management system for a software application. The system includes various permissions and password management functionalities. The provided code snippet includes declarations of variables related to permissions and password management. Your task is to implement a function that will update the ... | ```swift
func updatePasswordAndPermissions() {
if CurrentPasswordEncoded == PasswordEncoded {
PasswordEncoded = NewPasswordEncoded
}
if PermisoVisualizarFormato {
let formattedReport = FETipoReporte(type: "Formatted Report")
Consultas.append(formattedReport)
}
if !PermisoSa... | magicoder | swift |
You are tasked with creating a Python module that interfaces with a hardware device using the ctypes library to access a C library. The C library provides functions for setting event handlers and message handlers for device-related events. The provided code snippet shows the usage of the ctypes library to define the ar... | ```python
import platform
import ctypes
from ctypes import c_int, HANDLE, HWND
class DeviceEventHandler:
def __init__(self, api):
self.api = api
def set_event_device_added(self, handler):
if platform.system() == 'Windows':
self.api.LstSetEventDeviceAdded.argtypes = [HANDLE]
... | magicoder | python |
You are tasked with creating a script that automates the process of installing missing autotools files and performing any other one-time setup for a freshly cloned git repository. The script should also handle the case where `configure.ac` is modified, requiring the `autoreconf` command to be rerun to update the `confi... | ```bash
#!/bin/bash
# Check if configure.ac has been modified
if [ -n "$(git status --porcelain configure.ac)" ]; then
# If modified, run autoreconf -i to update configure script
autoreconf -i
else
# If not modified, still run autoreconf -i as a convenience script
autoreconf -i
fi
```
In this solution... | magicoder | shell |
You are tasked with creating a Python function that interacts with a Layer Service API to retrieve information about different layers in a GIS (Geographic Information System) application. The function should take a layer name as input and make a GET request to the Layer Service API to fetch the details of the specified... | ```python
import requests
def get_layer_info(layer: str) -> dict:
base_url = 'https://example.com/api' # Replace with the actual base URL of the Layer Service API
uri = f'/layers/{layer}/'
method = 'GET'
config = {
'uri': base_url + uri,
'method': method
}
response = ... | magicoder | python |
You are tasked with implementing a function to parse and process log messages from a system monitoring tool. The log messages are generated by the system and contain information about updated data records. Your task is to extract the record ID from each log message and store it in a data structure for further analysis.... | ```python
import logging
log = logging.getLogger(__name__)
def process_log_message(log_message):
"""
Extract the record ID from the log message and store it for further analysis.
Args:
log_message (str): The log message containing the updated data record information.
Returns:
str: The extrac... | magicoder | python |
You are tasked with implementing a function to handle scrolling behavior in a text panel. The function takes in several parameters related to the current view and the desired position to scroll to. Your task is to determine the appropriate scrolling action based on the given parameters.
The function is provided with t... | ```python
def handle_scroll_behavior(fheight, fbottom, ftop, vheight, panel, wanted_lines, vtop, vbottom, JUMP_COEFFICIENT):
scroll_to_line = lambda panel, line, animate: None # Placeholder for scroll_to_line function
if fheight <= vheight:
scroll_to_line(panel, ftop, animate=False)
return
... | magicoder | python |
You are tasked with creating a program that analyzes a given code snippet to identify and count the occurrences of specific HTML elements and attributes. The code snippet provided is a segment of an HTML file, and your program should be able to parse it and extract relevant information.
Write a function or method `ana... | ```python
import re
def analyzeHtmlCode(html_code):
element_pattern = r'<(\w+)[^>]*>'
attribute_pattern = r'(\w+)="([^"]*)"'
elements = re.findall(element_pattern, html_code, re.IGNORECASE)
attributes = re.findall(attribute_pattern, html_code, re.IGNORECASE)
element_counts = {}
attribute_coun... | magicoder | python |
You are tasked with creating a Python function that calculates the distance between two geographical coordinates using the Haversine formula. The Haversine formula is a well-known equation used to calculate the distance between two points on the Earth given their longitude and latitude. The function should take four pa... | ```python
import math
def calculate_distance(start_lon, start_lat, end_lon, end_lat):
R = 6371 # Radius of the Earth in kilometers
start_lat_rad = math.radians(start_lat)
end_lat_rad = math.radians(end_lat)
delta_lat = math.radians(end_lat - start_lat)
delta_lon = math.radians(end_lon - start_lon)... | magicoder | python |
You are tasked with creating a Django view that renders a list of applications and modifies the CMS Toolbar based on certain conditions. The given code snippet is a part of a Django application and defines a class `AppListView` that inherits from `ListView`. The `App` model is associated with this view, and the queryse... | ```python
from django.urls import reverse
from django.views.generic import ListView
from cms.toolbar.items import SideframeItem, ModalItem, Break
from cms.toolbar_base import CMSToolbar
class AppListView(ListView):
model = App
queryset = App.objects.all()
def render_to_response(self, context, **response_k... | magicoder | python |
You are tasked with creating a Python script to automate the process of cloning a Git repository as a mirror. Your script should take a repository URL as input and clone the repository as a mirror using the `git` command. Additionally, the script should handle any potential errors that may occur during the cloning proc... | ```python
import subprocess
def clone_git_repo(repo_url: str) -> str:
try:
subprocess.run(['git', 'clone', repo_url, '--mirror'], check=True)
return "Repository cloned as a mirror successfully."
except subprocess.CalledProcessError as e:
return f"Failed to clone repository as a mirror: ... | magicoder | python |
You are tasked with creating a Python function that validates email addresses based on certain criteria. The function should take an email address as input and return a boolean value indicating whether the email address is valid or not.
The validation criteria for the email address are as follows:
1. The email addres... | ```python
import re
def validate_email(email):
# Check if the email is of text type
if not isinstance(email, str):
return False
# Check if the email contains a single "@" symbol
if email.count('@') != 1:
return False
# Check if the domain part contains at least one "."
... | magicoder | python |
You are tasked with implementing a CRC32 checksum calculation algorithm in C#. The CRC32 algorithm is commonly used to detect accidental changes to raw data, such as in network communications or storage. Your task is to complete the implementation of the CRC32 algorithm in the provided C# class.
You are given a partia... | ```csharp
namespace StreamDb.Internal.Support
{
public static class Crc32
{
public const uint DefaultPolynomial = 0xedb88320;
private static uint[] _table;
static Crc32()
{
_table = new uint[256];
for (uint i = 0; i < 256; i++)
{
... | magicoder | csharp |
You are given a simplified representation of a game board as a one-dimensional array `m` of boolean values. Each element in the array represents a cell on the game board, and the value `true` indicates that the cell is occupied. The game board is a straight line, and each cell has two adjacent cells except for the ends... | ```java
public boolean isValidMove(boolean[] m, int i) {
if (i < 0 || i >= m.length) {
return false; // Index out of bounds
}
if (i == 0) {
return m[i + 1]; // Check if the cell at index i is adjacent to an occupied cell
} else if (i == m.length - 1) {
return m[i - 1]; // Check i... | magicoder | java |
You are tasked with implementing a class that handles network addresses. The class should support both local station addresses and network addresses. The provided code snippet is a part of the address handling logic within the class. Your task is to complete the implementation of the class by adding methods to set and ... | ```python
import struct
class NetworkAddressHandler:
def __init__(self):
self.addrType = None
self.addrNet = None
self.addrAddr = None
self.addrLen = 0
def set_address_type(self, addr_type):
if addr_type.lower() == "local":
self.addrType = "localStationAddr"... | magicoder | python |
You are tasked with implementing a function to remove a file specified by its path. The function should handle any potential errors that may occur during the removal process.
You are given the following code snippet as a starting point:
```rust
use std::fs::{remove_file, PathBuf};
pub fn remove(path: &PathBuf) -> st... | ```rust
use std::fs::{remove_file, metadata};
use std::io;
use std::path::PathBuf;
pub fn remove(path: &PathBuf) -> std::io::Result<()> {
if let Ok(meta) = metadata(path) {
if meta.is_file() {
remove_file(path)?;
Ok(())
} else {
Err(io::Error::new(io::ErrorKind::... | magicoder | rust |
You are working on a financial application that utilizes a database to store ledger actions. The code snippet provided is a part of a Python script that interacts with the database to retrieve ledger actions based on certain criteria. The script uses a SQL query to fetch the required data and then executes the query us... | ```python
def retrieve_ledger_actions(cursor, query_filter, limit, bindings):
FREE_LEDGER_ACTIONS_LIMIT = 100 # Assuming a default limit for free ledger actions
query = 'SELECT * FROM (SELECT * from ledger_actions ORDER BY timestamp DESC LIMIT ?) ' + query_filter
# Construct the SQL query with the provided... | magicoder | python |
You are tasked with implementing a custom data structure called `FibonacciQueue` that combines the properties of a queue and a Fibonacci sequence generator. The `FibonacciQueue` should support the following operations:
1. `enqueue(value)`: Add the given value to the end of the queue.
2. `dequeue()`: Remove and return t... | ```python
class FibonacciQueue:
def __init__(self):
self.queue = []
def enqueue(self, value):
self.queue.append(value)
def dequeue(self):
if len(self.queue) > 0:
return self.queue.pop(0)
else:
return None
def generate_next(self):
if len(... | magicoder | python |
You are tasked with implementing a Python function that calculates the dual norm of a given vector. The dual norm of a vector x in a vector space is defined as the supremum of the dot product of x and any vector y in the space, such that the norm of y is less than or equal to 1. In other words, the dual norm of x is th... | ```python
import numpy as np
def dual_norm(vector):
norm = np.linalg.norm(vector) # Calculate the norm of the input vector
dual_norm = norm # Dual norm is equal to the norm for 2-dimensional vectors
return dual_norm
```
The solution uses the `numpy` library to calculate the norm of the input vector. For... | magicoder | python |
You are tasked with implementing a logging handler class in Python that can be used to test the logging behavior of a system. The logging handler should be capable of waiting for specific log messages, verifying the content of the log messages, and ensuring that certain conditions are met during the logging process.
Y... | ```python
import threading
import unittest
class LoggingHandler:
def __init__(self):
self.messages = {'debug': [], 'info': [], 'warning': [], 'error': [], 'critical': []}
self.lock = threading.Lock()
def wait_for_message(self, level, num_messages):
with self.lock:
while len... | magicoder | python |
You are tasked with creating a Python script that utilizes the mmdetection library to perform object detection on a set of images. The script should take in command-line arguments for the input image directory, output directory for the detected images, configuration file, and checkpoint file. Additionally, it should al... | ```python
from mmdet.apis import inference_detector, init_detector
from argparse import ArgumentParser
import os
import cv2
def object_detection_script(img_dir: str, out_dir: str, config: str, checkpoint: str, device: str) -> None:
# Initialize the detector
model = init_detector(config, checkpoint, device=devi... | magicoder | python |
You are working on a scientific computing project and need to implement a class for handling data vectors and operators. The code snippet provided is part of a larger class that deals with data manipulation and error calculation. Your task is to implement a method for handling error calculation in the given class.
You... | ```python
class DataVector:
def __init__(self, size):
self.values = [0] * size
def getValues(self):
return self.values
def sub(self, other):
for i in range(len(self.values)):
self.values[i] -= other[i]
class BOperator:
def mult(self, alpha, vector):
for i ... | magicoder | python |
You are tasked with implementing a function that processes a list of teams and their task statistics to generate a report. Each team is represented as a dictionary with the following keys: "id" (team ID), "score" (team's score), and "taskStats" (a list of dictionaries representing task statistics). Each task statistic ... | ```python
from typing import List, Dict, Union
def generate_report(teams: List[Dict[str, Union[int, str, List[Dict[str, Union[str, int]]]]]) -> List[Dict[str, Union[int, str, float]]]:
report = []
for team in teams:
total_score = team["score"] + sum(task["taskScore"] for task in team["taskStats"])
... | magicoder | python |
You are tasked with implementing a MapReduce program to process taxi trip data. The input data consists of key-value pairs, where the key is a LongWritable representing the trip ID, and the value is a Segment object representing a segment of the trip. Each Segment object contains information about the trip, including t... | ```java
@Override
public void reduce(LongWritable key, Iterable<Segment> values, Context context) throws IOException, InterruptedException {
// Create a map to store the total revenue for each date
Map<String, Double> dateRevenueMap = new HashMap<>();
// Iterate through the segments and calculate the total reven... | magicoder | java |
You are tasked with implementing a command-line interface (CLI) for a data storage application. The provided code snippet is a TypeScript function that extends the command-line arguments with an option to specify the filesystem location for the data storage.
Your task is to extend this functionality by creating a CLI ... | ```typescript
import yargs from "yargs";
import { declareStoreArgs, StoreArgs } from "./storeArgs"; // Assuming the storeArgs file is in the same directory
interface StoreCommandArgs extends StoreArgs {
key: string;
value: string;
}
declareStoreArgs<StoreCommandArgs>(yargs)
.command(
"store <key> <value>",
... | magicoder | typescript |
You are tasked with implementing a parallel computation algorithm for calculating the normal vectors of fluid-fluid contacts in a simulation. The provided code snippet is a part of a larger program that computes the normal vectors for fluid-fluid contacts using parallel iteration and a vector library.
Your task is to ... | ```rust
use rayon::prelude::*;
// Define the Vector type and its associated operations
struct Vector {
// Define the fields and operations for the Vector type
}
impl Vector {
fn zeros() -> Vector {
// Implement the zeros method to create a zero-initialized vector
}
}
// Define the Fluid type and ... | magicoder | rust |
You are tasked with creating a Python function that simulates a simple text-based game. The game involves a player navigating through a grid-based world, collecting treasures, and avoiding obstacles. The grid is represented as a 2D list, where each cell can contain one of the following characters:
- 'P': Represents the... | ```python
def play_game(grid):
rows, cols = len(grid), len(grid[0])
treasures = sum(row.count('T') for row in grid)
collected_treasures = 0
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
def is_valid_move(x, y):
return 0 <= x < rows and 0 <= y < cols and grid[x][y] != 'X'
def move(x, ... | magicoder | python |
You are tasked with creating a program that simulates a simple 2D array manipulation. The program should prompt the user to input elements for a 2D array, and then display the array in a matrix format.
Write a Java program that accomplishes the following:
1. Declare a 2D array of integers, `arr`, with dimensions `n x ... | ```java
import java.util.Scanner;
public class ArrayManipulation {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of rows for the 2D array:");
int n = sc.nextInt();
System.out.println("Enter the number of columns f... | magicoder | java |
You are tasked with creating a Java program to read and process data from a file. Your program should read a file and perform a specific operation on the data it contains.
Write a Java method that takes a File object as input and returns a modified byte array. The method should read the contents of the file into a byt... | ```java
import java.io.*;
public class FileProcessor {
public static byte[] processFile(File f) throws IOException {
int size = (int) f.length();
byte buff[] = new byte[size];
FileInputStream fis = new FileInputStream(f);
DataInputStream dis = new DataInputStream(fis);
dis.r... | magicoder | java |
You are tasked with creating a program that simulates a simple shell environment similar to zsh. Your program should be able to handle basic commands and execute corresponding actions. For this problem, you will focus on implementing a command parser that can identify and execute specific commands.
Your program should... | ```python
import os
def parse_command(command: str) -> str:
tokens = command.split()
if tokens[0] == "echo":
return " ".join(tokens[1:])
elif tokens[0] == "ls":
files = os.listdir()
return "\n".join(files)
elif tokens[0] == "pwd":
return os.getcwd()
elif tokens[0] ==... | magicoder | python |
You are tasked with creating a protocol for URLSession and implementing it in a custom class. The protocol should include a method for making a network request and a method for canceling a network request. Additionally, you need to create a class that conforms to this protocol and implements the required methods.
Your... | ```swift
import Foundation
// Define a protocol for URLSession
public protocol URLSessionProtocol {
func dataTask(with request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask
func cancel()
}
// Create a class conforming to URLSessionProtocol
class Network... | magicoder | swift |
You are tasked with creating a Python function that simulates the process of partitioning a disk device using the `fdisk` command. The function should take in the device name, partition number, and partition type as input parameters. If the device is not already partitioned, the function should execute the partitioning... | ```python
import subprocess
def partition_disk(device_name, partition_number, partition_type):
# Check if the device is already partitioned
check_partition_cmd = f"sudo fdisk -l {device_name} | grep {device_name}1"
partition_check_process = subprocess.Popen(check_partition_cmd, shell=True, stdout=subproces... | magicoder | python |
You are tasked with implementing a simplified version of the MuSig2 BIP (Bitcoin Improvement Proposal) key aggregation scheme. In this scheme, multiple parties collaborate to create a single public key that can be used in an on-chain output for a Bitcoin transaction. The aggregated public key is used to authorize spend... | ```python
from hashlib import sha256
from ecdsa import VerifyingKey, SECP256k1
from ecdsa.numbertheory import inverse_mod
def aggregate_public_keys(individual_public_keys):
# Step 1: Compute the combined public key point
combined_point = sum(individual_public_keys, SECP256k1.generator)
# Step 2: Compute t... | magicoder | python |
You are tasked with creating a Python class that represents a user in an ORM (Object-Relational Mapping) system. The class should inherit from a base class and include attributes and methods for managing user data.
Your task is to complete the implementation of the `User` class by adding necessary attributes and metho... | ```python
class User(Base):
'''ORM Models - users'''
def __init__(self, username, email, is_active=True):
self.username = username
self.email = email
self.is_active = is_active
def update_email(self, new_email):
self.email = new_email
def toggle_active_status(self):
... | magicoder | python |
You are tasked with implementing a class for handling International Standard Book Numbers (ISBNs). An ISBN is a unique identifier for books, and it comes in two formats: ISBN-10 and ISBN-13. Each format has a specific structure and validation algorithm.
Your task is to implement the methods for generating ISBN-13 and ... | ```python
class ISBNHandler:
def __init__(self, rule, reg_pub):
self.rule = rule
self.reg_pub = reg_pub
def _body(self):
for rule in self.rule:
if reg_pub.startswith(rule.registrant):
reg_len = rule.registrant_length
break
else:
... | magicoder | python |
You are tasked with implementing a dependency resolution system for a software upgrade process. The system should handle dependencies between different upgrade tasks and ensure that tasks are executed in the correct order.
You are given the following code snippet as a starting point:
```python
branch_labels = None
de... | ```python
def execute_upgrade_tasks(depends_on):
def topological_sort(graph):
visited = set()
stack = []
def dfs(node):
if node in visited:
if node in stack:
raise ValueError("Cyclic dependency detected")
return
vis... | magicoder | python |
You are tasked with creating a program that analyzes a given PHP file to extract the template name used in the file's header comment section. The template name is specified as a comment within the PHP file and is denoted by the following format: `Template Name: <name>`. Your program should be able to identify and extra... | ```python
import re
def extract_template_name(file_content):
match = re.search(r'/\*\*\s*Template Name:\s*(.*?)\s*\*/', file_content)
if match:
return match.group(1)
else:
return "Template name not found"
# Test the function with the given PHP file content
php_file_content = """
<reponame>... | magicoder | python |
You are tasked with implementing a method to retrieve an authentication token from a given API endpoint. The provided code snippet is a part of a larger system and is responsible for obtaining the authentication token. Your task is to complete the implementation of the `getAuthToken` method, ensuring that it correctly ... | ```php
/**
* @return \stdClass
* @throws \Throwable
*/
public function getAuthToken()
{
// Assuming $this->getSkladInstance() returns the Sklad instance
// and $this->id is the identifier needed for the API call
$tokenResponse = $this->getSkladInstance()->getClient()->post(
ApiUrlRegistry::instan... | magicoder | php |
You are tasked with implementing a function that simulates a simplified version of an activity view controller in iOS. The function should take in various parameters and return a formatted string representing the configuration of the activity view controller.
The function signature is:
```swift
func configureActivityV... | ```swift
func configureActivityViewController(parameters: ActivityViewControllerParameters) -> String {
var configurationString = "Activity View Controller Configuration:\n"
if let activities = parameters.applicationActivities {
configurationString += "Application Activities: \(activities)\n"
}... | magicoder | swift |
You are tasked with implementing a file management system that involves copying files, generating saved state information, and iterating through a loop. Your goal is to write a Python function that performs these tasks based on the given code snippet.
You are provided with the following code snippet as a starting poin... | ```python
import shutil
class Env:
def __init__(self, root_dir, hh_fanout_path, hh_server_path):
self.root_dir = root_dir
self.hh_fanout_path = hh_fanout_path
self.hh_server_path = hh_server_path
def generate_saved_state(env, work_dir):
# Implement the logic to generate saved state inf... | magicoder | python |
You are tasked with creating a program to manage and analyze data from a social media platform using the GitGrabber library. The GitGrabber library provides various services for accessing and manipulating social media data. Your task is to implement a feature that retrieves and analyzes user information from the social... | ```python
# Import necessary GitGrabber library modules
from GitGrabber.Misc import *
from GitGrabber.Services import *
from GitGrabber.Social import *
from GitGrabber.Tests.ConfigModels import *
# Retrieve user information from the social media platform
user_id = "example_user_id"
user_data = SocialService.getUserDat... | magicoder | python |
You are tasked with creating a Swift class that manages life hacks. The class should have outlets for a description label, materials label, and instructions text view. Additionally, it should have a property called `lifeHacks` of type `LifeHacks`. When this property is set, it should update the user interface elements ... | ```swift
import UIKit
class LifeHacksManager: UIViewController {
// MARK: - Outlets
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var materialsLabel: UILabel!
@IBOutlet weak var instructionsTextView: UITextView!
// MARK: - Properties
var lifeHacks: LifeHacks? {
didSe... | magicoder | swift |
You are tasked with creating a Python function that generates a file path based on the given parameters. The function should construct a file path for storing training results in a specific directory, with the file name containing various parameters such as date and time, name, iterations, maximum epochs for negative l... | ```python
from datetime import datetime
def generate_file_path(directory, name, iterations, max_epochs_nll, max_epochs_mae, patience_nll, patience_mae):
datetimestr = datetime.now().strftime("%Y%m%d_%H:%M")
file_path = (
f"../../evaluation/train_results/{directory}/"
f"{datetimestr}_file_{name}... | magicoder | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.