query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with implementing a function that extracts the hostname from a given payload string. The payload contains a command followed by a hostname, separated by a space. The function should extract the hostname and return it as a string. However, there is a bug in the provided code snippet that needs to be fixed... | To fix the bug in the provided code snippet, the second while loop should be modified to correctly skip any leading spaces in the payload before extracting the hostname. The corrected code snippet is as follows:
```c
int cnt = 0;
char *pTmp = payload;
char *pSet = fWord;
/* skip first command word till encounter a blan... | magicoder | c |
You are given a string representing a snippet of C++ code. The snippet contains a series of closing curly braces (`}`) that are not aligned properly. Your task is to write a function that determines the minimum number of spaces needed to align each closing curly brace with its corresponding opening curly brace.
You ne... | ```cpp
#include <vector>
#include <string>
std::vector<int> alignCurlyBraces(const std::string& codeSnippet) {
std::vector<int> alignment;
int currentIndent = 0;
for (char c : codeSnippet) {
if (c == '{') {
alignment.push_back(currentIndent);
currentIndent += 4; // Assuming... | magicoder | cpp |
You are tasked with implementing a class that manages a collection of game items. The class should provide methods to update the quantity of game items and to remove a game item from the collection based on its name. You are given a code snippet that partially implements this functionality. Your task is to complete the... | ```java
import java.util.ArrayList;
import java.util.List;
class Game {
private String name;
private double price;
private int quantity;
private String company;
public Game(String name, double price, int quantity, String company) {
this.name = name;
this.price = price;
this... | magicoder | java |
You are tasked with implementing a tree parser for an API endpoint structure. The `TreeAPIParser` class is provided as a starting point, which inherits from `BaseAPIParser`. The goal is to complete the implementation of the `parse_tree` method to populate the `endpoints_tree` with the API endpoint structure.
The `Base... | ```python
from collections import defaultdict
class TreeAPIParser(BaseAPIParser):
"""
Creates a nice tree of API
"""
def __init__(self, *args, **kwargs):
self.endpoints_tree = defaultdict(dict)
super().__init__(*args, **kwargs)
def parse(self):
self.parse_tree(self.patterns... | magicoder | python |
You are tasked with implementing a Rust program that utilizes various experimental features. The provided code snippet includes a list of feature flags that enable experimental language features in Rust. Your goal is to create a program that demonstrates the use of at least three of these features in a meaningful way.
... | ```rust
#![feature(const_intrinsic_copy)]
#![feature(const_float_classify)]
#![feature(const_float_bits_conv)]
#![feature(const_fn_floating_point_arithmetic)]
// Define a struct using const_intrinsic_copy feature
#[derive(Debug, Copy, Clone)]
struct MyStruct {
value: u32,
}
// Implement a function that utilizes c... | magicoder | rust |
You are tasked with implementing a simple off-heap array data structure in Java. The off-heap array should be capable of storing elements of any data type. The off-heap array should utilize a direct byte buffer for memory management and should support operations for adding elements, accessing elements by index, and res... | ```java
import java.nio.ByteBuffer;
/**
* Simple off-heap array.
*/
public class SimpleOffHeapArray<T> extends AbstractOffHeapArray<T> {
private static final int LENGTH_SIZE = 4;
private int capacity = -1;
private DirectByteBuffer byteBuffer;
public SimpleOffHeapArray(int initialCapacity) {
... | magicoder | java |
You are given a function that takes a string as input and is supposed to return a list of valid substrings that are words. However, the function is incomplete and lacks the necessary logic to identify valid words within the input string. Your task is to complete the function by implementing the logic to identify valid ... | ```python
from typing import List
def find_valid_substrings(string: str, dictionary: List[str]) -> List[str]:
found = set()
for start in range(len(string)):
for end in range(start + 1, len(string) + 1):
substring = string[start:end]
if substring in dictionary:
fo... | magicoder | python |
You are tasked with implementing a function to parse and extract information from Rust documentation comments. Rust documentation comments are denoted by `///` or `//!` and are used to generate documentation for the code. These comments can contain various attributes and descriptions for the associated code elements.
... | ```rust
fn parse_documentation_comment(comment: &str) -> (Vec<String>, String) {
let mut attributes = Vec::new();
let mut description = String::new();
for line in comment.lines() {
if line.trim_start().starts_with("///") {
let content = line.trim_start_matches("///").trim();
... | magicoder | rust |
You are tasked with creating a Python program that processes Unicode character ranges and prints out the corresponding glyph names. The `glyphNameFormatter` library provides a function `printRange(category)` that takes a Unicode category as input and prints the glyph names for the characters within that category. Your ... | ```python
from glyphNameFormatter.exporters import printRange
# Call the printRange function with the "Alphabetic Presentation Forms" category
printRange("Alphabetic Presentation Forms")
```
When executed, this program will import the `printRange` function from the `glyphNameFormatter` library and then call the funct... | magicoder | python |
You are tasked with creating a Python function that can alter a database table by adding a new column with a specified data type. The function should be able to handle different database management systems (DBMS) such as MySQL and SQLite. The function should take the following parameters:
- `db_connection`: A connectio... | ```python
def add_column_to_table(db_connection, table_name, column_name, data_type):
db_type = db_connection.TYPE # Assuming the database connection object has a property 'TYPE' indicating the type of DBMS
if db_type == "mysql":
data_type = data_type.upper() # Convert data type to uppercase for MySQ... | magicoder | python |
You are tasked with creating a Python function to process and save simulation data from VTK files into an HDF5 format. The VTK files contain simulation results for different cases, each with specific physical and simulation properties. Your function should read the VTK files, extract the relevant data, and save it into... | ```python
import h5py
from utils import read_vtk
import os
def process_and_save_vtk_data(vtk_path: str, case_number: int, save_path: str) -> None:
case_folder = os.path.join(vtk_path, f'case/{case_number}')
# Read physical properties, step, and spatial step
physical_properties = read_vtk(os.path.join(... | magicoder | python |
You are given a Python dictionary containing key-value pairs representing different types of connectors and their corresponding quantities in a hardware store. The keys are the connector types, and the values are the quantities available. However, the dictionary is incomplete and contains only a subset of the available... | ```python
def complete_connector_inventory(inventory):
completed_inventory = inventory.copy()
for key, value in inventory.items():
completed_inventory[key] = value
completed_inventory[key[::-1]] = hex(value)[2:].upper()
completed_inventory[key + key] = value + 10
return completed_inv... | magicoder | python |
You are tasked with implementing a custom JSON deserialization method in C#. The method should take a JSON token, a property name, and a parameter type, and return the deserialized value of the specified property as an object of the given parameter type. The deserialization should follow specific settings, including th... | ```csharp
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
public class UnixDateTimeConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(DateTime) || objectType == typeof(DateTime?);
}
pu... | magicoder | csharp |
You are tasked with creating a simple in-memory cache system in JavaScript. Your cache should support basic operations such as setting a key-value pair, getting the value for a given key, and deleting a key from the cache. Additionally, the cache should have a maximum capacity, and when the capacity is reached, the lea... | ```javascript
class Node {
constructor(key, value) {
this.key = key;
this.value = value;
this.prev = null;
this.next = null;
}
}
class InMemoryCache {
constructor(capacity) {
this.capacity = capacity;
this.cache = new Map();
this.head = new Node();
this.tail = new Node();
this... | magicoder | javascript |
You are tasked with optimizing the `read_jpegs` function to efficiently read and process JPEG images from a specified folder using NVIDIA DALI library. The function should read the images, perform some basic preprocessing, and return the processed images as a NumPy array.
The `read_jpegs` function should take the foll... | ```python
import nvidia.dali.ops as ops
import nvidia.dali.types as types
import numpy as np
from timeit import default_timer as timer
import os
image_folder = "/data/dali/benchmark/benchmark_images"
def read_jpegs(folder):
pipe = ops.FileReader(file_root=folder, random_shuffle=True)
pipe = pipe.gpu(num_gpus=... | magicoder | python |
You are tasked with creating a Python class that dynamically modifies the behavior of another class. Your goal is to implement a metaclass that will allow the user to specify a list of editable fields for a given model class. The metaclass should then modify the behavior of the model class to only allow editing of the ... | ```python
class EditableMeta(type):
def __new__(cls, name, bases, dct):
if 'Meta' in dct:
editable_fields = getattr(dct['Meta'], 'list_editable', [])
dct['editable_fields'] = editable_fields
return super().__new__(cls, name, bases, dct)
class EditableModel(metaclass=Editable... | magicoder | python |
You are tasked with creating a Python function that processes a JSON file and updates its structure based on a set of rules. The function should take in the file name as a parameter and modify the JSON file in place. The JSON file contains a dictionary with keys 'data', 'metadata', and 'properties'. The function should... | ```python
import os
import json
def process_json_file(filename):
with open(filename, 'r') as file:
data = json.load(file)
if 'data' in data:
if 'metadata' in data:
data['metadata']['data'] = data.pop('data')
else:
data['metadata'] = {'data': d... | magicoder | python |
You are tasked with creating a Python logging utility that provides different log levels and a directory creation function. The provided code snippet includes three functions: `log(log_data)`, `logError(error_data)`, and `makedir(dir2make)`.
Your task is to extend this logging utility by adding a new function called `... | ```python
import os
def log(log_data):
print("\033[m" + log_data)
def logError(error_data):
print("\033[0;32;31m" + error_data)
def logWarning(warning_data):
print("\033[0;33m" + warning_data)
def makedir(dir2make):
if not os.path.exists(dir2make):
os.makedirs(dir2make)
log("Director... | magicoder | python |
You are tasked with implementing a doubly linked list in Java. A doubly linked list is a data structure that consists of a sequence of elements, where each element has a reference to the previous and next elements in the sequence. Your task is to create a Java class `DoublyLinkedList` that supports the following operat... | ```java
package com.jimmyyouhei.doubly_linked_list;
class Node {
int data;
Node prev;
Node next;
public Node(int data) {
this.data = data;
this.prev = null;
this.next = null;
}
}
public class DoublyLinkedList {
private Node head;
private Node tail;
public Doub... | magicoder | java |
You are tasked with creating a program that extracts the text content within HTML tags from a given input string. The input string will contain HTML code with various tags, and your program should identify and extract the text content within these tags.
Write a function `extractHTMLText` that takes a string `htmlCode`... | ```python
from typing import List
import re
def extractHTMLText(htmlCode: str) -> List[str]:
# Regular expression to match text content within HTML tags
pattern = r">([^<]+)<"
matches = re.findall(pattern, htmlCode)
return matches
```
The `extractHTMLText` function uses the `re.findall` method to sear... | magicoder | python |
You are tasked with implementing a Python class that encodes and decodes rows of data based on a given schema. The schema is represented using the `apache_beam.portability.api.schema_pb2.Schema` protobuf. The `RowCoder` class has a method `_create_impl` that returns an instance of `RowCoderImpl` which is responsible fo... | ```python
class RowCoder:
def __init__(self, schema):
"""
Args:
schema (apache_beam.portability.api.schema_pb2.Schema): The protobuf
representation of the schema of the data that the RowCoder will be used
to encode/decode.
"""
self.schema = schema
... | magicoder | python |
You are tasked with implementing a custom concurrent operation in Swift. The operation should have the ability to perform a task asynchronously and then mark itself as finished once the task is completed. You need to create a subclass of `Operation` and override the necessary methods to achieve this behavior.
Your tas... | ```swift
import Foundation
class CustomOperation: Operation {
private var isExecuting: Bool = false
private var isFinished: Bool = false
override var isAsynchronous: Bool {
return true
}
override var isExecuting: Bool {
return isExecuting
}
override var isFinished: Bool {... | magicoder | swift |
You are tasked with creating a custom annotation in Java to mark classes with a default implementation. The annotation should allow developers to specify a default implementation for a particular interface.
Create a Java annotation called `@Port` with a single element `defaultImplementation` of type `String` that repr... | ```java
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Port {
String defaultImplementation() default "";
}
// Example in... | magicoder | java |
You are tasked with simulating a simplified version of a card game using Python classes. The game involves a dealer and a player, and the goal is to create a program that can manage the game's flow.
You are provided with two Python classes: `Dealer` and `Player`. The `Dealer` class has methods for shuffling the deck, ... | ```python
from random import shuffle
class Dealer:
def __init__(self):
self.deck = []
self.suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
self.ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace']
def shuffle_deck(self):
self.deck = [(rank, s... | magicoder | python |
You are tasked with implementing a custom exception handling mechanism for a web service client. The client makes HTTP requests and expects JSON responses, which need to be deserialized into objects. However, there are potential issues with deserialization, such as invalid JSON or incompatible data types. Your goal is ... | ```csharp
using System;
public class DeserializationException : Exception
{
public string ResponseContent { get; }
public DeserializationException(string message, string responseContent, Exception innerException)
: base(message, innerException)
{
ResponseContent = responseContent;
}
}
... | magicoder | csharp |
You are tasked with creating a PHP function that processes a list of student objects and their associated grades. The function should calculate the total count of students and modify each student object to include the name of their associated grade. The student objects are represented as an array of associative arrays,... | ```php
function processStudentData(array $students, array $grades): array {
$count = count($students); // Calculate the total count of students
// Modify each student array to include the 'grade' key with the name of the associated grade
foreach ($students as &$student) {
$gradeId = $student['grade... | magicoder | php |
You are tasked with implementing a Python class that provides ANSI color codes for text output in a terminal. The class should have methods to format text with different colors and styles. The ANSI color codes for text formatting can be found at https://stackoverflow.com/questions/287871/how-to-print-colored-text-in-te... | ```python
class colors:
# ANSI color codes
RED = '\033[91m'
GREEN = '\033[92m'
BLUE = '\033[94m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
END = '\033[0m'
def red(self, text):
return self.RED + text + self.END
def green(self, text):
return self.GREEN + text + self.END
... | magicoder | python |
You are tasked with creating a Python script to automate the process of opening a specific website in Google Chrome and extracting specific information from the webpage. To achieve this, you will need to use the `pywinauto` library, which provides a set of consistent functions for automating the GUI operations on Windo... | ```python
from pywinauto import Application
import time
# Initialize the application
app = Application(backend='uia')
# Start Google Chrome
app.start('C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe --force-renderer-accessibility ')
# Wait for Chrome to open
time.sleep(2)
# Connect to the top window
wind... | magicoder | python |
You are tasked with creating a program that simulates a simple banking system. The program should allow users to create accounts, deposit and withdraw funds, and check their balance. Each account should have a unique account number, and the program should support multiple accounts. The program should also be able to ha... | ```python
from typing import Union
class BankingSystem:
def __init__(self):
self.accounts = {}
def create_account(self, name: str, initial_balance: float) -> int:
if initial_balance < 0:
raise ValueError("Initial balance cannot be negative")
account_number = len(self.accoun... | magicoder | python |
You are given a list of integers representing the heights of a 2D mesh. The mesh is represented as a 2D grid where each cell contains the height value. You need to find the total amount of water that can be trapped within the mesh. Water can only be trapped if it forms a basin between higher terrain.
For example, give... | ```python
from typing import List
def trapped_water(mesh: List[List[int]]) -> int:
rows, cols = len(mesh), len(mesh[0])
total_water = 0
for i in range(1, rows - 1):
for j in range(1, cols - 1):
left_max = max(mesh[i][:j])
right_max = max(mesh[i][j+1:])
top_max =... | magicoder | python |
You are tasked with implementing a multithreaded program to process a list of tasks concurrently. Each task is represented by a function that takes no arguments and returns a result. Your goal is to design a solution that efficiently utilizes multiple threads to execute these tasks in parallel.
You are given a list of... | ```python
import threading
def execute_tasks(tasks: List[Callable[[], Any]], num_threads: int) -> List[Any]:
results = [None] * len(tasks)
task_index = 0
lock = threading.Lock()
def execute_task(task_index):
nonlocal results
while task_index < len(tasks):
task = tasks[task_... | magicoder | python |
You are tasked with implementing a function to calculate the area of a polygon given its vertices. The vertices are represented as (x, y) coordinates in a two-dimensional plane. The polygon is assumed to be non-self-intersecting and the vertices are given in clockwise or counterclockwise order.
Write a function `calcu... | ```python
def calculatePolygonArea(vertices):
area = 0
n = len(vertices)
for i in range(n):
x1, y1 = vertices[i]
x2, y2 = vertices[(i + 1) % n]
area += (x1 * y2 - x2 * y1)
return abs(area) / 2
```
The `calculatePolygonArea` function iterates through each pair of adjacent vertic... | magicoder | python |
You are tasked with creating a Python package that includes a custom C extension module. Your goal is to write a setup script that compiles the C extension module during the package installation process. To achieve this, you need to define the necessary setup configuration and ensure that the C extension module is buil... | ```python
import os
import pathlib
from setuptools import setup, Extension, find_packages
from setuptools.command.build_ext import build_ext as build_ext_orig
# Define the custom extension module
custom_extension = Extension(
'package_name.custom_extension', # Replace 'package_name' with the actual package name
... | magicoder | python |
You are tasked with creating a function that processes the response from an Alamofire request and extracts specific data from it. The Alamofire request is made to a URL, and the response is in JSON format. Your function should parse the JSON response and extract specific information based on the given requirements.
Yo... | ```swift
func processResponse(response: DataResponse<Any>) -> (Int, String?) {
var statusCode = 0
var extractedData: String? = nil
switch response.result {
case .Success:
if let httpResponse = response.response {
statusCode = httpResponse.statusCode
}
if... | magicoder | swift |
You are given a list of integers representing the scores of a game. Your task is to write a function that calculates the average score of the game, excluding the highest and lowest scores.
Write a function `calculateAverageScore(scores)` that takes in a list of integers `scores` (2 <= len(scores) <= 100) and returns t... | ```python
def calculateAverageScore(scores):
if len(scores) < 4:
return "Not enough scores to calculate average"
scores.sort()
trimmed_scores = scores[1:-1] # Exclude the highest and lowest scores
average_score = round(sum(trimmed_scores) / len(trimmed_scores))
return average_score
```... | magicoder | python |
You are tasked with implementing a class hierarchy for different types of acceleration structures used in a scene description for a computer graphics application. The goal is to create a unified method for constructing acceleration structures from given parameters, ensuring flexibility and ease of use.
Your task is to... | ```java
// Define the enum for different types of acceleration structures
enum AccelerationStructureType {
BVH, // Bounding Volume Hierarchy
KD_TREE, // K-Dimensional Tree
GRID, // Grid-based acceleration structure
// Add more types as needed
}
// Create an abstract class for acceleration structures
ab... | magicoder | java |
You are tasked with implementing a feature extraction system for a real-time data processing application. The system will process incoming data streams and extract various features from the data. The features will be used for further analysis and decision-making. The code snippet provided includes some of the necessary... | ```cpp
#include <iostream>
#include <map>
#include <cmath>
class ExponentialHistogram {
private:
std::map<int, int> bins; // Map to store bin index and frequency
public:
void addValue(double value) {
int binIndex = static_cast<int>(log2(value)); // Calculate the bin index using logarithm
bin... | magicoder | cpp |
You are tasked with implementing a priority queue data structure in Rust. A priority queue is a data structure that maintains a set of elements, each associated with a priority. In this problem, you are required to implement the `PriorityQueue` data structure and its associated methods.
The `PriorityQueue` should supp... | ```rust
use std::cmp::Ordering;
use std::collections::BinaryHeap;
struct PriorityQueue<T, P> {
heap: BinaryHeap<(P, T)>,
}
impl<T, P: Ord> PriorityQueue<T, P> {
fn new() -> Self {
PriorityQueue { heap: BinaryHeap::new() }
}
fn put(&mut self, item: T, priority: P) {
self.heap.push((pri... | magicoder | rust |
You are given a list of strings representing fractions in the format "numerator/denominator". Your task is to write a function that sorts these fractions in ascending order based on their decimal values.
Create a function `sortFractions(fractions)` where:
- `fractions` is a list of strings representing fractions (e.g.... | ```python
def sortFractions(fractions):
def fraction_key(fraction):
numerator, denominator = map(int, fraction.split('/'))
return numerator / denominator # Decimal value of the fraction
sorted_fractions = sorted(fractions, key=fraction_key)
return sorted_fractions
```
The `sortFractions` ... | magicoder | python |
You are tasked with implementing a custom file indexing system in Python. The code snippet provided defines the `FileMetasource` and `Index` classes. The `FileMetasource` class is responsible for extracting metadata from files, while the `Index` class is used to create and manage an index of files based on their metada... | ```python
import os
class FileMetasource:
def extract_metadata(self, file_path):
metadata = {}
if os.path.isfile(file_path):
file_stat = os.stat(file_path)
metadata['file_name'] = os.path.basename(file_path)
metadata['file_size'] = file_stat.st_size
m... | magicoder | python |
You are tasked with implementing a Python class to manage sharding specifications for a distributed computing system. The class, `ShardingSpec`, is responsible for defining how data is partitioned and distributed across devices in a cluster environment. The sharding is defined by tile dimensions, tile assignments, and ... | ```python
class ShardingSpec:
def __init__(self, tile_dimensions, shard_dimensions, replicate_dimensions, cluster_env):
self.tile_assignment_dimensions = None
self.tile_assignment_devices = None
self.replicate_on_last_tile_dim = None
self.tile(tile_dimensions, shard_dimensions, repli... | magicoder | python |
You are tasked with implementing a trait data buffering system for a game using Unity and C#. The system should allow for efficient buffering and retrieval of trait data for game entities.
A trait is a specific characteristic or attribute that an entity in the game can possess, such as strength, agility, or intellige... | ```csharp
using System.Collections;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.TestTools;
public class TraitDataBuffering
{
private readonly Dictionary<string, Dictionary<string, object>> traitDataBuffer;
public TraitDataBuffering()
{
traitDataBuffer = new Dictionary<string, Dicti... | magicoder | csharp |
You are given a list of strings, where each string represents answers to a set of questions. Each line in the list corresponds to a person's answers, and an empty line separates different groups of people. Your task is to calculate the sum of the counts of unique answers for each group.
For each group, the unique answ... | ```python
from typing import List
def calculate_unique_answers(lines: List[str]) -> int:
total_unique_answers = 0
group_answers = set()
for line in lines:
if line == "\n":
total_unique_answers += len(group_answers)
group_answers = set()
else:
for ans... | magicoder | python |
You are tasked with implementing a Java program that simulates a simple asynchronous communication system between nodes. The program should include classes for asynchronous input and output streams, as well as a class representing a node to send data to. Your task is to create the necessary classes and methods to achie... | ```java
// AsyncInputStream class for handling asynchronous input operations
class AsyncInputStream {
// Implement necessary data structures and methods for asynchronous input handling
}
// AsyncOutputStream class for handling asynchronous output operations
class AsyncOutputStream {
// Implement necessary data... | magicoder | java |
You are tasked with implementing a connection pooling mechanism for a Java application. Connection pooling is a technique used to manage and reuse a collection of database connections, thus improving performance and scalability. Your goal is to create a class that implements the `PooledConnection` interface and manages... | ```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class DatabaseConnectionPool implements PooledConnection {
private List<Connection> connectionPool = new ArrayList<>();
private List<ConnectionEventListener... | magicoder | java |
You are tasked with creating a Python function that parses a given configuration dictionary and returns a formatted string representing the configuration settings. The configuration dictionary contains nested key-value pairs representing different configuration settings for a logging system. Each setting may have sub-s... | ```python
def parse_configuration(config: dict, indent: int = 0) -> str:
result = ""
for key, value in config.items():
result += f"{' ' * indent}- {key}:\n" if indent > 0 else f"{key}:\n"
if isinstance(value, dict):
result += parse_configuration(value, indent + 2)
else:
... | magicoder | python |
You are tasked with creating a Python class that interacts with a REST API using the requests library. Your task is to implement a method that retrieves information from a specific endpoint of the API. The class `RestApiService` has been provided with an `about` method that constructs the URL for the endpoint "/about" ... | ```python
import requests
from requests.auth import HTTPBasicAuth
class RestApiService:
def __init__(self, connection):
self.conn = connection
def about(self):
endpoint = "/about"
url_format = f"{self.conn.get('homePageUrl')}{endpoint}"
response = requests.get(url_format, auth=... | magicoder | python |
You are tasked with implementing a custom XML serializer for a simplified version of a car rental system. The system has a class `Car` with the following attributes: `make`, `model`, `year`, and `price`. Your task is to create a custom XML serializer to convert instances of the `Car` class into XML format and vice vers... | ```cpp
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/logging/LogMacros.h>
#include <iostream>
#include <utility>
using namespace Aws::RDS::Model;
using namespace Aws::Utils::Xml;
using namespace Aws::Utils::L... | magicoder | cpp |
You are tasked with creating a script to automate the installation of packages on an Ubuntu Server 16.04 LTS - 64. The script should present a menu using the `dialog` utility, allowing the user to select from a list of options. Upon selection, the script should execute the corresponding installation or update command. ... | ```bash
#!/bin/bash
# Display the menu using dialog
servico=$(dialog --stdout --backtitle 'Instalação de pacotes no Ubuntu Server 16.04 LTS - 64' \
--menu 'Selecione a opção com a seta ou o número e tecle Enter\n' 0 0 0 \
1 'Atualizar repositórios' \
2 'Instalar LAMP e o... | magicoder | shell |
You are tasked with creating a program that will process a given input string and apply a specific type of character substitution to it. The program should replace certain characters in the input string with their corresponding escape sequences, as specified in a provided mapping.
Your task is to implement a Python fu... | ```python
def apply_escape_sequences(input_string: str, escape_mapping: dict) -> str:
modified_string = input_string
for char, escape_sequence in escape_mapping.items():
modified_string = modified_string.replace(char, escape_sequence)
return modified_string
# Test the function
input_string = "This ... | magicoder | python |
You are tasked with creating a script to manage the startup of a server application. The script should determine the appropriate executable to run based on the system architecture, enable job control, start the server in the background, and allow it a brief period to initialize.
Your script should perform the followin... | ```bash
#!/bin/bash
ARCH="x86_64" # Example system architecture
if [ "$ARCH" = "x86_64" ]; then
EXECUTABLE='bin/server64';
else
EXECUTABLE='bin/server32';
fi
# Enable job control.
set -m
# Start up the server.
"$EXECUTABLE" &
# Give it a second to start up.
sleep 1
```
The script first sets the `EXECUTAB... | magicoder | shell |
You are tasked with simulating the behavior of a simple GPIO (General Purpose Input/Output) interface for a Raspberry Pi. The provided code snippet is a part of a Python script that interfaces with GPIO pins to control an external device. The script uses the RPi.GPIO library to interact with the GPIO pins. The `setup()... | ```python
import time
class GPIOSimulator:
def __init__(self):
self.debug_logging = False
self.pwm_running = False
self.gpio_state = {}
def set_debug_logging(self, enable):
self.debug_logging = enable
def setup(self):
if self.debug_logging:
print('Simul... | magicoder | python |
You are tasked with creating a program that processes images to identify and count the number of distinct objects present in the image. The program should utilize various image processing libraries and techniques to achieve this.
Your task is to implement a Python function `count_distinct_objects(image_path)` that tak... | ```python
from PIL import Image
from skimage import measure
import numpy as np
import cv2
def count_distinct_objects(image_path):
# Open the input image using PIL
image = Image.open(image_path)
# Convert the image to grayscale
grayscale_image = image.convert('L')
# Convert the grayscale image to ... | magicoder | python |
You are tasked with implementing a class that performs statistical calculations on a set of data. The class should have the following functionalities:
1. `add(key, value)`: A method that adds a new data point to the statistics. The `key` represents the category of the data point, and the `value` is the numerical value... | ```python
class Statistics:
def __init__(self):
self.count = {}
self.sum = {}
self.sum_square = {}
def add(self, key, value):
self.count[key] = self.count.get(key, 0) + 1
self.sum[key] = self.sum.get(key, 0.0) + value
self.sum_square[key] = self.sum_square.get(ke... | magicoder | python |
You are working on a natural language processing (NLP) project and need to implement a custom recurrent neural network (RNN) module for sequence processing. Your task is to create a Python class that includes methods for processing input sequences using an RNN and returning the hidden states of the RNN. The RNN should ... | ```python
import torch
class CustomRNN(torch.nn.Module):
def __init__(self, input_size, hidden_size, batch_first, only_use_last_hidden_state):
super(CustomRNN, self).__init__()
self.batch_first = batch_first
self.only_use_last_hidden_state = only_use_last_hidden_state
self.embedding... | magicoder | python |
You are given the following Python code snippet for a binary tree traversal algorithm:
```python
# self.right = right
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
l=[]
ans=[]
a=root
while True:
if not(a or l):
break
... | ```python
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
result = []
stack = []
current = root
while current or stack:
while current:
stack.append(current)
current = current.left
c... | magicoder | python |
You are tasked with creating a Java program to handle logging for an email sending application. The program should utilize the built-in Java logging framework to log any exceptions that occur during the email sending process. Your task is to implement the necessary code to achieve this functionality.
Your program shou... | ```java
import java.util.logging.Level;
import java.util.logging.Logger;
public class EmailSender {
private static final Logger logger = Logger.getLogger(EmailSender.class.getName());
public void sendEmail(String recipient, String message) {
try {
// Code to send the email
// .... | magicoder | java |
You are working on a data visualization project using the Streamlit library in Python. Your task is to create a program that allows users to select columns from a dataset and visualize them using line plots, area plots, and bar plots.
You have a dataset `x_train` containing various columns, and you want to provide an ... | ```python
import streamlit as st
# Assuming x_train is the dataset containing the data to be visualized
# num_cols is a list of column names in the dataset
# Display a title "Line plots"
st.title('Line plots')
# Allow users to select a column for plotting a line chart
col_line = st.selectbox('Columns for plotting li... | magicoder | python |
You are tasked with creating a class that represents a game board for a two-player game. The game board is a grid of cells, and the players take turns placing their pieces in empty cells. The goal of the game is for a player to achieve a certain number of their pieces in a row, either vertically, horizontally, or diago... | ```csharp
public class GameBoard
{
public int MinToWinVertically { get; set; }
public int MinToWinDiagonally { get; set; }
private int[,] board; // Assume this is the game board represented as a 2D array
public bool HasPlayerWon(int player)
{
// Check for vertical win
for (int col =... | magicoder | csharp |
You are tasked with implementing a JWT (JSON Web Token) service in C# to generate JWT tokens for user authentication. The JWT token should be generated using the HMAC SHA256 algorithm with a provided secret key. Your task is to complete the implementation of the `JwtService` class that implements the `IJwtService` inte... | ```csharp
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.IdentityModel.Tokens;
public class JwtService : IJwtService
{
public string GenerateJwtToken(string userId, string secret)
{
var key = new SymmetricSecurityKey(Encoding.UTF8.G... | magicoder | csharp |
You are tasked with creating a Python class that simulates a simple weather service. The class should be able to provide weather information and display corresponding emojis based on the weather conditions.
Create a Python class called `WeatherService` with the following specifications:
- The class should have a const... | ```python
class WeatherService:
def __init__(self):
self.weather_data = []
def add_weather_data(self, date, weather_code, temperature):
self.weather_data.append({'date': date, 'weather_code': weather_code, 'temperature': temperature})
def get_weather_data(self):
return self.weather... | magicoder | python |
You are tasked with implementing a message handling system for a communication protocol. The system receives messages as a stream of bytes and needs to determine if a complete message has been received. A complete message is denoted by the presence of a specific byte value, '\x04', which marks the end of the message. Y... | ```python
def is_complete(self):
eom_idx = self.get_eom_idx()
if not eom_idx:
return False
received = self.message.keys()
return all(idx < eom_idx for idx in received)
```
The `is_complete` method first retrieves the index of the end-of-message byte using the `get_eom_idx... | magicoder | python |
You are working on a project that involves processing astronomical data. Your task is to write a Python function that performs a specific transformation on a set of AstroData inputs. Each AstroData input is a collection of extensions, and the function should handle cases where the inputs have a different number of exte... | ```python
from typing import List
from astrodata import AstroData
from astropy.wcs import WCS
from astropy.modeling.models import Pix2Sky
from astropy.modeling import Transform
import logging
def perform_transformation(adinputs: List[AstroData]) -> List[AstroData]:
# Check if there are any inputs
if not adinpu... | magicoder | python |
You are tasked with implementing a function that simulates a simplified version control system. The function should be able to handle the creation of branches and the checkout of existing branches. The code snippet provided is a part of the implementation of the `git` module for this version control system. The `tsrc.g... | ```python
import subprocess
class VersionControl:
def __init__(self, clone_path: str):
self.clone_path = clone_path
def create_branch(self, branch_name: str):
subprocess.run(["git", "checkout", "-b", branch_name], cwd=self.clone_path)
def checkout_branch(self, branch_name: str):
s... | magicoder | python |
You are tasked with creating a Python function that handles database errors using the SQLAlchemy library. Your function should retrieve the MCC (Merchant Category Code) category for a given code. However, if an error occurs during the retrieval process, it should log the error and raise a custom DatabaseError with a sp... | ```python
from sqlalchemy.exc import SQLAlchemyError
class DatabaseError(Exception):
pass
def retrieve_mcc_category(mcc_code: str) -> str:
try:
# Your SQLAlchemy code to retrieve MCC category for the given mcc_code
# Example: mcc_category = session.query(MCCTable).filter_by(code=mcc_code).firs... | magicoder | python |
You are tasked with creating a Python class to manage publishing messages to a Kafka broker. The class should handle the configuration, connection, and publishing of messages to the broker. Your task is to implement the `KafkaBrokerPublisher` class with the necessary methods to achieve this functionality.
The `KafkaBr... | ```python
from typing import Any
from contextlib import asynccontextmanager
class BrokerMessageV1:
def __init__(self, key: str, payload: Any):
self.key = key
self.payload = payload
class BrokerMessageV1Payload:
def __init__(self, value: str):
self.value = value
class KafkaBrokerPublis... | magicoder | python |
You are working on a network communication module for a system that communicates with a remote server using a custom binary protocol. The server sends responses in the form of byte arrays, and you need to implement a method to parse and interpret these responses.
The server response consists of two parts:
1. The first... | ```python
def parseResponse(self, body_buf: bytes) -> (List[int], str):
hex_bytes = body_buf.split(b' ')[0]
decimal_numbers = body_buf.split(b' ')[1]
hex_string = ''.join([chr(int(byte, 16)) for byte in hex_bytes.split(b' ')])
decimal_list = [int(num) for num in decimal_numbers.split(b' ')]
return... | magicoder | python |
You are tasked with creating a program that simulates a memory allocation and deallocation process. The program should implement a custom memory management system using a linked list data structure to keep track of allocated and deallocated memory blocks.
Your task is to implement a C++ program that manages memory all... | ```cpp
#include <iostream>
#include <cstdlib>
struct MemoryBlock {
void* address;
size_t size;
bool allocated;
MemoryBlock* next;
};
class MemoryManager {
private:
MemoryBlock* head;
public:
MemoryManager() : head(nullptr) {}
void* allocate(size_t size) {
MemoryBlock* current = h... | magicoder | cpp |
You are tasked with implementing a function that processes a stream of bytes and extracts unsigned integer values from it. The function should read 5 bytes at a time and convert them into unsigned integers. The extracted integers should be stored in a list and returned as the final result.
The function signature is as... | ```python
from typing import List
class Stream:
def __init__(self, data: List[int]):
self.data = data
self.index = 0
def read(self, n: int) -> 'Stream':
if self.index + n > len(self.data):
raise ValueError("Not enough bytes to read")
result = Stream(self.data[self.i... | magicoder | python |
You are tasked with implementing a generic conversion method for a custom `Number` class in C#. The `Number` class represents a numerical value and needs to support conversion to various data types. Your task is to complete the implementation of the `ConvertTo<T>` method and the accompanying `ConvertTo` method, which w... | ```csharp
using System;
public class Number
{
private readonly double value;
public Number(double value)
{
this.value = value;
}
public T ConvertTo<T>()
{
return (T)ConvertTo(typeof(T));
}
public object ConvertTo(Type convertToType)
{
if (convertToType == ... | magicoder | csharp |
You are tasked with creating a Python program that acts as a simple echo client. An echo client is a program that sends a message to a server and receives the same message back. Your program should establish a connection to a specified server and port, send a message, and then receive and display the echoed message.
Y... | ```python
import socket
def main():
server_ip = input("Enter the server's IP address: ")
server_port = int(input("Enter the server's port number: "))
try:
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((server_ip, server_port))
except socket.err... | magicoder | python |
You are tasked with creating a Python function that parses a Django migration file and extracts the version number and timestamp of the migration. The migration file is generated by Django and contains a specific comment line indicating the version and timestamp. Your function should take the file path as input and ret... | ```python
import re
def parse_migration_file(file_path):
with open(file_path, 'r') as file:
content = file.read()
match = re.search(r'# Generated by Django (\d+\.\d+\.\d+) on (\d{4}-\d{2}-\d{2} \d{2}:\d{2})', content)
if match:
version = match.group(1)
timestamp = ma... | magicoder | python |
You are tasked with creating a service registration system for a dependency injection container. The system should allow users to register and configure services using a fluent interface. Each service can be associated with a specific Rector class and configured with a set of Rector services. The user should also be ab... | ```php
class RectorConfig
{
private $services;
public function services(): ServiceRegistry
{
$this->services = new ServiceRegistry();
return $this->services;
}
public function importNames(): void
{
// Implementation for importing names from the configuration
}
}
cl... | magicoder | php |
You are tasked with implementing a custom data structure that represents a mathematical sequence. The sequence is defined as follows: the first element is 0, the second element is 1, and each subsequent element is the sum of the previous two elements. You need to implement a method `GetNthElement(int n)` that returns t... | ```csharp
public class CustomSequence
{
private long[] elements;
public CustomSequence(int size)
{
elements = new long[size];
elements[0] = 0;
elements[1] = 1;
for (int i = 2; i < size; i++)
{
elements[i] = -1; // Placeholder for uninitialized elements
... | magicoder | csharp |
You are tasked with implementing a middleware system for a web application using PHP and Laravel. The middleware system is responsible for authenticating users before they can access certain routes. In Laravel, middleware can be applied to routes to filter HTTP requests entering the application. When a user tries to ac... | To solve this problem, you can create a custom middleware in Laravel to authenticate users before accessing the '/checkout' route. Here's a step-by-step solution:
1. Create a new middleware using the artisan command-line tool:
```bash
php artisan make:middleware AuthenticateCheckout
```
2. Open the newly cre... | magicoder | shell |
You are tasked with implementing a method to process and store virtual machine (VM) disk statistics from a database. The provided code snippet is a part of a larger codebase responsible for fetching and handling VM disk statistics. Your task is to create a method that processes the retrieved data and stores it in a sui... | ```java
public class VMDiskStatsProcessor {
// Method to process and store VM disk statistics
public void processAndStoreVMStats(ResultSet rs, List<EntityBean> vmDiskStats) {
try {
while (rs.next()) {
vmDiskStats.add(toEntityBean(rs, false));
}
} catch (SQ... | magicoder | java |
You are tasked with creating a Python script to automate the deployment of a Kubernetes cluster on VMware's Pivotal Container Service (PKS). The script should utilize the `pks` command-line interface and securely handle user credentials. Your script should prompt the user for their PKS credentials and the desired clust... | ```python
import os
import subprocess
# Prompt user for PKS credentials
pks_user = input(f"Enter PKS username [{os.getenv('PKS_USER')}]: ") or os.getenv('PKS_USER')
pks_password = input(f"Enter PKS password: ")
# Prompt user for cluster name
cluster_name = input(f"Enter cluster name [{os.getenv('CLUSTER_NAME')}]: ") ... | magicoder | python |
You are tasked with creating a utility function to parse and extract specific style properties from a given JavaScript object representing a stylesheet. The style properties to be extracted are `fontSize`, `flexDirection`, `flexWrap`, `questionTitle`, `marginBottom`, `textAlignVertical`, and `alignSelf`. The function s... | ```javascript
function extractStyles(stylesheet) {
const extractedStyles = {};
if (stylesheet.fontSize) {
extractedStyles.fontSize = stylesheet.fontSize;
}
if (stylesheet.horizontal) {
extractedStyles.flexDirection = stylesheet.horizontal.flexDirection;
extractedStyles.flexWrap = stylesheet.horizon... | magicoder | javascript |
You are tasked with creating a Django model for a new feature in an e-commerce platform. The feature involves allowing users to leave reviews for their purchases. The code snippet provided is a starting point for the `Review` model, which is intended to store information about a user's review for a specific purchase.
... | ```python
from django.db import models
from django.contrib.auth.models import User
from otcore.hit.models import Basket
class Review(models.Model):
basket = models.OneToOneField(Basket, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
time = models.DateTimeField(blank=Tru... | magicoder | python |
You are tasked with creating a Python function that processes a list of migration operations and returns a dictionary containing the count of each type of operation. Each migration operation is represented as a string in the format "migrations.OperationName(model_name='ModelName', ...)". The function should ignore case... | ```python
from typing import List, Dict
def count_migration_operations(operations: List[str]) -> Dict[str, int]:
operation_counts = {}
for operation in operations:
operation_name = operation.split('(')[0].split('.')[-1].lower()
operation_counts[operation_name] = operation_counts.get(operation_n... | magicoder | python |
You are tasked with implementing a Java class for managing NAT gateway SNAT (Source Network Address Translation) rules. The provided code snippet is a part of the class `CreateNatGatewaySnatRuleRequestOption`, which is used to configure SNAT rules for a NAT gateway.
The class `CreateNatGatewaySnatRuleRequestOption` ha... | ```java
// CreateNatGatewaySnatRuleOption class to represent the SNAT rule configuration
public class CreateNatGatewaySnatRuleOption {
private String sourceIp;
private String translatedIp;
// Constructor and methods for setting SNAT rule parameters
public CreateNatGatewaySnatRuleOption withSourceIp(Str... | magicoder | java |
You are tasked with implementing a simple class that represents a basic queue data structure. The class should have the following functionalities:
1. Enqueue: Add an element to the end of the queue.
2. Dequeue: Remove and return the element at the front of the queue.
3. Peek: Return the element at the front of the que... | ```java
public class Queue {
private Node front;
private Node rear;
private class Node {
Object data;
Node next;
Node(Object data) {
this.data = data;
this.next = null;
}
}
public void enqueue(Object element) {
Node newNode = new Nod... | magicoder | java |
You are tasked with creating a script that processes command-line options using the `getopts` function in a POSIX-compliant shell environment. The script should handle a specific option `-o` which takes an argument representing options for building a Docker image. Your task is to implement the logic for parsing this op... | ```bash
docker_build_options="default_options" # Set default value
while getopts "o:" opt; do
case "${opt}" in
o)
docker_build_options="${OPTARG}" # Store the argument for -o option
;;
esac
done
shift $((OPTIND - 1)) # Shift out processed options
echo "Docker build options: $docker_build_o... | magicoder | shell |
You are tasked with implementing a custom annotation processor that will analyze Java source code and identify methods that are marked with the `@Deprecated` annotation but do not have the `@deprecated` Javadoc tag. Your task is to write a program that takes a Java source file as input and identifies such methods.
You... | ```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DeprecatedMethodAnalyzer {
public static void main(String[] args) {
String filePath = "path_to_java_file"; // Replace with the actual fi... | magicoder | java |
You are tasked with implementing a function to find all anagrams of a given pattern within a larger input string. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. Your task is to write a function `find_string_anagrams(... | ```python
from collections import Counter
from typing import List
def find_string_anagrams(input_str: str, pattern: str) -> List[int]:
result = []
if not pattern or not input_str or len(pattern) > len(input_str):
return result # Return empty list for edge cases
window_start, matched = 0, 0
ch... | magicoder | python |
You are tasked with implementing a simple subscription management system in Swift using Combine framework. The system should allow adding and removing subscriptions, and it should handle memory management by canceling subscriptions when they are no longer needed.
You are provided with a code snippet that initializes a... | ```swift
import Combine
import XCTest
class SubscriptionManagerTests: XCTestCase {
private var subs: Set<AnyCancellable>!
override func setUp() {
super.setUp()
subs = []
}
func addSubscription(_ subscription: AnyCancellable) {
subs.insert(subscription)
}
func removeSu... | magicoder | swift |
You are tasked with creating a Rust program for a microcontroller using the Cortex-M framework. The program should utilize the provided crates `cortex_m`, `cortex_m_rt`, and `cortex_m_semihosting`. Your program needs to initialize the microcontroller, configure a GPIO pin, and then blink an LED connected to that pin at... | ```rust
// Import necessary crates
extern crate cortex_m;
extern crate cortex_m_rt;
extern crate cortex_m_semihosting;
use cortex_m_rt::entry;
use cortex_m_semihosting::hprintln;
use cortex_m::asm;
// Define LED pin and blink frequency
const LED_PIN: u8 = 5; // Example pin number
const BLINK_FREQ_HZ: u32 = 2; // Exam... | magicoder | rust |
You are working on a data analysis project and need to perform some operations on receiver operating characteristic (ROC) curve data. The ROC curve is a graphical plot that illustrates the diagnostic ability of a binary classifier system as its discrimination threshold is varied. You have been given a Python code snipp... | ```python
import pandas as pd
def calculate_auc(fpr, tpr):
"""
Calculate the area under the ROC curve using the trapezoidal rule.
Args:
fpr (array-like): False positive rate data.
tpr (array-like): True positive rate data.
Returns:
float: Area under the ROC curve (AUC).
"""
# Sort... | magicoder | python |
You are tasked with creating a Django REST framework API for managing courses and subjects. The given code snippet is a part of the URL configuration for the API. The `router` is used to automatically generate URL patterns for the `CourseViewSet`, and two additional URL patterns are manually defined for listing and vie... | ```python
# models.py
from django.db import models
class Subject(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Course(models.Model):
name = models.CharField(max_length=100)
subject = models.ForeignKey(Subject, on_delete=models.CASCADE)
d... | magicoder | python |
You are tasked with implementing a function that calculates the validation size and interval for a machine learning model training process. The function takes in several parameters related to the dataset and training settings and returns the validation size and interval.
The function signature is as follows:
```python... | ```python
from typing import Tuple, Optional
def validation_settings(dataset_size: int, batch_size: int, val_size: int, val_interval: int, keep_best_model: bool) -> Tuple[int, Optional[int]:
if val_size == 0:
val_size = int(0.2 * dataset_size)
if val_interval is None:
val_interval = int(0.... | magicoder | python |
You are tasked with implementing a custom asynchronous communication channel in C#. The channel should support both sending and receiving messages between different parts of a program. To achieve this, you need to create a class that encapsulates the functionality of the communication channel and provides methods for s... | ```csharp
using Cysharp.Threading.Tasks;
namespace Mirror.Websocket.Client
{
public class AsyncChannel<T>
{
private UniTaskChannel<T> channel = new UniTaskChannel<T>();
public async UniTask SendAsync(T message)
{
await channel.Writer.WriteAsync(message);
}
... | magicoder | csharp |
You are tasked with creating a Python class that interacts with Azure Blob Storage. Your class should be able to perform basic operations such as uploading a file, downloading a file, and listing files in a specified container.
Your task is to complete the implementation of the `AzureBlobStorageProvider` class by addi... | ```python
import os
from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient
class AzureBlobStorageProvider:
def __init__(self, connection_string, container_name):
self.connection_string = connection_string
self.container_name = container_name
self.blob_service_client =... | magicoder | python |
You are tasked with creating a Python function that samples values from a Gaussian Mixture Model (GMM) distribution. The GMM is defined by its parameters, including the mean, covariance, and weight of each component. The function should generate samples from the GMM and return the sampled values.
The GMM is represente... | ```python
import numpy as np
def Sample_GMM(gmm_params, ncenter, ndim, weight_smooth=0.0, sigma_scale=0.0):
b, target_length, _ = gmm_params.shape
nparams = 2 * ndim + 1
# Reshape gmm_params to separate mean, covariance, and weight components
gmm_params = gmm_params.reshape(b, target_length, ncenter, ... | magicoder | python |
You are given a 2D image represented as a grid of pixels, where each pixel is a vector of three floating-point values (e.g., Red, Green, Blue). Your task is to implement a bilinear interpolation algorithm to calculate the color value at a given fractional pixel position.
You are provided with the following code snippe... | ```cpp
cv::Vec3f bilinearInterpolation(const cv::Mat_<cv::Vec3f>& image, int ix, int iy, float ry) {
int ix_1 = std::min(ix + 1, image.cols - 1);
int iy_1 = std::min(iy + 1, image.rows - 1);
const cv::Vec3f& cxy = image.at<cv::Vec3f>(iy, ix);
const cv::Vec3f& cx_1y = image.at<cv::Vec3f>(iy, ix_1);
... | magicoder | cpp |
You are given a code snippet that appears to be a comment block at the beginning of a file. Your task is to write a program that can extract the author's name and email from the comment block. The comment block may contain multiple lines and may have varying formats, but the author's name and email will always be enclo... | ```python
import re
def extractAuthorInfo(comment_block):
author_info = {"name": "", "email": ""}
match = re.search(r"<<(.*?)>>(.*?)", comment_block)
if match:
author_info["name"] = match.group(1).strip()
author_info["email"] = match.group(2).strip()
return author_info
```
The `extra... | magicoder | python |
You are tasked with implementing a function to update a given image layer using a generator function that yields random 2x2 arrays. The update_layer function takes an image represented as a 2D array and updates a specific layer of the image with the values yielded by the generator function. Each yielded 2x2 array from ... | ```python
import numpy as np
from typing import List
def update_layer(image: List[List[List[int]]]) -> List[List[List[int]]]:
def generator_function():
yield np.array([[20, 21], [22, 23]])
yield np.array([[30, 31], [32, 33]])
gen = generator_function()
for i in range(len(image)):
f... | magicoder | python |
You are tasked with implementing a Python class that represents a configurable node in an Internet of Things (IoT) system. The class should have the following attributes and methods:
Attributes:
- `node`: a string representing the node's identifier
- `id`: an integer representing the unique ID of the node
- `name`: a ... | ```python
class Node:
def __init__(self, node, _id, name, settable, retained, qos, unit, data_type, data_format, value):
self.node = node
self.id = _id
self.name = name
self.settable = settable
self.retained = retained
self.qos = qos
self.unit = unit
s... | magicoder | python |
You are tasked with creating a simple command-line tool to analyze and visualize the syntax tree of a programming language using ANTLR (ANother Tool for Language Recognition). ANTLR is a powerful parser generator that can be used to build recognizers, interpreters, compilers, and translators for various languages.
You... | ```java
import org.antlr.v4.Tool;
import java.io.File;
import java.io.IOException;
public class SyntaxTreeAnalyzer {
public static void main(String[] args) {
try {
// Step 1: Use ANTLR tool to generate parser and related files
Tool antlrTool = new Tool(new String[]{"C0.g4", "-listen... | magicoder | java |
You are tasked with implementing a Content Security Policy (CSP) manager in Python. The CSP manager should be able to update and read CSP directives from a file. The CSP directives are represented as key-value pairs, where the key is the directive name and the value is the corresponding policy.
You need to implement a... | ```python
class CSPManager:
def __init__(self, file_path):
self.file_path = file_path
def update(self, directives: dict):
with open(self.file_path, 'w') as file:
for key, value in directives.items():
file.write(f"{key}:{value}\n")
def read(self) -> dict:
... | magicoder | python |
You are tasked with implementing a Python function to perform non-maximum suppression (NMS) on a set of bounding boxes. Non-maximum suppression is a technique used in object detection to filter out overlapping bounding boxes, retaining only the most confident ones.
You are given a code snippet that imports various mod... | ```python
def non_max_suppression(boxes, scores, threshold):
if len(boxes) == 0:
return []
# Initialize list to store selected box indices
selected_indices = []
# Calculate the area of each box
areas = (boxes[:, 2] - boxes[:, 0] + 1) * (boxes[:, 3] - boxes[:, 1] + 1)
# Sort the boundi... | magicoder | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.