query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with creating a command-line tool to generate icons for different platforms. The tool should accept various arguments and options to customize the icon generation process.
Your task is to implement the `IconsTask` class and its associated methods to fulfill the requirements. The `IconsTask` class should... | ```swift
import Foundation
enum Icon {
case Idiom
// Define the platform enum
enum Platform {
case iOS
case android
// Add more platforms as needed
}
}
struct ArgumentParser {
struct Result {
// Define the structure for parsing command-line arguments
func g... | magicoder | swift |
You are tasked with creating a custom extension method for verifying code annotations in C# source files. The extension method should be able to asynchronously verify the correctness of the annotations using a specified analyzer.
Your task is to implement the `VerifyAsync` extension method for the `AnnotatedSourceFile... | ```csharp
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Testing.NUnit;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Testing;
namespace CleanCodeHelper.Analyzer.Test.Helper.NUnit
{
public static class AnnotatedSourceFileExtensions
{
public static async Task ... | magicoder | csharp |
You are tasked with creating a Python class that processes text data to extract questions from a given input. Your class should implement a method that takes a string as input and returns a list of all the questions present in the text. A question is defined as a sentence that starts with a capital letter, followed by ... | ```python
import nltk
import re
class QuestionExtractor:
def __init__(self):
self.tokenizer = nltk.tokenize.punkt.PunktSentenceTokenizer()
self.QUESTION_REGEX = re.compile(r"[A-Z][a-z][^A-Z]*[?]$")
def extract_questions(self, text):
sentences = self.tokenizer.tokenize(text)
que... | magicoder | python |
You are tasked with creating a secure user authentication system for a web application. The system should handle user login and session management securely to prevent unauthorized access to sensitive information.
Your task is to implement a function or method that handles user login and session management. The functio... | ```csharp
public class UserAuthentication
{
// Method to handle user login and session management
public string HandleLogin(string username, string password)
{
// Validate username and password against a secure database
bool isValidCredentials = ValidateCredentials(username, password);
... | magicoder | csharp |
You are tasked with creating a custom memory allocation system for a C++ application. The system should provide a simple interface for allocating and freeing memory, and it should be able to handle memory requests of varying sizes. To achieve this, you need to implement a custom memory allocator using a linked list dat... | ```cpp
#include <cstddef>
#include <iostream>
struct MemoryBlock {
size_t size;
bool free;
MemoryBlock* next;
};
class CustomAllocator {
public:
CustomAllocator(size_t totalSize) {
memory = new MemoryBlock;
memory->size = totalSize;
memory->free = true;
memory->next = n... | magicoder | cpp |
You are tasked with implementing a pagination system for fetching data from a remote server. The provided code snippet is a part of a Swift function that handles the pagination logic. The function is responsible for checking the current state of pagination, determining if there are more pages to fetch, and updating the... | ```swift
struct PaginationState {
var page: Int
var pageCount: Int
}
class DataFetcher {
var state: PaginationState?
var isFetching: Bool = false
func fetchData(completion: ((Bool) -> Void)?) {
if let state = self.state {
if state.page + 1 >= state.pageCount {
c... | magicoder | swift |
You are tasked with implementing a function that can parse and extract information from a nested object representing a file structure. The object contains information about files and directories, and your goal is to extract the paths of all the files within the structure.
You are given a JavaScript object representing... | ```javascript
function extractFilePaths(fileStructure) {
const paths = [];
function traverse(directory, currentPath) {
if (directory.children) {
directory.children.forEach((item) => {
traverse(item, `${currentPath}/${item.path}`);
});
} else {
paths.push(currentPath);
}
}
... | magicoder | javascript |
You are tasked with implementing a class for controlling a walking robot's trajectory. The class should have methods for setting the center of mass (CoM) height and the swing foot height. Additionally, the class should have protected members for a reference trajectory module, maximum vertical force, end time, contact d... | ```cpp
#include <Eigen/Dense>
class WalkingReferenceTrajectoryModule {
// Define the WalkingReferenceTrajectoryModule class
// ...
};
class WalkingController {
public:
WalkingController(WalkingReferenceTrajectoryModule* trajectory_module, const Eigen::Vector3d& initial_com_position)
: walking_refe... | magicoder | cpp |
You are tasked with implementing a Python function that emulates the behavior of the `os.spawnlpe` function using the `subprocess.Popen` module. The `os.spawnlpe` function is used to spawn a new process, and it allows specifying the environment for the new process. Your task is to create a function that takes the same ... | ```python
import subprocess
import os
def spawnlpe(mode, file, *args, env=None):
if env is not None:
env_dict = dict(os.environ)
env_dict.update(env)
else:
env_dict = None
if mode == os.P_WAIT:
return subprocess.Popen([file] + list(args), env=env_dict).wait()
elif mode ... | magicoder | python |
You are tasked with creating a function to parse an XML file and handle Unicode errors. The function should read an XML file, identify any Unicode errors, and handle them appropriately.
You are given a code snippet from a Django test case that sets the stage for this problem. The `XMLParsingTest` class contains a met... | ```python
import xml.etree.ElementTree as ET
def parse_and_handle_unicode_errors(file_path, replacement_char='?'):
try:
with open(file_path, 'r', encoding='utf-8') as file:
xml_content = file.read()
# Parse the XML content
root = ET.fromstring(xml_content)
# ... | magicoder | python |
You are working on a natural language processing (NLP) project and need to implement a metric aggregation function for evaluating the performance of a model. The given code snippet is part of a larger codebase for a model called MTBertModel, which utilizes various modules for prediction and evaluation. Your task is to ... | ```python
def compute_aggregate_metric_ops(metric_ops, module_names, model_params):
metrics = []
ops = []
if 'boundary' in module_names and model_params.get('boundary_weight', 0) > 0:
metrics.append(metric_ops.get('boundary/f1', None))
return metrics, ops
```
The `compute_aggregate_metric_ops` ... | magicoder | python |
You are tasked with implementing a function that calculates the total number of unique ways to reach the top of a staircase. You are allowed to climb either 1 or 2 steps at a time. The staircase has a total of `n` steps.
Write a function `climbStairs` that takes in an integer `n` and returns the total number of unique... | ```python
def climbStairs(n: int) -> int:
if n == 1:
return 1
elif n == 2:
return 2
else:
first = 1
second = 2
for _ in range(3, n + 1):
third = first + second
first = second
second = third
return second
```
The `climbStairs... | magicoder | python |
You are given a list of software licenses, each represented as a string. Each license contains information about the permissions and conditions for using the software. Your task is to parse the licenses and extract specific details from them.
A software license is represented as a string in the following format:
```
/... | ```swift
func parseLicense(license: String) -> (permissions: [String], conditions: String, liability: String) {
var permissions: [String] = []
var conditions: String = ""
var liability: String = ""
if let permissionRange = license.range(of: "to permit persons to whom the Software is furnished to do... | magicoder | swift |
You are tasked with implementing a function that processes a directional cross-reference section and extracts the referenced entries. A directional cross-reference section is represented as an array of strings, where each string contains a reference to another entry. The references are denoted by the `{dxt}` tag follow... | ```typescript
export type DirectionalCrossReferenceSection = Array<string>
function extractCrossReferences(crossReferences: DirectionalCrossReferenceSection): Array<string> {
const referencedEntries: Array<string> = [];
for (const reference of crossReferences) {
const match = reference.match(/\{dxt\} (.+?)\./... | magicoder | typescript |
You are tasked with implementing a function that takes an integer as input and returns the negation of that integer. However, there's a twist - you are not allowed to use the unary negation operator (-) or any arithmetic operators (+, -, *, /) in your implementation. You can only use bitwise operators and logical opera... | ```python
def negateInteger(num: int) -> int:
if num == 0:
return 0
else:
return ~num + 1
```
The solution uses bitwise NOT (~) and addition to achieve the negation of the input integer. If the input is 0, the function returns 0 as the negation of 0 is 0. For non-zero input, it computes the two... | magicoder | python |
You are tasked with implementing a Python module that provides functionality for handling personal account numbers (PANs). A PAN is a unique identifier for an individual's account, typically used in financial transactions. The module should include a class `PAN` that encapsulates the behavior and attributes of a PAN.
... | ```python
class PAN:
def __init__(self, number, is_valid=False):
self.number = number
self.is_valid = is_valid
def validate(self):
if len(self.number) != 16:
self.is_valid = False
return
digits = [int(digit) for digit in self.number]
for i in ran... | magicoder | python |
You are tasked with implementing a command-line interface for a Python application using the `argparse` module. The application is designed to run various cron jobs, and you need to create a new cron job function and add the corresponding command-line argument parsing for it.
Your task is to complete the `cron_chiayi_... | ```python
import argparse
from app import cfg
from app import util
def cron_chiayi_city():
# Implement the logic for the new cron job (e.g., fetching data for Chiayi City)
pass
def parse_args():
'''Parse command-line arguments for the application.'''
parser = argparse.ArgumentParser(description='road... | magicoder | python |
You are tasked with implementing a payload management system for a messaging protocol. The system should allow for the definition of payload types and their associated IDs, and ensure that the IDs are unique within their respective categories (sendable or receivable).
You are provided with a code snippet that demonstr... | ```rust
// Define the PayloadManager struct to manage payload types and their IDs
pub struct PayloadManager {
sendable_payloads: std::collections::HashMap<String, u8>,
receivable_payloads: std::collections::HashMap<String, u8>,
}
impl PayloadManager {
// Create a new instance of PayloadManager
pub fn n... | magicoder | rust |
You are tasked with implementing a simple unit testing framework for a programming language. Your framework should be able to handle test cases, execute them, and report the results. You are given a code snippet of a test case written using the xUnit testing framework for inspiration.
Your task is to implement a TestR... | ```csharp
using System;
using System.Reflection;
public class TestRunner
{
public void RunTests<T>() where T : new()
{
int totalTests = 0;
int passedTests = 0;
int failedTests = 0;
T testClassInstance = new T();
Type testClassType = typeof(T);
foreach (var meth... | magicoder | csharp |
You are tasked with implementing a function to calculate the Harmonic Pitch Class Profile (HPCP) based on given frequencies and magnitudes. The HPCP is a feature extraction method commonly used in music information retrieval to represent the pitch content of an audio signal. The HPCP is a 12-element vector representing... | ```cpp
#include <vector>
#include <cmath>
std::vector<double> HPCP(const std::vector<double>& frequencies, const std::vector<double>& magnitudes) {
std::vector<double> hpcp(12, 0.0); // Initialize HPCP vector with zeros
// Iterate over the input frequencies and magnitudes
for (size_t i = 0; i < frequenci... | magicoder | cpp |
You are working for a real estate company that specializes in selling properties with mineral rights. Your task is to create a program that compares the mineral rights (MINE) of different properties and generates a visualization for the comparison. The mineral rights are represented as a list of integers, where each in... | ```python
import matplotlib.pyplot as plt
def compare_mineral_rights(mineral_rights):
# Calculate the average mineral rights value
average_value = sum(mineral_rights) / len(mineral_rights)
# Create a bar chart
plt.bar(range(len(mineral_rights)), mineral_rights, label='Property MINE')
plt.axhline(y... | magicoder | python |
You are tasked with implementing a Clock class in Python that can perform addition and subtraction operations on time values in military format (hhmm) and AM/PM format (hh:mm AM/PM). The Clock class should have methods to convert time from military format to AM/PM format and vice versa. Additionally, the class should b... | ```python
class Clock:
def __init__(self, hours, minutes):
self.hours = hours
self.minutes = minutes
@classmethod
def from_military(cls, mil_time):
hours = int(mil_time[:2])
minutes = int(mil_time[2:])
return cls(hours, minutes)
@classmethod
def from_am_pm(c... | magicoder | python |
You are tasked with creating a Python script to automate the process of creating a database schema using SQLAlchemy and a given database URL. Your script should take the database URL as input and use SQLAlchemy to create the necessary tables based on the defined models in the microblogging application.
Write a Python ... | ```python
from sqlalchemy import create_engine
from microblogging import app
def create_database_schema(database_url: str) -> None:
app.db.metadata.create_all(create_engine(database_url))
```
The `create_database_schema` function takes the database URL as input and uses SQLAlchemy to create the database schema ba... | magicoder | python |
You are tasked with implementing a class that manages configuration changes and allows listeners to be notified when a configuration change occurs. You need to create a `ConfigManager` class that provides methods to add, remove, and notify listeners about configuration changes.
Your `ConfigManager` class should have t... | ```java
import java.util.ArrayList;
import java.util.List;
public class ConfigManager<T> {
private List<ConfigChangeListener<T>> listeners;
public ConfigManager() {
this.listeners = new ArrayList<>();
}
public ConfigChangeListener.ListenerRegistration addChangeListener(ConfigChangeListener<T>... | magicoder | java |
You are working on a hotel management system that includes a Booking class with various methods. One of the methods is `get_category`, which retrieves the category of a room based on the room's category code. Another method is `cancel_booking`, which generates a URL for canceling a booking.
Your task is to implement a... | ```python
class Booking:
def __init__(self, room, pk):
self.room = room
self.pk = pk
def get_category(self):
categories = dict(self.room.ROOM_CATEGORIES)
category = categories.get(self.room.category)
return category
def cancel_booking(self):
return reverse('... | magicoder | python |
You are tasked with implementing a function to find the closest obstacle to an ellipsoid in a 3D space. The function takes the ellipsoid parameters and a set of obstacles as input and returns the closest obstacle to the ellipsoid. The ellipsoid is represented by its radii and orientation, while the obstacles are repres... | ```cpp
#include <iostream>
#include <vector>
#include <cmath>
// Define a 3D point structure
struct Vec3f {
float x, y, z;
};
// Define the ellipsoid structure
struct Ellipsoid {
float radius_;
std::pair<Vec3f, Vec3f> orientation_;
};
// Define the face structure for obstacles
struct Face {
Vec3f poi... | magicoder | cpp |
You are tasked with creating a program that simulates a simple command-line utility for managing a list of tasks. The program should support adding tasks, marking tasks as completed, listing all tasks, and removing tasks. The tasks should be stored in memory and should persist for the duration of the program's executio... | ```python
from typing import List
class TaskManager:
def __init__(self):
self.tasks = []
def add_task(self, description: str):
if description:
self.tasks.append((description, False))
else:
print("Error: Task description cannot be empty.")
def complete_task(... | magicoder | python |
You are tasked with creating a Python function that simulates a simplified version of a database migration system. The function should take in a list of migration operations and apply them to a database schema. Each migration operation is represented as a tuple with the following format: (operation_type, model_name, fi... | ```python
def apply_migrations(migrations, database_schema):
for operation, model_name, field_name, new_field_type in migrations:
if operation == "AddField":
if model_name in database_schema:
database_schema[model_name].append(field_name)
else:
databas... | magicoder | python |
You are tasked with creating a custom inspector for a Unity game object that contains a list of topics related to TensorFlow (TF). The code snippet provided is a part of the custom inspector script. The `serializedObject` is a reference to the object being inspected, and it is used to find the property "m_TFTopics" whi... | ```csharp
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(YourScriptContainingTFTopics))]
public class TFTopicsInspector : Editor
{
public override void OnInspectorGUI()
{
serializedObject.Update();
var list = serializedObject.FindProperty("m_TFTopics");
EditorGUILayout.Prop... | magicoder | csharp |
You are given a set of nested curly braces as shown in the code snippet below. Your task is to write a function that determines whether the braces are properly nested. A set of braces is considered properly nested if for every opening brace, there is a corresponding closing brace and they are properly nested within eac... | ```cpp
#include <iostream>
#include <stack>
#include <string>
bool isProperlyNested(std::string braces) {
std::stack<char> stack;
for (char brace : braces) {
if (brace == '{') {
stack.push(brace);
} else if (brace == '}') {
if (stack.empty() || stack.top() != '{') {
... | magicoder | cpp |
You are tasked with implementing a custom LSTM layer in Python without using any external libraries such as TensorFlow or Keras. Your custom LSTM layer should be able to handle variable input sequence lengths and should include the ability to return sequences at each time step. Additionally, you need to implement the a... | ```python
class CustomLSTM:
def __init__(self, units, input_shape):
self.units = units
self.input_shape = input_shape
self.Wf = np.random.randn(input_shape[1] + units, units) # Weight matrix for forget gate
self.Wi = np.random.randn(input_shape[1] + units, units) # Weight matrix fo... | magicoder | python |
You are given a Java code snippet that includes a `Node` class and a `MyNode` class that extends the `Node` class. The `Node` class has a method `setData` that sets the data and prints "Node.setData", while the `MyNode` class has a method `setData` that overrides the `setData` method in the `Node` class and prints "MyN... | The output of the code snippet when executed will be:
```
MyNode.setData
Node.setData
```
Explanation:
1. When an instance of `MyNode` is created and its `setData` method is called, it first prints "MyNode.setData" as defined in the `MyNode` class.
2. Inside the `setData` method of `MyNode`, it then calls the `super.s... | magicoder | java |
You are tasked with creating a custom error type in Rust for handling serialization and deserialization errors when working with LTSV (Labeled Tab-separated Values) data format. The LTSVError type should be able to represent both serialization and deserialization errors using the From trait to convert from serde_value:... | ```rust
// Custom error type for LTSV serialization and deserialization errors
#[derive(Debug)]
enum LtsvError {
SerializerError(serde_value::SerializerError),
DeserializerError(serde_value::DeserializerError),
}
impl From<serde_value::SerializerError> for LtsvError {
fn from(err: serde_value::SerializerEr... | magicoder | rust |
You are tasked with creating a program that simulates a simplified version of a cargo management system for a shipping company. The program should be able to handle the loading and unloading of cargo onto/from different types of transport vehicles.
Your task is to implement a Cargo class and a TransportVehicle class w... | ```python
class Cargo:
def __init__(self, cargo_id, description, weight):
self.id = cargo_id
self.description = description
self.weight = weight
def display_info(self):
print(f"Cargo ID: {self.id}, Description: {self.description}, Weight: {self.weight} tons")
class TransportVe... | magicoder | python |
You are tasked with implementing a custom data structure called `State` which is a wrapper around `usize`. The `State` struct has a specific requirement that makes it very hard, if not impossible, to reach the limit manually. Your task is to implement the `State` struct and a method to increment its value, ensuring tha... | ```rust
/// A wrapper around usize with a unique increment method.
pub struct State {
value: usize,
}
impl State {
/// Creates a new State with an initial value.
pub fn new(initial_value: usize) -> State {
State { value: initial_value }
}
/// Increments the value by a specified amount.
... | magicoder | rust |
You are tasked with implementing a function to serialize data along with metadata using a specific protocol version. The function should take three parameters: `data` (the main data to be serialized), `metadata` (additional information to be included), and `protocol_version` (the version of the serialization protocol t... | ```python
import json
import xml.etree.ElementTree as ET
def serialize(data, metadata, protocol_version):
if protocol_version == 1:
serialized_data = {
"data": data,
"metadata": metadata
}
return json.dumps(serialized_data)
elif protocol_version == 2:
roo... | magicoder | python |
You are tasked with creating a command-line utility that simulates the behavior of the `ln` command in Unix-based systems. The `ln` command is used to create links between files or directories. Your utility should support creating hard links, symbolic links, and force creating links if the target already exists.
Your ... | ```python
import os
import argparse
def create_link(args):
source = args.source
target = args.target
force = args.force
symbolic = args.symbolic
if not os.path.exists(source):
print(f"Error: Source '{source}' does not exist.")
return
if os.path.exists(target) and force:
... | magicoder | python |
You are tasked with implementing a simple endpoint throttling mechanism for an HTTP server. The goal is to limit the number of requests that can be made to a specific endpoint within a given time frame. You are provided with a Java class `AdHocThrottleEndpoint` that represents an endpoint and its associated throttling ... | ```java
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
public class AdHocThrottleEndpoint {
private final String _method;
private final String _path;
private final Map<String, Map<String, AtomicInteger>> requestCounters = new Concurren... | magicoder | java |
You are tasked with creating a script to generate a FindBugs filter file for a Java project. The script should parse all Java files in a given workspace directory and extract the package names from each file. The package names should then be used to populate the FindBugs filter file. The script should follow the given ... | ```bash
#!/bin/bash
workspaceDir="/path/to/workspace"
includeFile="findbugs-filter.xml"
regex='^[[:space:]]*package[[:space:]]+(.+);'
# Extract package names from Java files and store them in the packages array
declare -a packages=( $( \
find "${workspaceDir}" -type f -name "*.java" \
-exec grep -E "${regex}" '... | magicoder | shell |
You are tasked with creating a mobile device detection system for a web application. The system should be able to identify whether a given user agent corresponds to a mobile device, a tablet, and retrieve the version of a specific device.
You are provided with a PHP class `MobileDetect` that contains the necessary met... | ```php
class MobileDetect {
public function detect($propertyName, $device = null) {
// Implement device detection logic based on $propertyName and $device
// Return the appropriate result based on the detection logic
// Example implementation for demonstration purposes
if ($property... | magicoder | php |
You are tasked with implementing a function `parseStr` that takes a string as input and returns a dictionary containing the count of each character in the string. The function should ignore spaces and should be case-insensitive, meaning that 'A' and 'a' should be considered the same character.
For example, if the inpu... | ```python
def parseStr(input_str):
# Convert the input string to lowercase to make it case-insensitive
input_str = input_str.lower()
# Initialize an empty dictionary to store the character counts
char_count = {}
# Iterate through each character in the input string
for char in input_str... | magicoder | python |
You are tasked with implementing a function that unserializes pairs of data from a given input string. The input string contains a series of key-value pairs in a specific format, and your function should parse and return these pairs as a dictionary.
You are given the following code snippet as a starting point for your... | ```python
def unserialize_pairs(input_string):
pairs = input_string.split(',')
result = {}
for pair in pairs:
key, value = pair.split(':')
result[key] = value
return result
```
The `unserialize_pairs` function first splits the input string by the delimiter ',' to obtain individual key-v... | magicoder | python |
You are tasked with implementing a memory management system for a virtual environment. The system is responsible for creating and managing pools of different types of entities within the virtual environment. Each pool is represented by a class, and the memory for these pools is allocated dynamically using the `new` ope... | To implement the memory management system for entity pools, you can create a generic `CPool` class that serves as the base class for managing different types of entity pools. This class can handle memory allocation, deallocation, and management of entities within the pool. Additionally, you can create specific derived ... | magicoder | cpp |
You are tasked with implementing a command-line interface (CLI) adapter for a software system. The CLI adapter should provide a way for users to interact with the system through a command-line interface, executing various commands and receiving corresponding outputs. The adapter should be designed to handle different t... | ```cpp
// adpt.cpp
#include "pch.h"
#include "adpt.h"
#include <iostream>
#include <sstream>
void CLIAdapter::registerCommandHandler(const std::string& command, std::function<void(const std::vector<std::string>&)> handler) {
commandHandlers[command] = handler;
}
void CLIAdapter::parseAndExecuteCommand(const std::... | magicoder | cpp |
You are given a code snippet that contains a function named `Special`. Your task is to complete the function by implementing a specific functionality. The `Special` function takes an array of integers as input and should return the count of unique elements in the array.
The function signature is:
```python
def Special... | ```python
from typing import List
def Special(arr: List[int]) -> int:
unique_elements = set(arr)
return len(unique_elements)
```
The `Special` function first creates a set from the input array, which automatically removes duplicate elements. Then, it returns the length of the set, which represents the count of... | magicoder | python |
You are tasked with creating a unit test for a Java class using the Mockito framework. The class under test is a service that interacts with a database to retrieve and manipulate data. Your goal is to write a unit test that verifies the behavior of the service class without actually interacting with the real database.
... | ```java
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class UserServiceTest {
@Mock
private UserRepository userRepository;
private UserService userService;
@Be... | magicoder | java |
You are tasked with implementing a function to perform private encryption using the RSA algorithm. The provided code snippet is a part of a larger cryptographic library and contains a function `private_encrypt` that takes an RSA private key and a byte array as input and returns a result of type `Tomb` or an error. The ... | ```rust
use openssl::rsa::Rsa;
use openssl::error::ErrorStack;
use openssl::symm::{encrypt, Cipher};
use base64::{encode, decode};
pub struct Tomb {
aes_key: String,
aes_iv: String,
value: String,
}
pub fn private_encrypt(key: &Rsa<openssl::pkey::Private>, bytes: &[u8]) -> Result<Tomb, ErrorStack> {
/... | magicoder | rust |
You are tasked with creating a program that formats and displays tabular data in a visually appealing manner. The program should take a list of records, where each record is a dictionary representing a row of the table, and a list of column names. The goal is to align the columns and display the data in a neat, organiz... | ```python
def format_table(records, columns):
column_max = {}
header = []
separator = []
for column in columns:
col_len = len(column)
maximum = max(len(str(r.get(column, ''))) for r in records)
maximum = maximum if maximum > col_len else col_len
column_max[column] = maxi... | magicoder | python |
You are tasked with implementing a Python class that manages a queue of asynchronous tasks. The class should support adding tasks to the queue, executing tasks in parallel, and retrieving the results of completed tasks. Each task is represented by a function and its arguments. The class should also provide a method to ... | ```python
import concurrent.futures
class AsyncTaskQueue:
def __init__(self):
self.tasks = {}
self.results = {}
def add_task(self, func, *args, **kwargs):
task_id = len(self.tasks) + 1
self.tasks[task_id] = (func, args, kwargs)
def _task_wrapper(self, task_id):
fun... | magicoder | python |
You are tasked with implementing a function that simulates a simple animation sequence using keyframes. The animation involves rotating a view to the right by a certain angle and then resetting it back to its original state. Your task is to write a function that takes a UIView as input and performs the specified animat... | ```swift
func performRotationAnimation(on view: UIView) {
UIView.animateKeyframes(withDuration: 1.0, delay: 0, options: [], animations: {
UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.25) {
view.transform = .identity // resets the transform to its original state
}
... | magicoder | swift |
You are tasked with creating a program that simulates a simple file management system. The program should allow users to perform basic file operations such as creating, deleting, and listing files in a specified directory.
Your task is to implement a Python class `FileManager` with the following methods:
1. `__init__... | ```python
import os
from typing import List
class FileManager:
def __init__(self, directory: str):
self.directory = directory
def create_file(self, file_name: str):
file_path = os.path.join(self.directory, file_name)
with open(file_path, 'w'):
pass
def delete_file(self... | magicoder | python |
You are tasked with creating a function that takes in a JavaScript object representing a React element and returns the corresponding HTML string. The React element is represented in the form of a JavaScript object, similar to what is created using `React.createElement()`.
The `React.createElement()` function takes thr... | ```javascript
function reactElementToHTML(reactElement) {
const { type, props } = reactElement;
const attributes = Object.keys(props)
.filter(key => key !== 'children')
.map(key => `${key}="${props[key]}"`)
.join(' ');
const childrenHTML = props.children
.map(child => typeof child === 'object' ? ... | magicoder | javascript |
You are tasked with creating a Python class that performs static analysis on a codebase. Your class should have methods to display JavaScript dependencies, show toggles, show complexity, and send logs to a logger. Additionally, you need to implement a method to count the number of CouchDB model subclasses in the codeba... | ```python
class StaticAnalyzer:
def __init__(self, logger, stdout):
self.logger = logger
self.stdout = stdout
def show_js_dependencies(self):
# Implement logic to display JavaScript dependencies
pass
def show_toggles(self):
# Implement logic to display toggles
... | magicoder | python |
You are tasked with implementing a Connect Four game using Python. Connect Four is a two-player connection game in which the players first choose a color and then take turns dropping colored discs from the top into a vertically suspended grid. The pieces fall straight down, occupying the lowest available space within t... | ```python
class ConnectFourGame:
def __init__(self):
self.board = [[None] * 7 for _ in range(6)] # 6x7 game board
self.rows = 6
self.cols = 7
def drop_disc(self, column, color):
for row in range(self.rows - 1, -1, -1):
if self.board[row][column] is None:
... | magicoder | python |
You are tasked with creating a Python function that processes a given list of dates and times and returns the earliest valid date and time in the list. The function should handle time zone localization and return the earliest date and time in the specified time zone, or in the default time zone if no time zone is provi... | ```python
import pandas as pd
def find_earliest_datetime(date_times, tz=None):
s = pd.Series(pd.to_datetime(date_times).tz_localize(tz))
earliest_datetime = s.dropna().min()
return earliest_datetime
```
The `find_earliest_datetime` function uses the `pandas` library to convert the input list of date and t... | magicoder | python |
You are working on a text analysis project and need to implement a system that can efficiently extract key phrases from a given text. To achieve this, you decide to use a variety of algorithms for keyword extraction, including SCake, SGRank, TextRank, and YAKE. Each algorithm is implemented in a separate module, and yo... | ```python
from scake import scake
from sgrank import sgrank
from textrank import textrank
from yake import yake
class KeywordExtractor:
def __init__(self):
# Initialize any necessary resources for the keyword extraction algorithms
pass
def extract_keywords(self, text, algorithm):
"""
... | magicoder | python |
You are tasked with creating a custom view in an Android application that displays a list of items in a horizontal scrolling manner. The custom view should be implemented as a subclass of `ViewGroup` and should support adding child views dynamically. Each child view should display an image and some text.
Your task is ... | ```java
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public clas... | magicoder | java |
You are tasked with implementing 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. The function should take two integer parameters, `start` and `end`, representing the inclusive range wit... | ```swift
func sumOfPrimes(_ start: Int, _ end: Int) -> Int {
guard start > 1 else { return 0 } // Prime numbers start from 2
func isPrime(_ number: Int) -> Bool {
if number < 2 { return false }
for i in 2..<number {
if number % i == 0 {
return false
}
... | magicoder | swift |
You are working on a computer vision project and need to manipulate a series of images using the OpenCV library in Python. Your task is to write a function that takes a list of image file names, loads the images, and then concatenates them horizontally after cropping each image to only include the right half. The funct... | ```python
import cv2
import numpy as np
from typing import List
def crop_and_concat_images(file_names: List[str]) -> np.ndarray:
images = []
for file_name in file_names:
im = cv2.imread(BASE+'gt/'+file_name) # Load the image
cropped_im = im[:, im.shape[1]//2:, :] # Crop to include only the ri... | magicoder | python |
You are tasked with implementing a reminder system using a custom data structure. The data structure supports the following operations:
1. `PopLast`: Remove the last reminder from the data structure.
2. `Continue(usize)`: Add a new reminder with the given index to the end of the data structure.
3. `Edit(usize)`: Modif... | ```rust
struct ReminderSystem {
reminders: Vec<String>,
}
impl ReminderSystem {
fn new() -> Self {
ReminderSystem { reminders: Vec::new() }
}
fn pop_last(&mut self) {
self.reminders.pop();
}
fn continue_reminder(&mut self, index: usize) {
self.reminders.push(format!("R... | magicoder | rust |
You are tasked with creating a Django migration for a model named `Channel`. The migration should alter two fields in the `Channel` model: `street` and `voivodeship`. The `street` field should be changed to a boolean field with a default value of `False`, and the `voivodeship` field should also be changed to a boolean ... | ```python
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('yourappname', 'previous_migration_number'), # Replace 'yourappname' and 'previous_migration_number' with actual values
]
operations = [
migrations.AlterField(
model_na... | magicoder | python |
You are working as a DevOps engineer for a company that uses Docker for containerization. Your team is responsible for building and maintaining Docker images for various applications. As part of this process, you need to create a script that automates the building of a Docker image using a specific Dockerfile.
You are... | ```bash
#!/bin/bash
# Check if Docker is installed and running
if ! [ -x "$(command -v docker)" ]; then
echo 'Error: Docker is not installed or not running.' >&2
exit 1
fi
# Check if the Dockerfile exists in the current directory
if [ ! -f "./Dockerfile" ]; then
echo 'Error: Dockerfile not found in the current ... | magicoder | shell |
You are tasked with implementing a session verification system for an admin panel. The system should verify the session token and return the admin's name if the verification is successful. However, the given code snippet contains some missing parts and potential issues. Your task is to complete the code and identify an... | ```python
import hashlib
def verify_admin_session(admin_session_token, admin_token_hash, admin_name, stored_admin_token_hash):
try:
# Verify the session token by comparing its hash with the stored hash
hashed_session_token = hashlib.sha256(admin_session_token.encode()).hexdigest()
if hashed... | magicoder | python |
You are tasked with implementing a simple TCP server in Rust that can handle multiple client connections concurrently. Your server should be able to receive messages from clients and broadcast those messages to all connected clients. To achieve this, you will need to use the `tokio` library for asynchronous I/O and the... | ```rust
async fn handle_client(mut stream: TcpStream, connections: Arc<Mutex<Vec<TcpStream>>>) {
let (reader, mut writer) = stream.split();
let mut reader = tokio::io::BufReader::new(reader);
let mut buffer = String::new();
{
let mut connections = connections.lock().unwrap();
connection... | magicoder | rust |
You are tasked with creating a Python program that simulates a simple chat server using Flask-SocketIO. The server should handle multiple client connections and allow them to exchange messages in real-time. Your task is to implement the server-side code that initializes the SocketIO server and handles incoming client c... | ```python
import eventlet
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
# Initialize Flask app and SocketIO
app = Flask(__name__)
app.config['PORT'] = 5000 # Set the port for the server
socketio = SocketIO(app)
# Event handler for new client connections
@socketio.on('connect')
de... | magicoder | python |
You are tasked with creating a chatbot for managing addresses and statistics. The chatbot should be able to display addresses, provide statistics, and allow users to perform various actions on the addresses. You need to implement a function that processes the user's input and returns the appropriate response based on t... | ```python
def processInput(input: str) -> str:
predefined_responses = {
"stats1": "Where do you want to consult the statistics?",
"statsaddr": "My Addresses",
"statsp2m": "EqualHash",
"statsReturn": "<< Back to Stats",
"noneAddr": "You have not added an address yet.\nYou can ... | magicoder | python |
You are tasked with implementing a C++ template class that serves as a base widget for a radio button in a graphical user interface (GUI) application. The provided code snippet is a partial implementation of this base widget class. Your task is to complete the implementation of the `radio_btn` class by adding necessary... | ```cpp
#include <iostream>
// Forward declaration of detail::radio_btn_to_model
namespace detail {
template <typename T>
struct radio_btn_to_model;
}
// Forward declaration of base_widget
template <typename Widget, typename Value, typename Conversion>
class base_widget;
// Complete the radio_btn class
templa... | magicoder | cpp |
You are given a Python code snippet that involves the use of PyTorch tensors and operations. Your task is to understand the code and implement a function that performs similar operations using PyTorch.
You need to implement a function `calculate_likelihood_loss(adj, mm_mask, mask)` that takes three inputs:
- `adj`: a ... | ```python
import torch
def calculate_likelihood_loss(adj, mm_mask, mask):
adj_dense = adj.to_dense() # Convert the sparse adjacency matrix to a dense tensor
subset_adj = adj_dense[mask, :][:, mask] # Extract the subset of the adjacency matrix using the mask indices
likelihood_mask = -torch.mul(mm_mask, ... | magicoder | python |
You are tasked with implementing a Python function that takes a list of integers as input and returns the count of prime numbers in the list. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. The function should be named `count_primes` and should take a single para... | ```python
def count_primes(nums):
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
count = 0
for num in nums:
if is_prime(num):
count += 1
return count... | magicoder | python |
You are tasked with implementing a command handler for a classroom application. The application uses the MediatR library for handling commands and queries. Your goal is to create a handler for the `LeaveClassroomCommand` that removes a student from a classroom.
The `LeaveClassroomCommand` class is defined as follows:
... | ```csharp
using MediatR;
using System;
using System.Threading;
using System.Threading.Tasks;
using Application.Common;
using Application.Common.Results;
namespace Application.Classrooms.Commands.LeaveClassroom {
public class LeaveClassroomCommandHandler : IRequestHandler<LeaveClassroomCommand, Result<Unit>> {
... | magicoder | csharp |
You are working for a software development company that is building a time tracking system for its employees. The system needs to parse and process data from a CSV file containing time tracking information. Each row in the CSV file represents a time entry with the following columns: username, date, task, duration, work... | ```python
import csv
from typing import Dict
import arrow
import re
def calculate_total_duration(username: str, csv_file_path: str) -> Dict[str, int]:
total_duration = {}
with open(csv_file_path, 'r') as file:
csv_reader = csv.DictReader(file)
for row in csv_reader:
if row['username... | magicoder | python |
You are tasked with implementing a LossStatistic class that calculates and tracks the loss statistics during the training process of a machine learning model. The LossStatistic class should inherit from RunningCallbackFreeStatistic and be initialized with the following parameters:
- platform: An instance of PlatformMan... | ```python
class LossStatistic(RunningCallbackFreeStatistic):
def __init__(self, platform: PlatformManager, writerstub: WriterStub, n_epochs: int, n_batches: int, train: bool):
super().__init__(platform, writerstub, n_epochs, n_batches, train)
self.loss_statistics = []
def update_loss(self, loss... | magicoder | python |
You are tasked with creating a program that analyzes a given HTML file and extracts specific information from it. The HTML file contains various content boxes, each with a title and a paragraph of text. Your task is to extract the titles and the corresponding paragraphs from the content boxes and store them in a struct... | ```python
from bs4 import BeautifulSoup
def extractContentBoxes(html):
soup = BeautifulSoup(html, 'html.parser')
content_boxes = soup.find_all('div', class_='content-box')
result = []
for box in content_boxes:
title = box.find('h3', class_='normal').text
paragraph = box.find('p').text
... | magicoder | python |
You are tasked with implementing a Caesar cipher encryption and decryption program for Base64 encoded strings. The Caesar cipher is a simple encryption technique in which each letter in the plaintext is shifted a certain number of places down or up the alphabet. In this case, we will be applying the Caesar cipher to a ... | ```python
import base64
def caesar_cipher_base64(s_b64: str, shift: int) -> str:
B64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
def char_shift(c, shift):
if c in B64_ALPHABET:
i = B64_ALPHABET.index(c)
return B64_ALPHABET[(i+shift) % 64]
... | magicoder | python |
You are tasked with creating a Python program that manages a dictionary of words and their definitions. The program should include functions to load the dictionary from a file, save the dictionary to a file, add new words and their definitions, look up the definition of a word, and delete a word from the dictionary.
Y... | ```python
def add_word_definition(word, definition, dictionary):
dictionary[word] = definition
def lookup_word_definition(word, dictionary):
if word in dictionary:
return dictionary[word]
else:
return f"The word '{word}' is not found in the dictionary."
def delete_word(word, dictionary):
... | magicoder | python |
You are tasked with implementing a dropdown menu component for a web application. The dropdown menu should display a list of button elements, each representing a specific value. The dropdown menu should have the following functionality:
- When a button is clicked, it should trigger an event to handle the selected value... | ```javascript
// Define the dropdown menu component
class DropdownMenu {
constructor(items) {
this.items = items;
this.dropdown = document.createElement('div');
this.dropdown.classList.add('dropdown-menu');
this.createDropdownItems();
this.attachEventListeners();
}
createDropdownItems() {
... | magicoder | javascript |
You are working on a project that involves managing different types of DNS records for various domain providers. The project uses a Python module that provides classes for handling MX records for different domain providers. The module contains the following classes:
1. `MXRecords`: A class for managing MX records for ... | ```python
from typing import List
def get_mx_records(domain: str) -> List[str]:
if domain.endswith('.com'): # Replace with actual logic to determine domain provider
mx_records = MXRecords().get_mx_records(domain)
elif domain.endswith('.google.com'): # Replace with actual logic to determine Google dom... | magicoder | python |
You are tasked with creating a script to validate and send an email using a shell script. The script should check if certain variables are empty and, if so, send an error email with specific details. The script should use the `SENDMAIL` command to send the email.
The script should perform the following checks:
- Check... | ```bash
#!/bin/bash
# Check if any of the required variables are empty
if [ -z "$TO_ADDR" -o -z "$REPLY_TO_ADDR" -o -z "$SUBJECT" -o -z "$BODY_FILE" ]; then
# Construct the error email
$SENDMAIL -t <<EOF
From: $FROM
Subject: ERROR: invalid email
To: $ERROR_TO
Wrong parameters for $0
to: "$TO_ADDR"
reply-to: "... | magicoder | shell |
You are tasked with implementing a parser for a custom language that supports string literals. The provided code snippet is a part of the parser's implementation. Your task is to complete the implementation of the `parse_string` method, which is responsible for parsing a string literal from the input.
The `parse_strin... | ```rust
impl Lexer {
pub fn parse_string(&mut self) -> JsResult<bool> {
let mut parsed_successfully = true;
let mut string_literal = String::new();
loop {
let escaped = self.is_escaped();
let c = self.current_char();
let t = match self.mode() {
... | magicoder | rust |
You are tasked with creating a program to manage tasks using a mobile app. The app will utilize the MapKit framework to display task locations and the Realm database to store task information. You need to implement a function that calculates the distance between the user's current location and a given task location.
Y... | ```swift
func calculateDistanceToTask(userLocation: CLLocation, taskLocation: CLLocation) -> CLLocationDistance {
let lat1 = userLocation.coordinate.latitude.degreesToRadians
let lon1 = userLocation.coordinate.longitude.degreesToRadians
let lat2 = taskLocation.coordinate.latitude.degreesToRadians
let lo... | magicoder | swift |
You are tasked with implementing a simplified version of a stack data structure using a linked list. The stack should support the standard push, pop, and top operations. Additionally, you need to implement a function that returns the minimum element in the stack at any given time. You are given the following Node struc... | ```c
#include <climits>
struct Node {
int data;
Node* next;
};
void push(Node* &top, int value) {
Node* newNode = new Node;
newNode->data = value;
newNode->next = top;
top = newNode;
}
void pop(Node* &top) {
if (top != nullptr) {
Node* temp = top;
top = top->next;
... | magicoder | c |
You are tasked with creating a Python class that represents an inventory management system for a retail store. The class should be able to add items to the inventory, remove items from the inventory, and display the current inventory. Additionally, the class should have a method to calculate the total value of the inve... | ```python
class Inventory:
def __init__(self):
self.items = {}
def add_item(self, name, quantity, unit_price):
self.items[name] = (quantity, unit_price)
def remove_item(self, name):
if name in self.items:
del self.items[name]
else:
print(f"{name} not... | magicoder | python |
You are tasked with implementing a function that maps global coordinates to local coordinates in a parallel computing environment. The function takes in the lattice grid size in the x and y directions, as well as the number of processes in the x and y directions. It then returns the process coordinates along with the l... | ```python
def map_global_to_local(lx, ly, x_size, y_size, global_x, global_y):
"""
Maps global coordinates to local coordinates in a parallel computing environment.
Args:
lx (int): lattice grid size in x direction
ly (int): lattice grid size in y direction
x_size (int): number of pr... | magicoder | python |
You are tasked with implementing a genetic algorithm to solve the traveling salesman problem (TSP). In this problem, you are given a set of cities and the distances between them. The goal is to find the shortest possible route that visits each city exactly once and returns to the original city. The fitness of a potenti... | ```python
import random
class Tour:
def __init__(self, cities):
self.cities = cities
self.tour = random.sample(cities, len(cities)) # Initialize a random tour
def distance(self, city1, city2):
# Calculate the distance between two cities
# Assume the existence of a function to ... | magicoder | python |
You are tasked with implementing a function that simulates a simple text-based game. The game involves a player navigating through a grid-based world, represented by a 2D array, and collecting treasures. The player's position is denoted by a pair of coordinates (x, y) within the grid. The grid contains various elements... | ```python
from typing import List
def collect_treasures(grid: List[List[str]], moves: List[str]) -> int:
treasures_collected = 0
x, y = 0, 0 # Initial position of the player
for move in moves:
if move == 'U' and x > 0 and grid[x - 1][y] != '#':
x -= 1
elif move == 'D' and x < ... | magicoder | python |
You are tasked with implementing a generic codec system for encoding and decoding data. The provided code snippet shows the declaration of various codec instances and a constructor for a `SettingSelectProcProvider` class. Your task is to design and implement the generic codec system to support encoding and decoding of ... | ```java
// Define the Codec class with generic interfaces for encoding and decoding
public class Codec {
public interface Encoder<T> {
void encode(T data);
}
public interface Decoder<T> {
T decode();
}
}
// Implement the generic codec system to support encoding and decoding of differen... | magicoder | java |
You are tasked with creating a Python class that simulates a simple banking system. The class should be able to handle basic banking operations such as account creation, deposit, withdrawal, and balance inquiry. Additionally, the class should be able to generate monthly bank statements for each account.
You are provid... | ```python
class BankAccount:
def __init__(self, account_number, customer_name, initial_deposit):
self.account_number = account_number
self.customer_name = customer_name
self.balance = initial_deposit
self.transaction_history = []
def deposit(self, amount):
self.balance +... | magicoder | python |
You are tasked with creating a Python function that simulates a simple game of dice. The game involves rolling two dice and calculating the sum of their values. The function should take the number of rolls as input and return the frequency of each possible sum from 2 to 12.
The code snippet below shows the initial imp... | ```python
# Filename: dice_game.py
import random
def simulate_dice_rolls(num_rolls):
results = {2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0}
for _ in range(num_rolls):
roll1 = random.randint(1, 6)
roll2 = random.randint(1, 6)
total = roll1 + roll2
results... | magicoder | python |
You are tasked with creating a Python function that calculates the time it takes for the synodic new moon to return to the same nakshatra and the number of revolutions it completes during this period. The synodic month is the period between successive occurrences of the same phase (e.g., new moon to new moon). The new ... | ```python
def synodic_new_moon_return(degrees_per_month: float) -> tuple:
# Calculate the time taken for the new moon to return to the same nakshatra
time_taken = round(360 / degrees_per_month, 6)
# Calculate the number of revolutions completed during this period
revolutions = int(time_taken)
retu... | magicoder | python |
You are tasked with creating a Python program to automate the preprocessing of source code files for a machine learning model. The program needs to handle two scenarios: one for processing original source code files and another for analyzing mutant source code files. The preprocessing involves extracting features from ... | ```python
import os
def preprocess_source_code(path: str, f: str, CONTINUE_PROCESS: bool, NUM_THREADS: int, PYTHON: str, EXTRACTOR: str) -> None:
f_name = f[:-5] # Extracting the filename without the extension
if not CONTINUE_PROCESS or not os.path.exists(os.path.join(path, f_name + ".test.c2v")):
# ... | magicoder | python |
You are tasked with creating a Python function that determines the relative position of a given point with respect to a set of other points on a 2D plane. The function should take in the coordinates of the reference point and a list of other points, and return a list indicating whether each point is to the left, right,... | ```python
def relative_position(reference_point, other_points):
result = []
x_ref, y_ref = reference_point
for point in other_points:
x, y = point
if x < x_ref:
result.append('left')
elif x > x_ref:
result.append('right')
else:
result.appen... | magicoder | python |
You are tasked with implementing a function that calculates the total number of occurrences of a given word in a list of strings. The function should be case-insensitive and should count partial matches as well. For example, if the word is "car" and the list contains "car", "cars", and "scar", the function should retur... | ```python
from typing import List
def count_word_occurrences(word: str, word_list: List[str]) -> int:
count = 0
word = word.lower() # Convert the word to lowercase for case-insensitive comparison
for item in word_list:
item = item.lower() # Convert each item in the list to lowercase
if wo... | magicoder | python |
You are tasked with implementing a Python module that manages the metadata for a software project. The module should maintain a list of allowed attributes and provide a mechanism for accessing and updating these attributes. Your task is to create a class that enforces the allowed attributes and their values.
You shoul... | ```python
class MetadataManager:
allowed_attributes = ["author", "version"]
def __init__(self, **kwargs):
for key in kwargs:
if key not in self.allowed_attributes:
raise ValueError(f"Invalid attribute: {key}")
self.__dict__.update(kwargs)
def __getattr__(self, i... | magicoder | python |
You are tasked with implementing a custom data structure to store and manage a collection of books in a library. The data structure should support operations for adding a new book, removing an existing book, and retrieving the total number of books in the library. Additionally, the data structure should allow for retri... | The `Library` class is implemented with a private property `books` to store the collection of books using a `Set` to ensure uniqueness. The `addBook` method adds a new book to the collection, the `removeBook` method removes an existing book, the `totalBooks` method returns the total number of books, and the `allBooks` ... | magicoder | python |
You are working on a machine learning project and need to implement a scoring function using TensorFlow. The given code snippet is a part of the scoring function that combines confidence scores and class probabilities to calculate the final scores for different classes.
You are given the following information:
- `conf... | ```python
import tensorflow as tf
def calculate_scores(confidence, class_probs, classes):
if classes == 1:
scores = confidence
else:
scores = confidence * class_probs
return scores
# Example usage
confidence = tf.placeholder(tf.float32, shape=(None, 3)) # Example shape (batch_size, num_cl... | magicoder | python |
You are working on a system monitoring tool that needs to extract specific information from a given command output. The tool needs to identify the process ID (PID) of a process named "Domino" and then change the current directory to a specific path if the process is found running.
You are given a code snippet that att... | ```python
import subprocess
import os
def monitor_domino_process():
name = "Domino"
command = "ps -ef | grep {} | grep -v 'grep'".format(name)
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, _ = process.communicate()
output = output.decode('ut... | magicoder | python |
You are tasked with implementing a custom logging system for a software application. The application uses the Java programming language and the Apache Log4j library for logging. The provided code snippet initializes a logger instance using the `Logger.getLogger` method from the Log4j library.
Your task is to create a ... | ```java
import org.apache.log4j.Logger;
public class CustomLogger extends Logger {
protected CustomLogger(String name) {
super(name);
}
@Override
public void info(Object message) {
super.info("[INFO]: " + message);
}
@Override
public void error(Object message) {
s... | magicoder | java |
You are tasked with creating a program that simulates a simple card game called "War." In this game, two players are each dealt half of a standard deck of 52 playing cards. The players then reveal the top card from their respective decks, and the player with the higher card wins both cards, placing them at the bottom o... | ```python
import random
class Card:
def __init__(self, rank, suit):
self.rank = rank
self.suit = suit
class Deck:
def __init__(self):
self.cards = [Card(rank, suit) for rank in range(2, 15) for suit in ['Hearts', 'Diamonds', 'Clubs', 'Spades']]
random.shuffle(self.cards)
d... | magicoder | python |
You are tasked with creating a Python package version checker. Your program should take a user-input version number and compare it to the latest version of the package. If the user's version is outdated, the program should inform the user and provide the option to update the package.
Create a Python function `check_pa... | ```python
def check_package_version(user_version):
latest_version = '0.3.7' # Replace with the actual latest version
if user_version == latest_version:
return "You are using the latest version of the package."
elif user_version < latest_version:
return f"Your version is outdated. The latest... | magicoder | python |
You are tasked with creating a class that can dynamically fill its properties based on an input array. Your task is to implement a method `fillObjectProperties` that takes an associative array and a `ReflectionClass` object as input and returns an instance of the class with its properties filled based on the input arra... | ```php
protected static function fillObjectProperties(array $value, ReflectionClass $ref)
{
$constructArgs = $value['construct'] ?? [];
unset($value['construct']);
$obj = $ref->newInstanceArgs($constructArgs);
foreach ($value as $k => $v) {
if ($ref->hasProperty($k)) {
$property = ... | magicoder | php |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.