query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with creating a Bash script that processes command-line arguments to perform specific actions based on the input. Your script should handle the case when the user provides an invalid argument or fails to provide the required input.
Your script should accept the following command-line options:
- `-d <dir... | ```bash
#!/bin/bash
# Function to display error message and help information
error_trig() {
echo "Error: $1" >&2
echo "Usage: script_name -d <directory> | -h" >&2
exit 1
}
# Process command-line options
while getopts "d:h" opt; do
case $opt in
d)
directory=$OPTARG
# Add your logic to perform operations... | magicoder | shell |
You are tasked with creating a script to automate the deployment and running of a Docker container for Apache Lucene notebooks. Apache Lucene is a high-performance, full-featured text search engine library written entirely in Java. The provided code snippet demonstrates the manual process of building the Docker image a... | ```bash
#!/bin/bash
# Step 1: Build the Docker image
docker build -t apache-lucene-notebooks .
# Step 2: Run the Docker container
docker run --rm -p 8888:8888 -v $PWD/notebooks:/home/jovyan/notebooks apache-lucene-notebooks
```
In this solution, a shell script named "deploy_lucene_notebooks.sh" is created to automat... | magicoder | shell |
You are tasked with implementing a custom accessibility feature for a table view in an iOS app. The given code snippet is part of a custom implementation for generating accessibility actions for a table view cell. The `tableView` is an optional property representing the table view, and `delegate` is an optional propert... | ```swift
func generateAccessibilityActions(for tableView: UITableView?, delegate: UITableViewDelegate?) -> [UIAccessibilityCustomAction] {
guard let tableView = tableView, let indexPath = tableView.indexPath(for: self) else {
return []
}
let leftActions = delegate?.tableView(tableView, editActi... | magicoder | swift |
You are tasked with creating a script to automate the testing of a project's codebase. The script should traverse through the project directory, identify the presence of a `go.mod` file, and execute a test command if the file exists. Additionally, the script should capture the return code of the test command and store ... | ```bash
#!/bin/bash
# Initialize the highest non-zero return code encountered
RET_CODE=0
# Function to traverse through the project directory
traverse_directory() {
for file in "$1"/*; do
if [ -d "$file" ]; then
if [ -f "$file/go.mod" ]; then
# If go.mod file exists, execute the test command
... | magicoder | shell |
You are tasked with creating a Python function that dynamically retrieves a class from a given module based on the class name provided as an argument. Your function should take two parameters: `module` (the module from which to retrieve the class) and `className` (the name of the class to be retrieved). The function sh... | ```python
def retrieve_class(module, className):
try:
return getattr(module, className)
except AttributeError:
raise AttributeError(f"Class '{className}' not found in module '{module.__name__}'")
```
The `retrieve_class` function uses Python's `getattr` function to dynamically retrieve the clas... | magicoder | python |
You are working on a news management system that allows users to create, update, and delete news items. The system uses PHP and a custom framework. The code snippet provided is part of a method that handles different actions related to news items. The method receives a command and performs the corresponding action base... | ```php
class NewsManager {
public function createNews($data_arr) {
// Assuming $data_arr contains necessary details for creating a news item
$id = news_peer::instance()->insert($data_arr);
return $id;
}
public function updateNews($id, $data_arr) {
// Assuming $data_arr conta... | magicoder | php |
You are tasked with implementing a function `parlay_odds(odds)` that takes in a parameter `odds`, which can be either an integer, a float, or a list of integers or floats. The function should return the parlay odds based on the input. Parlay odds are used in sports betting to calculate the potential payout for a combin... | ```python
from fractions import Fraction
from math import gcd
def parlay_odds(odds):
if isinstance(odds, int):
g_cd = gcd(odds, 1)
num = int(odds / g_cd)
denom = 1
return Fraction(num, denom)
elif isinstance(odds, float):
new_odds = int((odds - 1) * 100)
g_c... | magicoder | python |
You are tasked with creating a Python function that measures the time taken to update project files in a given directory using a specified tool. Your function should take in the tool path, directory, and a flag indicating whether the update should be performed recursively. The function should then return the number of ... | ```python
import datetime
import os
from typing import Tuple
def update_project_files(tool_path: str, directory: str, recursive: bool) -> Tuple[int, datetime.timedelta]:
start_time = datetime.datetime.now()
updated_file_count = 0
# Perform the update using the specified tool
# Replace the following pl... | magicoder | python |
You are tasked with implementing a class that manages SSL/TLS server configurations. Your task is to create a Swift class `SSLServerConfig` with an initializer that takes in various parameters to set up the SSL/TLS server context.
The `SSLServerConfig` class should have the following properties and functionalities:
- ... | ```swift
enum ServerType {
case http
case webSocket
// Add more server types as needed
}
class SSLServerConfig {
let server: ServerType
let sslContext: SSLServerContext
init(server: ServerType, certificate: String, privateKey: String, certificateChain: String? = nil) throws {
self.serv... | magicoder | swift |
You are tasked with creating a program that processes a given Blade template file and extracts the content within the `@section` directives. Blade is a templating engine used in the Laravel PHP framework, and it allows developers to write expressive, concise templates using a familiar syntax.
Your program should read ... | ```python
import re
def extract_sections_from_blade_template(file_path):
with open(file_path, 'r') as file:
content = file.read()
section_matches = re.findall(r"@section\('([^']*)'\)(.*?)@endsection", content, re.DOTALL)
for section_name, section_content in section_matches:
print(f"Sectio... | magicoder | python |
You are tasked with implementing a simplified version of a TransformerDecoder module in PyTorch. The TransformerDecoder is a stack of N decoder layers, each of which consists of self-attention, multi-head attention, and position-wise feedforward networks. Your task is to implement the forward method of the TransformerD... | ```python
import torch
import torch.nn as nn
class TransformerDecoder(nn.Module):
def __init__(self, d_model, nhead, num_layers, dim_feedforward, dropout):
super(TransformerDecoder, self).__init__()
decoder_layer = nn.TransformerDecoderLayer(d_model, nhead, dim_feedforward, dropout)
self.tr... | magicoder | python |
You are tasked with implementing a multi-threaded program that simulates a simple lock mechanism using Rust's standard library. The lock should allow multiple threads to read a shared resource concurrently, but only one thread should be able to write to the resource at a time. Your task is to implement the lock and ens... | ```rust
use std::sync::{Arc, Mutex};
use std::thread;
struct SharedResource {
// Define the shared resource here
}
fn main() {
// Create a shared resource
let shared_resource = Arc::new(Mutex::new(SharedResource { /* initialize resource */ }));
// Spawn multiple reader threads
for _ in 0..5 {
... | magicoder | rust |
You are tasked with designing a class that wraps the functionality of the FFmpeg library for handling audio and video frames. The provided code snippet shows the constructor of a class called `AVFrameWrapper`, which takes an object of type `FFmpegFunctions` as a parameter. Your task is to implement the `AVFrameWrapper`... | ```cpp
#include <iostream>
#include <FFmpegFunctions.h> // Assuming the header file for FFmpegFunctions is included
class AVFrameWrapper {
private:
FFmpegFunctions ffmpeg; // Instance of FFmpegFunctions
// Other private data members as needed
public:
AVFrameWrapper(const FFmpegFunctions& ffmpeg) noexcept ... | magicoder | cpp |
You are tasked with implementing a simplified XML document management system. The provided code snippet is a part of the XMLManager class, which is responsible for creating new XML documents.
The XMLManager class has a method `newXMLDoc` that takes two parameters:
1. `opnum` (an integer) - representing the operation n... | ```cpp
#include <iostream>
#include <string>
#include <vector>
class XMLDoc {
private:
int ID;
std::vector<std::pair<int, std::string>> children;
public:
XMLDoc(int id) : ID(id) {}
void newChild(int opnum, std::string CDATA) {
children.push_back(std::make_pair(opnum, CDATA));
}
void ... | magicoder | cpp |
You are given a string `s` consisting of lowercase English letters and an integer `k`. Your task is to write a function that takes the string `s` and the integer `k` as input and returns the final value of `nums` after performing the following operations `k` times:
1. Convert each character in the string `s` to its co... | ```python
def final_value(s: str, k: int) -> int:
nums = ''
for char in s:
nums += str(ord(char) - ord('a') + 1)
for i in range(k):
nums = str(sum((int(c) for c in nums)))
return int(nums)
# Test cases
print(final_value("abc", 2)) # Output: 9
print(final_value("xyz", 3))... | magicoder | python |
You are tasked with implementing a correction rewriter for a text processing system. The rewriter takes three sets of strings: original values, errors, and their corresponding corrections. The rewriter is initialized with these sets and used to correct errors in the input text.
You need to implement a function that ta... | ```cpp
#include <string>
#include <vector>
#include <algorithm>
class CorrectionRewriter {
// Assume the implementation of CorrectionRewriter class
};
std::string CorrectErrors(const std::string& input) {
// Assume rewriter_ is the initialized CorrectionRewriter instance
// Apply the correction rewriter ... | magicoder | cpp |
You are tasked with implementing a generic data structure in Rust that represents a MaybeNull type, which can be used to handle nullable values in a database context. The MaybeNull type wraps another type T, which itself implements the Expression trait. Additionally, the MaybeNull type has an associated type SqlType, w... | ```rust
use diesel::expression::Expression;
use diesel::query_builder::QueryFragment;
use diesel::sql_types::IntoNullable;
use diesel::query_builder::QueryBuilder;
use diesel::backend::Backend;
struct MaybeNull<T> {
inner: T,
}
impl<T> Expression for MaybeNull<T>
where
T: Expression,
T::SqlType: IntoNulla... | magicoder | rust |
You are tasked with implementing a function to extract data from comments in a specific format. The comments contain data islands, which are sections of structured data embedded within the comments. The data islands are represented as dictionaries in JSON-like format, where keys and values are separated by colons and i... | ```python
import re
def extract_data_from_comment(comment: str) -> dict:
data_islands = re.findall(r'{(.*?)}', comment)
extracted_data = {}
for island in data_islands:
try:
data = eval('{' + island + '}')
if isinstance(data, dict):
extracted_data.update(data)... | magicoder | python |
You are tasked with implementing a function to parse a given file containing opcode information and storing it in a data structure for further processing. The file contains opcode information in the following format:
```
opcode_name_1 opcode_ref_1
opcode_name_2 opcode_ref_2
...
```
Where `opcode_name` is a string rep... | ```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_OPCODES 100
typedef struct
{
char *pszName;
int ref;
} OpcodeInfo;
int parseOpcodeFile(const char *filePath, OpcodeInfo *opcodes) {
FILE *file = fopen(filePath, "r");
if (file == NULL) {
perror("Error opening file");
... | magicoder | c |
You are tasked with implementing a custom HTML parser in Python that utilizes the BeautifulSoup library for processing HTML content. Your parser should extend the `BaseParser` class and provide a method `parse_data` to handle the parsing of HTML data. The method should accept several parameters including the HTML text,... | ```python
from bs4 import BeautifulSoup
from base_parser import BaseParser
class HTMLParser(BaseParser):
"""
Use BeautifulSoup for easy html processing.
"""
def parse_data(self, text, maxwidth, maxheight, template_dir, context, urlize_all_links):
# Parse the HTML text using BeautifulSoup
... | magicoder | python |
You are tasked with creating a Python class for managing a game lobby system using SQLAlchemy, a popular ORM (Object-Relational Mapping) library for Python. Your task is to implement a class called `GameLobby` that represents a game lobby in a multiplayer game application. The lobby will have a one-to-many relationship... | ```python
from sqlalchemy import Column, Integer, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class GameLobby(Base):
__tablename__ = 'lobby'
id = Column(Integer, primary_key=True)
words = relationship("GameWord", back... | magicoder | python |
You are tasked with implementing a k-nearest neighbor (k-NN) algorithm for a given set of points in a two-dimensional space. The k-NN algorithm is a simple, yet powerful, classification and regression technique used for pattern recognition and predictive modeling.
Your task is to create a function that takes a set of ... | ```rust
fn k_nearest(points: &[(f64, f64)], pt: (f64, f64), k: usize) -> Vec<(f64, f64)> {
let mut distances: Vec<(f64, usize)> = points
.iter()
.enumerate()
.map(|(i, &p)| (euclidean_distance(pt, p), i))
.collect();
distances.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
... | magicoder | rust |
You are tasked with implementing a context manager for a database connection in Python. The context manager should handle the opening and closing of the database connection, as well as the committing or rolling back of transactions based on whether an exception occurred within the context.
Your task is to complete the... | ```python
import psycopg2
class DatabaseConnection:
def __init__(self, dbname, user, password, host, port):
self.dbname = dbname
self.user = user
self.password = password
self.host = host
self.port = port
self.connection = None
self.cursor = None
def __e... | magicoder | python |
You are tasked with implementing a Python function that calculates the contour levels of a bivariate normal distribution and visualizes them using filled contour plots. The bivariate normal distribution is defined by the equation:
\[ f(x, y) = \frac{1}{2\pi\sigma_x\sigma_y\sqrt{1-\rho^2}} \exp\left(-\frac{1}{2(1-\rho^... | ```python
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import multivariate_normal
def plot_bivariate_normal_contour(mu_x, mu_y, sigma_x, sigma_y, rho):
# Create a grid of x and y values
delta = 0.025
x = np.arange(-3.0, 3.0, delta)
y = np.arange(-3.0, 3.0, delta)
X, Y = np.me... | magicoder | python |
You are tasked with implementing a Python function that calculates the attention and co-attention masks for two input tensors. The function should take into account the use of co-attention masks and biattention probabilities. The biattention function is already provided and takes two input tensors as arguments. Your ta... | ```python
def calculate_masks(input_tensor1, input_tensor2, attention_mask1=None, attention_mask2=None, co_attention_mask=None, use_co_attention_mask=False):
# Calculate attention masks
if use_co_attention_mask:
attention_mask1 = input_tensor1 != 0 # Example calculation, replace with actual attention m... | magicoder | python |
You are tasked with implementing a text processing algorithm that involves replacing protected tokens in a given text and handling special characters for specific languages. The provided code snippet is a part of the algorithm and contains some incomplete and commented-out code. Your task is to complete the algorithm b... | To complete the text processing algorithm, you can follow the steps below:
1. Complete the implementation of replacing protected tokens in the given text:
```python
# Apply the protected_patterns.
for i, token in enumerate(protected_tokens):
substitution = "THISISPROTECTED" + str(i).zfill(3)
text = text.replac... | magicoder | python |
You are tasked with creating a Flutter plugin for macOS that integrates with the bitsdojo_window package to customize the window appearance and behavior. The bitsdojo_window package provides functionalities for customizing the window frame, title bar, and other window-related features in a Flutter desktop application.
... | ```swift
// clang-format off
import FlutterMacOS
import Foundation
import bitsdojo_window_macos
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
BitsdojoWindowPlugin.register(with: registry.registrar(forPlugin: "BitsdojoWindowPlugin"))
// Customizing the window appearance and behavior
if let w... | magicoder | swift |
You are tasked with implementing a generic factory interface for creating tabs in a form. The interface, `IEmfFormTabFactory`, is defined as follows:
```java
import com.softicar.platform.dom.elements.tab.DomTab;
import com.softicar.platform.emf.form.IEmfForm;
import com.softicar.platform.emf.table.row.IEmfTableRow;
p... | ```java
import com.softicar.platform.dom.elements.tab.DomTab;
import com.softicar.platform.emf.form.IEmfForm;
import com.softicar.platform.emf.table.row.IEmfTableRow;
public class MyFormTabFactory<R extends IEmfTableRow<R, ?>> implements IEmfFormTabFactory<R> {
@Override
public boolean isVisible(R row) {
// Add l... | magicoder | java |
You are tasked with creating a Python function that processes a given HTML code snippet and extracts the text content of all the anchor tags with the class "menu-item". The function should return a list of the extracted text content in the order they appear in the HTML code.
Function Signature: `def extract_menu_items... | ```python
from bs4 import BeautifulSoup
from typing import List
def extract_menu_items(html: str) -> List[str]:
soup = BeautifulSoup(html, 'html.parser')
menu_items = soup.find_all('a', class_='menu-item')
return [item.get_text() for item in menu_items]
``` | magicoder | python |
You are tasked with implementing a product repository using C#. The repository should allow for adding, updating, and retrieving products by their unique identifiers. Additionally, the repository should support the ability to retrieve all products that have a price within a specified range.
You are provided with a par... | ```csharp
using System;
using System.Collections.Generic;
public class Product
{
public string Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
public class AlternateRepository
{
private Dictionary<string, Product> products;
public AlternateRepository()
{... | magicoder | csharp |
You are tasked with creating a Python program that simulates a simple game using the `pyautogui` library. The game involves a player navigating through a maze by pressing arrow keys to move a character represented by an image. The objective is to reach the end of the maze without hitting any obstacles.
Your program sh... | ```python
import pyautogui
import time
# Function to detect obstacles at given coordinates
def detect_obstacle(x, y):
# Use pyautogui to capture the pixel color at the given coordinates
pixel_color = pyautogui.pixel(x, y)
# Check if the pixel color matches the color of the obstacle
# Replace (R, G, B) ... | magicoder | python |
You are tasked with creating a program that simulates a simple CPU scheduling algorithm. The program should implement a round-robin scheduling algorithm to allocate CPU time to a set of processes. Each process has a unique process ID, arrival time, burst time, and priority. The round-robin algorithm should allocate a f... | ```python
import json
def round_robin_scheduling(time_quantum, processes):
queue = processes.copy()
execution_order = []
current_time = 0
while queue:
process = queue.pop(0)
if process["burst_time"] > time_quantum:
execution_order.append(process["pid"])
current_t... | magicoder | python |
You are tasked with implementing a custom sorting method for an array of objects that conform to the `Dateable` protocol. The `Dateable` protocol ensures that the conforming objects have a date property that can be used for sorting. Your task is to complete the implementation of the `sorted(byDateDescending:)` method w... | ```swift
extension Array where Element: Dateable {
public mutating func sorted(byDateDescending descending: Bool = true) {
self.sort { (first, second) in
if descending {
return first.date > second.date
} else {
return first.date < second.date
... | magicoder | swift |
You are tasked with creating a Swift program to manage comments on a social media platform. The program should include a class for comments and a protocol for comment functionality. The `Comment` class is a subclass of `NSManagedObject` and conforms to the `CommentProtocol`. It has properties for `identifier`, `body`, ... | ```swift
protocol CommentProtocol {
// Define protocol requirements here
}
final class Comment: NSManagedObject, CommentProtocol {
@NSManaged private(set) var identifier: Int64
@NSManaged private(set) var body: String
@NSManaged private(set) var name: String
@NSManaged private(set) var post: Post?
... | magicoder | swift |
You are tasked with creating a Python program that generates a wordlist based on a given set of characters and a maximum length. The wordlist should contain all possible combinations of the characters up to the specified maximum length. The program should also provide the option to save the generated wordlist to a file... | ```python
def generate_wordlist(characters, max_length, output_file=None):
wordlist = []
generate_word("", characters, max_length, wordlist)
if output_file:
with open(output_file, 'w') as file:
for word in wordlist:
file.write(word + '\n')
else:
print(wor... | magicoder | python |
You are tasked with implementing a simplified version of Conway's Game of Life, a cellular automaton devised by the British mathematician John Horton Conway. The game is played on an infinite two-dimensional grid of square cells, each of which is in one of two possible states: alive or dead. Every cell interacts with i... | ```rust
struct ConwaysLife;
impl ConwaysLife {
fn simulate_with_logic(initial_state: bool, live_neighbors: usize) -> bool {
if initial_state {
match live_neighbors {
2 | 3 => true,
_ => false,
}
} else {
live_neighbors == 3
... | magicoder | rust |
You are tasked with implementing a constraint satisfaction problem (CSP) for assigning robots to specific targets. The given code snippet is a part of the implementation using the Constraint Programming (CP) library. Your task is to complete the implementation by defining the constraints and variables for the CSP probl... | To solve the CSP problem of assigning robots to targets, you can define the variables and constraints as follows:
```python
from ortools.sat.python import cp_model
class RobotAssignmentProblem:
def __init__(self, robotgrid):
self.robotgrid = robotgrid
self.model = cp_model.CpModel()
self.a... | magicoder | python |
You are tasked with creating a program that analyzes the licensing information of a given source code file. The program should read the file and determine if the license information complies with the Apache License, Version 2.0. The Apache License, Version 2.0, allows the use of the licensed software for any purpose, i... | ```python
import re
def check_apache_license(file_path):
with open(file_path, 'r') as file:
content = file.read()
apache_license_pattern = r"Licensed under the Apache License, Version 2.0"
license_url_pattern = r"http://www.apache.org/licenses/LICENSE-2.0"
copyright_pattern = r"Copy... | magicoder | python |
You are tasked with creating a command-line tool to manage the startup of multiple development environments for a monorepo project. The project consists of three main components: API, App, and Web. Each component has specific startup commands and may require different configurations. Your task is to create a script tha... | ```bash
#!/bin/bash
# Start API component
guake --split-vertical -e 'cd ~/Source/v3vo/monorepo/api && npm run test -- --watch'
# Start App component
guake -n guake -e 'cd ~/Source/v3vo/monorepo/app && npm run start' guake -r app
guake --split-vertical -e 'cd ~/Source/v3vo/monorepo/app && npm run dev'
# Start Web com... | magicoder | shell |
You are tasked with creating a mock implementation for a service in an Angular application. The application uses dependency injection to provide different implementations for services based on the environment. In this case, you need to create a mock implementation for the `TaskService` using Angular's dependency inject... | ```typescript
// TaskServiceMock.ts
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { Task } from './task.model';
@Injectable()
export class TaskServiceMock {
// Mock data for tasks
private mockTasks: Task[] = [
{ id: 1, title: 'Mock Task 1', description: 'This is a m... | magicoder | typescript |
You are tasked with creating a Rust program that interacts with a Kubernetes cluster using the `kube` crate. Your program needs to implement a watcher that monitors changes to resources in the Kubernetes cluster and logs relevant information.
Your task is to complete the implementation of the `main` function to achiev... | ```rust
use kube::Client;
use log::debug;
use std::env;
use anyhow::Result; // Import the Result type from the `anyhow` crate
#[tokio::main]
async fn main() -> Result<()> {
// Set the log level to "info" if the environment variable "RUST_LOG" is not set
if env::var("RUST_LOG").is_err() {
env::set_var("... | magicoder | rust |
You are working as a DevOps engineer for a company that manages multiple servers and applications. As part of your responsibilities, you need to automate the process of starting and stopping various services on the servers. You have a configuration file named `terminal_configs.sh` that contains a series of commands to ... | ```python
import subprocess
def execute_commands_from_file(file_path):
try:
with open(file_path, 'r') as file:
commands = file.readlines()
for command in commands:
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
... | magicoder | python |
You are tasked with implementing a function to generate an RSA key pair using the iOS Security framework. The iOS Security framework provides a set of functions and data types for implementing security services in iOS applications. The code snippet provided initializes parameters for generating an RSA key pair and then... | ```swift
import Security
func generateRSAKeyPair(completion: @escaping (SecKey?, SecKey?, Error?) -> Void) {
let parameters: [String: Any] = [
kSecAttrKeyType as String: kAsymmetricCryptoManagerKeyType,
kSecAttrKeySizeInBits as String: kAsymmetricCryptoManagerKeySize,
kSecPublicKeyAttrs as ... | magicoder | swift |
You are tasked with creating a Rust WebAssembly (Wasm) module that implements a simple hashing function. The hashing function should take a string as input and return its hash value. You will need to use the `wasm-bindgen` tool to generate the Wasm module and make it accessible to JavaScript.
Your task is to write the... | Rust code for hashing function (`lib.rs`):
```rust
use wasm_bindgen::prelude::*;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
#[wasm_bindgen]
pub fn hash_string(input: &str) -> u64 {
let mut hasher = DefaultHasher::new();
input.hash(&mut hasher);
hasher.finish()
}
```
Gene... | magicoder | rust |
You are tasked with implementing a logging system for a file processing application. The application processes AsciiDoc files and attempts to extract the title from each file. However, if the title extraction fails, the application logs an error message using a logger object. The code snippet provided is a part of the ... | ```python
import logging
class AsciiDocProcessor:
def __init__(self, logger):
self.logger = logger
def process_file(self, file_path):
try:
# Attempt to extract the title from the AsciiDoc file
# If extraction fails, raise an OSError for demonstration purposes
... | magicoder | python |
You are tasked with implementing a utility function to calculate the size of a file after gzip compression. The function should accept a file path as input and return the size of the compressed file in bytes. Additionally, you need to create a stream that emits a `gzip-size` event and has a `gzipSize` property.
Your t... | ```typescript
// Import the required modules and interfaces
import { createReadStream } from 'fs';
import { createGzip } from 'zlib';
import { EventEmitter } from 'events';
// Define the Options interface for configuration parameters
interface Options {
level?: number; // Compression level
}
// Define the GzipSizeS... | magicoder | typescript |
You are given a class `CustomArray` that represents a custom implementation of an array. The class has the following methods:
- `size()`: Returns the size of the array.
- `get(index)`: Returns the element at the specified index.
- `set(index, value)`: Sets the element at the specified index to the given value.
You nee... | ```python
class CustomArray:
def __init__(self, elements):
self.elements = elements
def size(self):
return len(self.elements)
def get(self, index):
return self.elements[index]
def set(self, index, value):
self.elements[index] = value
def lowerAlternateElements(arr: Cu... | magicoder | python |
You are tasked with implementing a Python class that simulates a simple messaging system. The class, named `MessagingSystem`, should allow users to create connections, send messages, and close connections. Your task is to implement the `MessagingSystem` class with the following methods:
1. `__init__(self)`: Initialize... | ```python
import uuid
class MessagingSystem:
def __init__(self):
self.connections = {}
def create_connection(self):
connection_id = str(uuid.uuid4())
self.connections[connection_id] = []
return connection_id
def send_message(self, connection_id, message):
if connec... | magicoder | python |
You are given two binary strings, a and b, which represent non-negative integers. Write a function to add the two numbers and return the sum as a binary string.
The input strings are both non-empty and contain only characters 1 or 0.
Example:
Input: a = "11", b = "1"
Output: "100"
Input: a = "1010", b = "1011"
Outpu... | ```python
def addBinary(a, b):
result = ""
carry = 0
i, j = len(a) - 1, len(b) - 1
while i >= 0 or j >= 0 or carry:
if i >= 0:
carry += int(a[i])
i -= 1
if j >= 0:
carry += int(b[j])
j -= 1
result = str(carry % 2) + result
c... | magicoder | python |
You are tasked with implementing a tracking module for a physics simulation software. The tracking module is responsible for processing and analyzing tracks of particles within the simulated environment. The code snippet provided is the beginning of the base class `THaTrackingModule` for this tracking module.
Your tas... | ```cpp
// THaTrackingModule
//
// Base class for a "track" processing module, which is a
// specialized physics module.
//
//////////////////////////////////////////////////////////////////////////
#include "THaTrackingModule.h"
#include "VarDef.h"
class THaTrackingModule {
// ... other class members and method... | magicoder | cpp |
You are tasked with creating a script that processes a list of files and performs specific operations on each file. The script should handle errors gracefully and provide detailed logging for each operation. Your task is to implement the missing functionality in the given Bash script template.
```bash
#!/bin/bash
set... | ```bash
#!/bin/bash
set -xe
# Function to process a file
process_file() {
file=$1
# Check if the file exists
if [ -f "$file" ]; then
echo "Processing file: $file"
# Perform operations such as file manipulation, analysis, or transformation
# Example: Count the number of lines in the... | magicoder | shell |
You are working on a reinforcement learning algorithm that involves simulating multiple paths and making decisions based on immediate rewards. The given code snippet is a part of a larger algorithm and is responsible for determining the stopping time for each path and calculating the rewards based on the stopping time.... | ```python
import numpy as np
def calculate_rewards(continue_value, immediate_reward, pol_sim_paths_rewards, discount, num_stages, pol_sim_sample_paths):
eliminated_paths = []
reward = []
continue_value_list = np.zeros_like(continue_value)
for t in range(num_stages):
stopping_time = np.less_eq... | magicoder | python |
You are tasked with implementing a function to calculate the hash of a Git object based on its type and content. Git objects can have different types such as commit, tree, blob, tag, or an offset delta. The hash calculation is based on the SHA-1 algorithm and involves concatenating the object type, a space character, t... | ```rust
use sha1::{Digest, Sha1};
enum ObjectType {
Commit,
Tree,
Blob,
Tag,
OfsDelta(u32),
}
fn git_sha1(object_type: &str, content_length: usize, content: &str) -> String {
let mut input = String::new();
input.push_str(object_type);
input.push(' ');
input.push_str(&content_length... | magicoder | rust |
You are tasked with creating a script to automate the process of checking for uncommitted changes in a Git repository and obtaining the current commit's SHA-1 hash. Your script should perform the following steps:
1. Use the `git rev-parse HEAD` command to obtain the SHA-1 hash of the current commit.
2. If the `git rev... | ```bash
GIT_REV=$(git rev-parse HEAD)
if [[ $? != 0 ]];
then
exit 1
fi
echo "BUILD_SCM_REVISION ${GIT_REV}"
# Check whether there are any uncommitted changes.
if [[ -n $(git status -s) ]];
then
echo "Uncommitted changes found"
exit 1
else
echo "No uncommitted changes"
exit 0
fi
```
In the solution... | magicoder | shell |
You are tasked with creating a command-line interface (CLI) tool for sending notifications using different methods. The tool should support sending notifications over Gotify and email. The CLI should have subcommands for each notification method, and each subcommand should have specific arguments for configuring the no... | ```python
import argparse
import os
def send_gotify(args):
# Implementation for sending notifications over Gotify
print(f"Sending Gotify notification: Host={args.gotify_host}, Token={args.gotify_token}, Message={args.message}")
def send_email(args):
# Implementation for sending notifications over email
... | magicoder | python |
You are tasked with implementing a custom hook in a React application that retrieves and parses query parameters from the URL. The hook should return an object containing the parsed query parameters, with each parameter's value being of type string. You are provided with a code snippet that serves as a starting point f... | ```typescript
import { useLocation } from 'react-router-dom';
export function useSearchParams<T extends { [key in keyof T]?: string }>(): T {
const searchParams = new URLSearchParams(useLocation().search);
const parsedParams: Partial<T> = {};
for (const [key, value] of searchParams.entries()) {
if (key in p... | magicoder | typescript |
You are tasked with implementing a custom error handling system for a Bluetooth Low Energy (BLE) communication module in a Swift-based iOS application. The provided code snippet contains a set of error cases that can occur during various stages of BLE communication. Your task is to create a custom Swift enum that repre... | ```swift
// Custom BLE Error Enum
enum BLEError: Error {
// Services
case servicesDiscoveryFailed(peripheral: Peripheral, error: Error?)
case includedServicesDiscoveryFailed(peripheral: Peripheral, error: Error?)
case addingServiceFailed(service: CBServiceMock, error: Error?)
case serviceDeallocated... | magicoder | swift |
You are tasked with creating a Python script to manage a database of cryptographic keys. The script should provide options to drop old keys, generate new keys, or generate new keys only if none exist. The script should interact with a database using the `sqlite3` module.
Your task is to implement the `manage_keys` fun... | ```python
# The solution provided in the problem description is a comprehensive and correct solution to the problem. It establishes a connection to the database, creates the keys table if it does not exist, and defines the `manage_keys` function to handle the specified options. The function correctly performs the actio... | magicoder | python |
You are tasked with implementing a custom deserialization process for a Python class that represents objects with various attributes, including a duration attribute. The class `TestDurationObj` has a dictionary `attr_desc` that describes the attributes and their types. The duration attribute is specified with the key "... | ```python
class DeserializationError(Exception):
pass
class TestDurationObj:
attr_desc = {
'attr_a': {'key': 'attr_a', 'type': 'duration'},
}
@classmethod
def from_dict(cls, data):
obj = cls()
for attr, attr_desc in cls.attr_desc.items():
if attr_desc['type'] ==... | magicoder | python |
You are tasked with implementing a function that converts a given string of digits into their corresponding word representation. For example, "123" should be converted to "one two three".
You are given a partial code snippet in Rust that uses conditional compilation attributes to define a macro for creating the conver... | ```rust
macro_rules! new {
($name:ident; $($digit:literal->$word:literal),*; avx = true) => {
pub fn $name(input: &str) -> String {
let mut result = String::new();
for c in input.chars() {
match c {
$($digit => result.push_str($word),)*
... | magicoder | rust |
You are tasked with creating a SwiftUI view that displays a list of monsters with a search functionality. The monsters are fetched from an external source and are represented by the `Monster` struct, which has properties `id`, `name`, and `icon`. The search functionality should filter the monsters based on the user's i... | ```swift
import SwiftUI
struct Monster: Identifiable {
let id: Int
let name: String
let icon: String
}
struct MonsterListView: View {
@State private var searchText = ""
@State private var isSearching = false
@State private var filteredMonsters: [Monster] = []
var body: some View {
... | magicoder | swift |
You are tasked with creating a Python function that can efficiently determine the number of occurrences of a specific word in a collection of text files. To achieve this, you need to implement a function that takes in a directory path and a target word as input and returns the total count of occurrences of the target w... | ```python
import os
import re
def count_word_occurrences(directory_path: str, target_word: str) -> int:
total_occurrences = 0
for root, _, files in os.walk(directory_path):
for file in files:
if file.endswith('.txt'):
file_path = os.path.join(root, file)
with... | magicoder | python |
You are tasked with implementing a class method for searching entities based on a given search term. The method should iterate over a collection of entities and yield those that contain the search term. You are provided with a partial implementation of the class containing the method `search_entities`. Your task is to ... | ```python
class EntitySearch:
def entity_contains(self, entity, search):
"""
Check if the entity contains the search term.
"""
return search in entity
def search_entities(self, entities, search):
"""
Iterate over entities from supplied iterator containing supplie... | magicoder | python |
You are given a list of strings, where each string represents a comma-separated sequence of numeric values. Your task is to write a function that processes the input list and returns a new list containing only those sequences that do not contain the maximum representable floating-point number (1.7e+308).
Write a funct... | ```python
from typing import List
def filter_max_float(datas: List[str]) -> List[List[float]]:
cols = []
for data in datas:
col = []
for _it in data.split(','):
if _it.strip() != '':
col.append(float(_it))
if 1.7e+308 not in col:
cols.append(col)
... | magicoder | python |
You are tasked with implementing a function that processes input from a call context and returns an optional 16-bit unsigned integer. The call context provides access to arguments of various types, and the function should handle these inputs appropriately. Your task is to create a Rust function that achieves this funct... | ```rust
use quickjs_runtime::{CallContext, JsUnknown, ValueType, to_js_error};
pub fn get_optional_u16(ctx: &CallContext, index: usize) -> Result<Option<u16>, JsValue> {
let arg = ctx.get::<JsUnknown>(index)?;
let result = match arg.get_type()? {
ValueType::Undefined | ValueType::Null => None,
... | magicoder | rust |
You are tasked with implementing a function that calculates the average of a list of latitude coordinates. Latitude coordinates are represented in degrees and can range from -90 to 90. Your function should take in a list of latitude coordinates and return the average latitude.
Function Signature:
```python
def averag... | ```python
from typing import List
def average_latitude(latitudes: List[float]) -> float:
if not latitudes:
return 0.0 # Return 0 if the input list is empty
total = sum(latitudes)
average = total / len(latitudes)
return average
```
The `average_latitude` function takes a list of latitude coord... | magicoder | python |
You are tasked with creating a Python program to monitor the active window on a Linux system using Xlib. The program should continuously print the name and bounding box coordinates (x1, y1, x2, y2) of the active window in a loop.
Your program should utilize the Xlib library to achieve this functionality. The Xlib libr... | ```python
import Xlib.X
import Xlib
import Xlib.display
from Xlib.ext import randr
import time
# Connect to the X server
display = Xlib.display.Display()
root = display.screen().root
# Define a named tuple to store window information
WindowInfo = namedtuple('WindowInfo', ['name', 'x1', 'y1', 'x2', 'y2'])
# Function ... | magicoder | python |
You are tasked with designing a Python class that manages various operations related to a data outflow system. The class should include methods for handling datasets, delivery nodes, fulfillment options, fulfillment plans, items, and order fulfillments. Each of these operations is represented by a separate attribute in... | ```python
class DataOutflowManager:
def __init__(self, data_outflow_run, dataset, delivery_node, fulfillment_option, fulfillment_plan, item, order_fulfillment):
self.data_outflow_run = data_outflow_run
self.dataset = dataset
self.delivery_node = delivery_node
self.fulfillment_option ... | magicoder | python |
You are tasked with creating a form validation function for a serverless application deployment tool. The function should validate the input parameters for deploying a serverless function to AWS Lambda. The input parameters include the function name, AWS region, S3 bucket name, repository URI, build command, and the di... | ```java
import java.util.regex.Pattern;
public class FormValidator {
public static FormValidation validate(String functionName, String region, String s3Bucket, String repoUri, String command, String storeToS3) {
if (functionName.isEmpty() || region.isEmpty() || s3Bucket.isEmpty() || repoUri.isEmpty() || co... | magicoder | java |
You are tasked with implementing a thread-safe singleton logger class in Python. The class should ensure that only one instance of the logger is created and that it can be accessed from multiple threads without causing any race conditions.
You need to create a `SafeLogger` class that follows the singleton pattern and ... | ```python
import logging
import threading
class SafeLogger(object):
_lock = threading.Lock()
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
with cls._lock:
if cls._instance is None:
cls._instance = super(SafeLogger, cls... | magicoder | python |
You are tasked with creating a Python function to process and analyze data from a baseball game. The function will take a list of player statistics as input and perform various calculations to determine the overall performance of the players. The statistics include the player's name, number of hits, number of at-bats, ... | ```python
from typing import List, Dict, Union
def calculate_player_performance(player_stats: List[Dict[str, Union[str, int]]]) -> Dict[str, float]:
performance_ratings = {}
for player in player_stats:
hits = player["hits"]
at_bats = player["at_bats"]
rbis = player["rbis"]
perfo... | magicoder | python |
You are tasked with creating a command-line interface (CLI) tool for running tests in a Python project. The tool should accept different testing "modes" as command-line arguments and execute the corresponding tests based on the mode specified.
Your task is to implement a Python script that takes in command-line argume... | ```python
import sys
def run_full_tests():
# Implement code to run all tests
print("Running all tests...")
def run_backend_tests(backend):
# Implement code to run tests using a specific backend
print(f"Running tests using backend: {backend}...")
def run_nobackend_tests():
# Implement code to run ... | magicoder | python |
You are tasked with implementing a Private Frequency Oracle (PFO) class in C++ to estimate the frequency of elements in a dataset while preserving the privacy of individual elements. The PFO uses the Count-Min Sketch algorithm with differential privacy to achieve this.
Your task is to complete the implementation of th... | ```cpp
#include <cstdint>
#include <vector>
#include <string>
#include <cmath>
#include <random>
#include <iostream>
class PrivateFrequencyOracle {
public:
PrivateFrequencyOracle(int K_, double eps_, bool debug_=false, uint32_t seed=0)
: K(K_), eps(eps_), debug(debug_), seed(seed) {
int width = sta... | magicoder | cpp |
You are tasked with implementing a stack-based evaluation system for mathematical expressions. The system should support the evaluation of arithmetic expressions involving addition, subtraction, multiplication, and division. The expressions are represented using a custom data structure, and the evaluation process invol... | ```java
private void evalUpdate(){
UpdCont upd = (UpdCont) s.pop(); // Pop the update from the stack
Expr x = upd.x; // Retrieve the expression to be updated from the update
// Apply the update to the expression
switch (upd.op) {
case ADD:
x.setValue(x.getValue() + upd.value);
... | magicoder | java |
You are tasked with implementing a class that manages a collection of strings and their associated IDs. The class should provide functionality to add a new string with a unique ID, retrieve a string by its ID, and remove a string by its ID. Additionally, the class should support the ability to retrieve the ID of a give... | ```cpp
#include <unordered_map>
#include <string>
class StringManager {
private:
std::unordered_map<tCIDLib::TCard4, std::string> idToStringMap;
std::unordered_map<std::string, tCIDLib::TCard4> stringToIdMap;
tCIDLib::TCard4 nextId = 1;
public:
// Add a new string with a unique ID
void addString(c... | magicoder | cpp |
You are tasked with creating a function that generates an unguessable reference. An unguessable reference is a unique identifier that is difficult for an outsider to predict or guess. Your task is to implement a function that generates such a reference using a combination of random characters.
You are given the follow... | ```python
import random
import string
def generate_unguessable_reference(length=10):
characters = string.ascii_letters + string.digits # Concatenating uppercase letters, lowercase letters, and digits
unguessable_reference = ''.join(random.choice(characters) for _ in range(length)) # Generating a random refer... | magicoder | python |
You are tasked with implementing a Python class for creating and sending email messages. The class should provide methods for setting various attributes of the email message, such as the sender, receiver, subject, body, and attachments. The class should also allow method chaining for setting multiple attributes in a si... | ```python
class EmailMessage:
def __init__(self):
self.message = {}
def set_sender_email(self, email):
self.message['sender'] = email
return self
def set_receiver_email(self, email):
self.message['receiver'] = email
return self
def set_cc_emails(self, emails):
... | magicoder | python |
You are tasked with creating a function that parses a given HTML code and extracts all the href attributes from anchor tags within a specific parent element. The function should take the HTML code and the class name of the parent element as input and return a list of href attributes.
For example, given the following H... | ```python
from bs4 import BeautifulSoup
def extractHrefAttributes(html, parentClassName):
href_attributes = []
soup = BeautifulSoup(html, 'html.parser')
parent_element = soup.find(class_=parentClassName)
if parent_element:
anchor_tags = parent_element.find_all('a')
href_attributes = [ta... | magicoder | python |
You are tasked with creating a program that simulates a simple memory management system. The system should allocate and deallocate memory blocks and keep track of memory leaks using a simplified version of Valgrind, a popular memory debugging tool.
Your program should support the following commands:
1. `allocate <bloc... | ```python
class MemoryManager:
def __init__(self):
self.memory_blocks = {}
def allocate(self, block_id, size):
if block_id in self.memory_blocks:
print(f"Error: Block with ID {block_id} already exists")
else:
self.memory_blocks[block_id] = [0] * size
... | magicoder | python |
You are tasked with implementing a chess game in TypeScript. You need to create a class that represents a chess piece and its position on the board. The chess pieces include pawns, rooks, knights, bishops, queens, and kings. Each piece has a color (white or black) and a position on the board represented by a combinatio... | ```typescript
export enum Player {
WHITE, BLACK
}
export enum PieceType {
PAWN, ROOK, KNIGHT, BISHOP, QUEEN, KING
}
export class ChessPiece {
color: Player;
position: string;
type: PieceType;
constructor(color: Player, position: string, type: PieceType) {
this.color = color;
this.position = posit... | magicoder | typescript |
You are tasked with automating the deployment process of a software project using Docker. Your goal is to create a script that builds a Docker image, tags it, and pushes it to a container registry. The script should be able to handle different versions of the software and push the images to a specific container registr... | ```bash
#!/bin/bash
# Check if all required arguments are provided
if [ $# -ne 3 ]; then
echo "Usage: $0 IMAGE_VERSION WORKSPACE REGISTRY_URL"
exit 1
fi
IMAGE_VERSION=$1
WORKSPACE=$2
REGISTRY_URL=$3
# Build the Docker image
docker build -t mindspore_euleros_x86:${IMAGE_VERSION} ${WORKSPACE}
# Tag the built ... | magicoder | shell |
You are tasked with implementing a Python function that processes a set of images using a given neural network model. The provided code snippet is part of a larger script that sets up the input for the neural network and prepares the necessary directories for storing the results.
Your task is to complete the implement... | ```python
import os
def define_img_size(input_size):
# Function to define the image size based on input_size
# Placeholder for actual implementation
return input_size # Placeholder return value
def process_images(input_size, args):
height = input_size[1]
width = input_size[0]
priors = define_... | magicoder | python |
You are tasked with implementing a generic buffer management system in Rust. The `Buffer` struct represents a buffer that holds data of type `T`, and the `Manager` struct is responsible for managing the creation and destruction of buffers. Your goal is to implement the `Buffer` and `Manager` structs along with their as... | ```rust
// Define the Buffer struct
struct Buffer<R, T> {
// Define the buffer data and handle
data: T,
handle: usize,
// Define the associated methods
fn from_raw(handler: &mut Manager<R>, data: T, info: BufferInfo) -> Self {
let handle = handler.make_buffer((), info);
Buffer { data... | magicoder | rust |
You are tasked with implementing a layer normalization function for a neural network. Layer normalization is a technique used to normalize the inputs of each layer in a neural network, which helps in stabilizing the learning process and improving the convergence speed. The given code snippet contains a part of the laye... | ```python
import numpy as np
from functools import reduce
from operator import mul
def layer_norm_grad_ref(gout_full, norm, mean_full, stdev_full, X_full):
left = reduce(mul, X_full.shape[:axis], 1)
right = reduce(mul, X_full.shape[axis:], 1)
X = np.reshape(X_full, [left, right])
stdev = np.reshape(std... | magicoder | python |
You are tasked with implementing a function that takes two strings, `a` and `b`, as input and returns the longest common subsequence (LCS) of the two strings. A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous. For example, "abc", "abg", "bdf", "aeg", "acefg", .. etc are... | ```cpp
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
string longestCommonSubsequence(string a, string b) {
int m = a.length();
int n = b.length();
vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
for (int i = 1; i <= m; i++) {
for (int... | magicoder | cpp |
You are tasked with creating a Python program to automate the process of transferring images from one folder to another. The program should read images from a specified origin folder, process them, and save the processed images to a target folder. Your task is to complete the implementation of the `trans` function, whi... | ```python
import os
import matplotlib.pyplot as plt
origin_fold = r'C:\Users\calvchen\AppData\Roaming\Typora\typora-user-images'
target_fold = r'C:\Users\calvchen\PycharmProjects\chqwer2.github.io\img\Typora'
def trans(origin_loc, target_loc):
try:
if os.path.exists(origin_loc): # Check if the origin loc... | magicoder | python |
You are tasked with implementing a function to expand a given cubic matrix into a higher-dimensional matrix. The expansion is based on the dimensions of the input matrix and follows a specific formula. Your task is to write a function that takes a cubic matrix as input and returns the expanded matrix based on the provi... | ```python
import numpy as np
def expand_cubic(Gc):
r, s = Gc.shape
expanded_dim = r*(r+1)*(r+2)//6
if s != expanded_dim:
raise ValueError("Invalid input dimensions for cubic expansion")
# Perform the expansion based on the provided formula
expanded_matrix = np.zeros((r, r, r))
col_idx ... | magicoder | python |
You are tasked with implementing a class for managing query parameters in a database application. The class, `QueryParams`, is responsible for constructing query parameters for database queries. One of the functionalities of this class is to set an end point for a query result. The `endAt` method is used to specify the... | ```java
public class QueryParams {
private Node endNode;
private String endKey;
// Other methods and constructors
public QueryParams endAt(Node node, String key) {
this.endNode = node;
this.endKey = key;
// Serialize the end point for the query result
String serializedE... | magicoder | java |
You are tasked with creating a Python script to automate the registration of brain MRI images to a template using the ANTs registration toolkit. The script should take input images in NIfTI format, apply a specified transformation, and output the registered images. Additionally, it should use labeled images to guide th... | ```python
import os
import subprocess
BASE_DIR = '/homedtic/gmarti/DATA/Data/'
SCRIPTS_DIR = '/homedtic/gmarti/CODE/upf-nii/scripts'
TEMPLATE = '/homedtic/gmarti/DATA/Hippo_PMaragall/template/template_img.nii.gz'
LABELS_suffix = '_labels.nii.gz'
TEMPLATE_LABEL = '/homedtic/gmarti/DATA/Hippo_PMaragall/template/template... | magicoder | python |
You are tasked with implementing a learning algorithm for a cognitive modeling framework. The framework provides an interface, `CognitiveModuleFactoryLearner`, which defines the functionality of an object that can learn a `CognitiveModuleFactory` from a collection of input data. Your goal is to create a class that impl... | ```java
import gov.sandia.cognition.framework.CognitiveModuleFactory;
import gov.sandia.cognition.framework.CognitiveModelInput;
import gov.sandia.cognition.util.CloneableSerializable;
import java.util.Collection;
/**
* A class that implements the CognitiveModuleFactoryLearner interface to learn a CognitiveModuleFact... | magicoder | java |
You are tasked with implementing a regularization penalty calculation method for a machine learning model. The regularization penalty is calculated using the Kullback-Leibler (KL) divergence between the true distribution and the estimated distribution. The code snippet provided contains a class and a method for this pu... | ```python
import numpy as np
class RegularizationPenalty:
def __init__(self, coeff, p):
self.coeff = coeff
self.p = p
def expr(self, model, data, **kwargs):
"""
Calculate regularization penalty.
"""
X = data
p = self.p
p_hat = np.abs(model.encode... | magicoder | python |
You are tasked with creating a Python class that generates SQL statements based on input data. Your class should have the following methods:
1. `yield_applicant_info`: This method should yield applicant information.
2. `null_source_sql`: This method should take a dictionary `raw` as input and yield SQL statements for... | ```python
import connection # Assuming the database connection module is imported
def values_from_json(raw, schema):
# Assuming this function is defined elsewhere to extract source SQL and source data
pass
class SQLGenerator:
def __init__(self, schema, null_sources):
self.schema = schema
... | magicoder | python |
You are given a 2D array representing a grid of numbers. Each cell in the grid contains a non-negative integer. Your task is to write a function that finds the maximum sum of a path from the top-left cell to the bottom-right cell, moving only right or down.
For example, given the following grid:
```
[
[1, 3, 1],
[... | ```python
from typing import List
def maxPathSum(grid: List[List[int]]) -> int:
rows, cols = len(grid), len(grid[0])
# Initialize the first row
for j in range(1, cols):
grid[0][j] += grid[0][j-1]
# Initialize the first column
for i in range(1, rows):
grid[i][0] += grid[i-1... | magicoder | python |
You are tasked with implementing a generic CLI (Command Line Interface) in Rust for interacting with a data store. The provided code snippet is a partial implementation of the CLI structure and its associated traits and dependencies.
The `Cli` struct has three fields:
1. `glue`: An instance of the `Glue` struct, which... | ```rust
use std::fmt::Debug;
use std::io::Write;
// Define the GStore and GStoreMut traits for interacting with the data store
trait GStore<T> {
// Define methods for reading from the data store
fn read(&self) -> Option<T>;
}
trait GStoreMut<T>: GStore<T> {
// Define methods for writing to the data store
... | magicoder | rust |
You are working on a project that involves processing audio signals in a real-time system. As part of the signal processing, you need to implement a function that applies a filter to the audio data. The filter is represented by an array of coefficients, and the filtering operation involves multiplying the filter coeffi... | ```csharp
unsafe void ApplyFilter(short* inputSamples, double* filterCoefficients, int inputLength, int filterLength, double* outputSamples)
{
for (int i = 0; i < inputLength - filterLength + 1; i++)
{
double sum = 0;
for (int j = 0; j < filterLength; j++)
{
sum += inputSampl... | magicoder | csharp |
You are tasked with creating a custom error handling system for a web application. The application uses TypeScript for server-side code and has a file named `errors.ts` where error messages are defined. Your goal is to implement a class that can handle these errors and provide a standardized way to manage and display t... | ```typescript
// ErrorHandler.ts
import { errors } from './errors';
export class ErrorHandler {
static getError(errorCode: string): Promise<string> {
return new Promise((resolve) => {
setTimeout(() => {
resolve(errors[errorCode] || 'An unknown error occurred');
}, 100);
});
}
}
// Usag... | magicoder | typescript |
You are tasked with implementing a Python class that represents a dataset and provides methods for data manipulation. The dataset can be of two types: "VolumeDataset" and "BlockDataset". Both types of datasets have common methods for adding data, removing data, and getting the size of the dataset. However, each type ha... | ```python
class Dataset:
def __init__(self, dataset_type):
self.dataset_type = dataset_type
self.data = []
def add_data(self, data_point):
self.data.append(data_point)
def remove_data(self, data_point):
if data_point in self.data:
self.data.remove(data_point)
... | magicoder | python |
You are tasked with implementing a message processing system for a chat application. The `listenAppData` method is responsible for receiving and processing incoming messages. Each message is a string containing the message content. Your task is to implement the `listenAppData` method to handle different types of messag... | ```java
public class MessageProcessor {
public void listenAppData(String message) {
if (message.startsWith("MSG:")) {
String actualMessage = message.substring(4);
System.out.println("Received message: " + actualMessage);
} else if (message.startsWith("SYS:")) {
St... | magicoder | java |
You are working on a machine learning library called `simple_ml` that provides various algorithms for classification, regression, and dimensionality reduction. The code snippet provided includes imports for different modules within the `simple_ml` library. Your task is to create a function that dynamically loads and ex... | ```python
def run_ml_algorithm(algorithm_name, data):
try:
algorithm_module = __import__('simple_ml.' + algorithm_name, fromlist=[algorithm_name])
algorithm_class = getattr(algorithm_module, algorithm_name.capitalize())
algorithm_instance = algorithm_class()
result = algorithm_instan... | magicoder | python |
You are tasked with implementing a function that performs string expansion based on a given context and key-value pairs. The function takes in an input string `expanded`, a context object `context`, and a default value `default`. The input string `expanded` contains placeholders in the form of `${group.key}` that need ... | ```python
class Context:
def __init__(self, Descriptor, params):
self.Descriptor = Descriptor
self.params = params
class Descriptor:
def __init__(self, Parameters):
self.Parameters = Parameters
def string_expansion(expanded: str, context: Context, default: str) -> str:
for match in... | magicoder | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.