query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with implementing a Python module that provides Optical Character Recognition (OCR) functionality. The given code snippet is a part of the module and uses the `__all__` attribute to specify the public interface of the module. The `__all__` attribute is a list of strings containing the names of all the pu... | ```python
def update_ocr_interface(current_interface, new_objects):
updated_interface = list(set(current_interface + new_objects))
return updated_interface
```
The `update_ocr_interface` function takes the `current_interface` and `new_objects` as input parameters. It combines the `current_interface` and `new_o... | magicoder | python |
You are tasked with implementing a gRPC service for a machine learning model server. The provided code snippet is a part of the gRPC server setup, where different RPC methods are being registered with their respective request and response serializers.
Your task is to create a Python class that handles the gRPC request... | ```python
import grpc
import grpc__service__pb2
class ModelService(grpc__service__pb2.ModelServiceServicer):
def ModelInfer(self, request, context):
# Handle model inference request
# Deserialize the request
infer_request = grpc__service__pb2.ModelInferRequest.FromString(request)
... | magicoder | python |
You are tasked with creating a Python function that processes a text file and performs a specific operation on its content. The function should read the file, manipulate the data, and then write the modified content back to the file. Your task is to implement the function `process_file` that takes a file path as input ... | ```python
def process_file(filepath: str, word: str) -> None:
with open(filepath, 'r') as file:
filedata = file.read()
# Count occurrences of the word
count = filedata.lower().count(word.lower())
# Replace all occurrences of the word with its uppercase version
modified_data = filed... | magicoder | python |
You are tasked with implementing a macro expansion in Rust. The macro, `impl_par_dist_rename`, is intended to rename certain types and traits within a Rust module. The macro takes the form:
```rust
macro_rules! impl_par_dist_rename {
($($body:tt)*) => {
$($body)*
rename! { [
ParallelStr... | ```rust
macro_rules! rename {
([$src:ident $dst:ident $($rest:tt)*]) => {
mod rename_mod {
pub use super::*;
pub use super::$src as $dst;
}
rename! { [$($rest)*] }
};
([]) => {};
}
// Example usage
mod my_module {
pub struct ParallelStream;
pub struct... | magicoder | rust |
You are tasked with creating a Discord bot command that allows users with the appropriate permissions to kick members from a server. The bot should be able to accept a member's name and an optional reason for the kick. Your task is to implement the `kick` command function within the `kick` class of the Discord bot.
Th... | ```python
import discord
from discord.ext import commands
class kick(commands.Cog):
def __init__(self, client):
self.client = client
#kick command
@commands.command()
@commands.has_permissions(kick_members=True)
async def kick(self, ctx, member: discord.Member, *, reason=None):
aw... | magicoder | python |
You are tasked with creating a grid-solving algorithm for a robotic vehicle navigating a grid-based environment. The grid is represented as a two-dimensional array, and the vehicle must find the optimal path from a starting position to a goal position while avoiding obstacles. The vehicle can move in four directions: u... | ```python
from typing import List, Tuple
from collections import deque
def find_shortest_path(grid: List[List[int]], start: Tuple[int, int], goal: Tuple[int, int]) -> List[Tuple[int, int]]:
rows, cols = len(grid), len(grid[0])
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
queue = deque([(start, [start])... | magicoder | python |
You are tasked with creating a Python function that parses absolute size specifications for block devices. The function should take a string representing the size specification and return the parsed size in bytes.
The absolute size specification can be in the following formats:
- Integer representing bytes (e.g., "102... | ```python
def parse_abs_size_spec(size_spec: str) -> int:
if size_spec[-1] not in ['B', 'K', 'M', 'G']:
raise ValueError("Invalid size specification format")
try:
size = int(size_spec[:-1])
except ValueError:
raise ValueError("Invalid size specification format")
if size_spec.en... | magicoder | python |
You are tasked with implementing a string interning mechanism in Rust. String interning is a process of storing only one copy of each distinct string value, which can help reduce memory usage and improve performance in certain scenarios. Your goal is to create a simple string interning library that provides the ability... | ```rust
use std::collections::HashMap;
/// An interned string created via [`intern!`].
///
/// [`intern!`]: macro.intern.html
#[derive(Clone, Copy)]
pub struct Str {
/// 14-bit address
pub(crate) address: u16,
}
struct FmtWrite<'a> {
fmt: &'a mut InternalFormatter,
}
struct InternalFormatter {
// Imp... | magicoder | rust |
You are tasked with implementing a simple object-oriented program in Java. Your goal is to create a class that represents a basic geometric shape and its properties. The class should have methods to calculate the area and perimeter of the shape. Additionally, you need to create a main method to demonstrate the function... | ```java
public class GeometricShape {
private String name;
private double area;
private double perimeter;
public GeometricShape(String name) {
this.name = name;
}
public void calculateArea() {
if (name.equalsIgnoreCase("circle")) {
// Assuming radius is known
... | magicoder | java |
You are tasked with creating a Python function to write data to a file in a specific format. The function should take in several parameters and append the data to a file. The data to be written includes the name, phone number, pincode, city, and a list of resources. The resources should be enclosed in square brackets a... | ```python
def write_data(name, phone, pincode, city, resources):
file_path = '/Users/mukesht/Mukesh/Github/covid_resource/resource_item.text'
with open(file_path, 'a') as f:
resource_str = ', '.join(resources)
f.write(f"{name}, {phone}, {pincode}, {city}, [{resource_str}]\n")
```
The `write_dat... | magicoder | python |
You are tasked with implementing a function to process a list of data entries. Each entry consists of a name and a value. Your function should identify and remove any duplicate entries based on the name, keeping only the first occurrence of each unique name. If a duplicate entry is encountered, a warning message should... | ```csharp
public class DataProcessor
{
public List<DataEntry> ProcessData(List<DataEntry> entries)
{
List<DataEntry> uniqueEntries = new List<DataEntry>();
HashSet<string> uniqueNames = new HashSet<string>();
foreach (var entry in entries)
{
if (!uniqueNames.Contains... | magicoder | csharp |
You are tasked with creating a secure authentication system for a web application. The system should generate and store authentication data for each user, including an access token, refresh token, and device token. To achieve this, you need to implement a function that generates the authentication data with placeholder... | ```python
import hashlib
def gen_auth_data():
auth_data = {
"account_id": 123,
"access_token": "<PASSWORD>",
"refresh_token": "<PASSWORD>",
"device_token": "<PASSWORD>",
}
return auth_data
def store_passwords(account_id, access_token, refresh_token, device_token):
# Imp... | magicoder | python |
You are tasked with creating a Python class that represents a database table. The class should have attributes that correspond to the fields of the table and methods to perform basic CRUD (Create, Read, Update, Delete) operations on the table. The provided code snippet is a Django model definition for an "orderform" ta... | ```python
import sqlite3
class DatabaseTable:
def __init__(self, table_name, field_names):
self.table_name = table_name
self.field_names = field_names
def create_record(self, values):
conn = sqlite3.connect('database.db')
c = conn.cursor()
placeholders = ','.join(['?'] ... | magicoder | python |
You are given a list of integers `nums`. Your task is to write a function `lengthOfLIS` to find the length of the longest increasing subsequence (LIS) within the list `nums`.
A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remainin... | ```python
def lengthOfLIS(nums):
if not nums:
return 0
dp = [1] * len(nums)
for i in range(len(nums)):
for j in range(i):
if nums[i] > nums[j]:
dp[i] = max(dp[i], dp[j] + 1)
return max(dp)
```
The `lengthOfLIS` function takes a list of integers `nums` as i... | magicoder | python |
You are tasked with implementing a secure messaging system using Python. Your goal is to create a class that can handle encryption and decryption of messages using RSA and SHA-512 algorithms. The class should have methods for generating RSA key pairs, encrypting messages with the public key, and decrypting messages wit... | ```python
import hashlib
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
class SecureMessenger:
def __init__(self, privkey_path, pubkey_path):
self.privkey_path = privkey_path
self.pubkey_path = pubkey_path
self.algos = {'sha512': ''}
def generate_keys(self):
... | magicoder | python |
You are tasked with implementing a function that measures the performance of a data persistence operation. The function takes in several parameters, including a collection ID, an expected input frontier, and a mutable reference to a benchmarking tool. The code snippet provided is a part of the function and shows the cl... | ```rust
use test::Bencher; // Import the Bencher type from the test crate
fn measure_persistence_performance<M>(
persistence_base_path: String,
nonce: u64,
collection_id: String,
expected_input_frontier: u64,
b: &mut Bencher<M>,
) {
// Clone the necessary variables for use within the benchmarki... | magicoder | rust |
You are tasked with creating a Minecraft plugin that manages player teleportation between different dimensions. The plugin should allow players to teleport to any available dimension within the Minecraft server. To achieve this, you need to implement a method that retrieves a list of available dimensions and their corr... | ```java
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.world.WorldServer;
import net.minecraftforge.common.DimensionManager;
import net.minecraftforge.fml.common.FMLCommonHandler;
public class DimensionTeleportPlugin {
public void listAvailableDimensions(Object sender) {
if (!(sende... | magicoder | java |
You are tasked with creating a Python class that processes and manipulates 3D voxel data. The class should inherit from the `dpWriteh5` class and include functionality for handling voxel types. The voxel type data is stored in a HDF5 dataset named 'voxel_type' and is represented using the `np.uint8` data type. Addition... | ```python
import numpy as np
from emdrp.dpWriteh5 import dpWriteh5
from emdrp.utils.utils import optimal_color
class emVoxelType(dpWriteh5):
VOXTYPE_DTYPE = np.uint8
VOXTYPE_STR_DTYPE = 'uint8'
VOXTYPE_DATASET = 'voxel_type'
EMPTY_VOXTYPE = np.iinfo(VOXTYPE_DTYPE).max
def select_optimal_color(self... | magicoder | python |
You are tasked with implementing a Python class that interacts with a remote server using a custom serialization library. The class should be able to serialize and deserialize data to communicate with the server. The server expects data in a specific format, and the class needs to ensure that the data is properly forma... | ```python
from BridgePython import serializer, reference
class Client(object):
def __init__(self, server_url):
self.server_url = server_url
def send_data(self, data):
serialized_data = self.serialize(data)
reference.send_to_server(self.server_url, serialized_data)
def receive_data... | magicoder | python |
You are tasked with implementing a Python generator function that yields a specific pattern of values. Additionally, you need to compare the memory usage of a list comprehension and a generator expression in Python.
Implement a Python generator function called `generate_values` that yields a specific pattern of values... | ```python
import sys
def generate_values():
for i in range(4, 9):
yield "valor " + str(i)
# Usage of the generator function
f = generate_values()
for i in f:
print(i)
# Memory usage comparison
l1 = [x for x in range(1000)] # List comprehension
l2 = (x for x in range(1000)) # Generator expression
p... | magicoder | python |
You are given an array of integers `nums` of length `n`. Your task is to write a function `next_larger_element` that takes `n` and `nums` as input and returns an array of integers representing the next larger element for each element in the input array. If there is no next larger element, the output array should contai... | ```cpp
#include <vector>
#include <stack>
std::vector<int> next_larger_element(int n, const std::vector<int>& nums) {
std::vector<int> result(n, -1); // Initialize result array with -1
std::stack<int> stack; // Stack to store indices of elements
for (int i = 0; i < n; i++) {
while (!stack.empty(... | magicoder | cpp |
You are tasked with implementing a file transfer protocol using Python's socket programming. Your goal is to create a server program that can send a file to a client program over a network connection. The server should read the file in chunks and send each chunk to the client until the entire file has been transmitted.... | ```python
import socket
# Define the file to be saved
FILE_PATH = 'path_to_save_file'
SIZE = 1024
# Create a socket object
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Get the hostname of the server
host = socket.gethostname()
# Define the port on which the server is listening
port = 9999
# ... | magicoder | python |
You are tasked with implementing a loss function for a generative adversarial network (GAN) architecture. The GAN consists of a generator and a discriminator, and the goal is to train the generator to produce realistic data samples that can fool the discriminator. The code snippet provided includes references to differ... | ```python
def custom_loss(generator_output, discriminator_output_real, discriminator_output_generated, loss_type):
if loss_type == 'oasis_d_loss':
return oasis_d_loss(discriminator_output_real, discriminator_output_generated)
elif loss_type == 'oasis_g_loss':
return oasis_g_loss(discriminator_ou... | magicoder | python |
You are tasked with creating a program that generates a specific pattern called "Rangoli". Rangoli is a form of Indian folk art in which patterns are created on the ground or floor using colored rice, flour, sand, or flower petals. In this problem, you are required to create a Python function `print_rangoli(size)` that... | ```python
def print_rangoli(size):
import string
alphabets = string.ascii_lowercase
pattern = []
width = 4 * size - 3
for i in range(size):
s = '-'.join(alphabets[size-1:i:-1] + alphabets[i:size])
pattern.append((s.center(width, '-')))
for i in range(size-2, -1, -1):
s ... | magicoder | python |
You are tasked with implementing a Python class that generates a compiled list of strings based on given templates and data. The class should have methods to add templates, categories, and compiled data, and a method to generate the final compiled list.
You are given a code snippet that partially implements the class.... | ```python
from string import Template
class CompiledGenerator:
def __init__(self):
self.__templates = {}
self.__categories = set()
self.__compiled = {}
def add_template(self, template_name, template_string):
self.__templates[template_name] = Template(template_string)
def a... | magicoder | python |
You are tasked with creating a script that analyzes a directory containing QML files and extracts information about the imports used in those files. QML (Qt Modeling Language) is a user interface markup language used to design user interfaces in Qt applications. Each QML file may contain import statements to include ot... | ```bash
#!/bin/bash
if [ $# -ne 1 ]; then
echo "Usage: $0 <directory>"
exit 1
fi
directory=$1
if [ ! -d "$directory" ]; then
echo "Error: $directory is not a directory"
exit 1
fi
find "$directory" -type f -name '*.qml' -exec grep -h '^import' {} \; | sort -u
```
The script first checks if the correct numbe... | magicoder | shell |
You are tasked with implementing a function that searches for a specific element in a given array using a custom search algorithm. The array is first filtered based on a given condition, and then the search is performed on the filtered array. Your task is to write a function that takes in an array, a search term, and a... | ```javascript
function customSearch(array, search, condition) {
// Filter the array based on the given condition
var filteredArray = array.filter(condition);
// Search for the element in the filtered array
var indexOfSearch = filteredArray.indexOf(search);
// Return the index of the search... | magicoder | javascript |
You are tasked with implementing a generic class that enforces a clamped property within a specified range. The clamped property should be of a specific type and should only allow values within the defined range. Your task is to create a C# class that fulfills these requirements and write a unit test to verify its func... | ```csharp
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
public interface IClampedPropertyT<T> {
bool IsValueInRange(T value);
}
public interface IClampedVersion : IClampedPropertyT<Version> {
}
public class ClampedVersion : IClampedVersion {
private readonly Version _minVersion;
priva... | magicoder | csharp |
You are tasked with implementing a class that simulates a login process. The class contains a method `get_login_responce` that performs the following steps:
1. Prints a line of dashes as a separator.
2. Prints "Step3: Loggin and resolve response."
3. Calls the method `_generate_encrypted_login_info` to generate encrypt... | ```python
class LoginSimulator:
def __init__(self):
self._login_result = None
def _generate_encrypted_login_info(self):
# Implement the logic to generate and store encrypted login information
pass # Placeholder, replace with actual implementation
def _send_login_info(self):
... | magicoder | python |
You are tasked with creating a PHP class that manages tasks for a project management system. The class should handle the creation, retrieval, and deletion of tasks. Each task has a title, description, status, and due date. You need to implement the methods for adding a new task, retrieving all tasks, retrieving tasks b... | ```php
<?php
class Task
{
public $id;
public $title;
public $description;
public $status;
public $dueDate;
public function __construct($id, $title, $description, $status, $dueDate)
{
$this->id = $id;
$this->title = $title;
$this->description = $description;
$... | magicoder | php |
You are tasked with implementing a TypeScript function that processes equipment state updates for a game. The game has various entities that can be equipped with items at different attachment points. The provided code snippet defines some types and an enum related to equipment state updates.
Your task is to implement ... | ```typescript
type BinaryValue = boolean;
type equippedEntityId = number;
export type EquippedStateUpdateSchema = [BinaryValue, equippedEntityId?];
export enum EquippableAttachmentPoint {
HEAD,
LEFT_HAND,
RIGHT_HAND
}
type EquipmentState = {
[key in EquippableAttachmentPoint]?: equippedEntityId;
};
function... | magicoder | typescript |
You are tasked with writing a script to automate the build process for a software project. The script needs to source certain constants from a file, set build arguments, and navigate to the build context directory. Additionally, it should handle a flag for signing the build.
Given the provided code snippet, your task ... | ```bash
#!/bin/bash
# Source the constants from the file
source $REPO_DIR/build/__sdkStorageConstants.sh
# Set the build arguments using the constants
declare -r BASE_TAG_BUILD_ARGS="--build-arg PYTHON_BASE_TAG=$PYTHON_BASE_TAG \
--build-arg PHP_BUILD_BASE_TAG=$PHP_BUILD_BASE_TAG \
... | magicoder | shell |
You are tasked with implementing a function that parses a given text document and extracts specific information from it. The text document is structured in a key-value format, where each key is followed by a colon and the corresponding value. The keys and values are separated by a newline character. The text document m... | ```typescript
function parseTextDocument(text: string, key: string): string[] {
const result: string[] = [];
const parseSection = (sectionText: string) => {
const regex = new RegExp(`${key}:\\s*({[^{}]*})`, 'g');
let match;
while ((match = regex.exec(sectionText)) !== null) {
result.push(match[1]... | magicoder | typescript |
You are given a code snippet that appears to be a template for generating code related to nested loops and iterators. Your task is to analyze the given code and identify the potential output or behavior of the code when it is fully expanded and executed.
Given the code snippet:
```
{{>conflict var="arg" is_tri... | The given code snippet appears to be a template for generating nested loops and iterators. However, the specific details of the template and the context in which it is used are not provided. Without the complete context and the definitions of the template variables and functions, it is not possible to accurately predic... | magicoder | python |
You are tasked with creating a program that processes a configuration file in the format of key-value pairs and performs specific operations based on the provided commands. The configuration file contains lines in the format "key=value" and commands in the format "command key". The commands can be "get", "set", or "uns... | ```python
def process_configuration_file(config_file, commands):
config = {}
with open(config_file, 'r') as file:
for line in file:
line = line.strip()
if line and not line.startswith('#'):
key, value = line.split('=')
config[key] = value
for ... | magicoder | python |
You are tasked with implementing a self-attention module for a neural network. The self-attention module is designed to process content and style features and produce an output. The module consists of two self-attention networks (SANet), an upsampling layer, and a convolutional layer for merging the features. The forwa... | ```python
import torch
class Self_Attention_Module(nn.Module):
# ... (same as in the problem description)
def forward(self, content_feats, style_feats):
# Apply the first self-attention network (SAN1) to the content features
content_feats = self.SAN1(content_feats)
# Apply the second ... | magicoder | python |
You are tasked with creating a smart contract for a decentralized application (dApp) on a blockchain platform. The smart contract is responsible for handling the initialization process when it is first deployed. The code snippet provided is a unit test written in Rust for the proper initialization of the smart contract... | ```rust
use cosmwasm_std::{Depositor, DepsMut, Env, MessageInfo, Response, StdError, StdResult};
// Define the struct for the initialization message
pub struct InstantiateMsg {}
// Define the instantiate function
pub fn instantiate(deps: DepsMut, _env: Env, info: MessageInfo, _msg: InstantiateMsg) -> StdResult<Respon... | magicoder | rust |
You are tasked with creating a C++ function that utilizes the `mayaUsd` library to perform a specific operation on a USD file. The `mayaUsd` library provides a set of tools for working with USD (Universal Scene Description) files within the Autodesk Maya environment. Your function should take a USD file path as input a... | ```cpp
#include <mayaUsd/fileio/utils/shadingUtil.h>
#include <mayaUsd/utils/util.h>
#include <pxr/base/tf/diagnostic.h>
#include <string>
#include <vector>
std::vector<std::string> extractShadingInformation(const std::string& usdFilePath) {
std::vector<std::string> shadingInfo;
// Load the USD file using th... | magicoder | cpp |
You are working with a storage management system that allows you to manage storage pools. Each storage pool has a name and a state, and can be either managed or unmanaged. You have access to a client object `oneview_client` that provides methods for interacting with the storage pools.
Your task is to implement a Pytho... | ```python
def manage_storage_pools(oneview_client):
# Print the current state of all storage pools
storage_pools_all = oneview_client.storage_pools.get_all()
for pool in storage_pools_all:
print(" '{}' state is {}".format(pool['name'], pool['state']))
# Remove the first storage pool from mana... | magicoder | python |
You are given a dynamic programming problem that involves calculating the number of ways to reach a certain sum. You are given an array `dp` of size `(n+1) x (s+1)` where `n` is the number of elements in the input array and `s` is the target sum. The value `dp[i][j]` represents the number of ways to achieve the sum `j`... | ```python
from typing import List
def countWays(nums: List[int], target: int) -> int:
mod = 10**9 + 7
n = len(nums)
dp = [[0] * (target + 1) for _ in range(n + 1)]
dp[0][0] = 1
for i in range(n):
for j in range(target + 1):
dp[i+1][j] += dp[i][j]
dp[i+1][j] %= mod
... | magicoder | python |
You are tasked with implementing a generic `AdapterService` class that provides a method `getService` to retrieve a specific service by its name. The `getService` method takes a `serviceName` as a parameter and returns an instance of the specified service. Your task is to create the `AdapterService` class and implement... | ```java
// Generic AdapterService class
public class AdapterService<T> {
// Method to retrieve a specific service by name
public T getService(String serviceName) {
// Implement service retrieval logic here
// For demonstration purposes, let's assume a map of available services
Map<String... | magicoder | java |
You are tasked with implementing a function that determines the direct parent view controller of a given view controller in a hierarchical iOS app structure. The hierarchy is defined by the following order of parent view controllers: Navigation, SplitView, TabBar, and Presenting.
You are given the following Swift code... | ```swift
func directParentViewController(of viewController: UIViewController) -> UIViewController? {
if let presentingViewController = viewController.presentingViewController {
return presentingViewController
} else if let tabBarController = viewController.tabBarController {
return tabBarControl... | magicoder | swift |
You are tasked with creating a PHP function that processes an array of monitoring data and generates a report based on certain conditions. The monitoring data is represented as an array of associative arrays, where each inner array contains information about a specific monitoring event. The function should filter the m... | ```php
function generateMonitoringReport($monitoringData, $version, $threshold) {
// Filter the monitoring data based on the given version and threshold
$filteredData = array_filter($monitoringData, function($event) use ($version, $threshold) {
return $event["VERSION"] === $version && $event["VALUE"] >=... | magicoder | php |
You are tasked with implementing a program to process and analyze a collection of objectives. Each objective is represented by an object with properties including `objectiveHash`, `progress`, `completionValue`, `complete`, and `visible`. The `objectiveHash` is a unique identifier for the objective, `progress` indicates... | ```javascript
class Objective {
objectiveHash: number;
progress: number;
completionValue: number;
complete: boolean;
visible: boolean;
constructor(objectiveHash: number, progress: number, completionValue: number, complete: boolean, visible: boolean) {
this.objectiveHash = objectiveHash;
this.progre... | magicoder | javascript |
You are tasked with implementing a Python function that applies the Roberts edge detection algorithm to a given grayscale image. The Roberts operator is a simple edge detection algorithm that uses two 2x2 convolution kernels to detect vertical and horizontal edges in an image. The algorithm calculates the gradient magn... | ```python
import cv2
import numpy as np
def apply_roberts_edge_detection(image_path, threshold):
img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
# Roberts kernels for edge detection
roberts_kernel_x = np.array([[1, 0], [0, -1]])
roberts_kernel_y = np.array([[0, 1], [-1, 0]])
# Apply Roberts ke... | magicoder | python |
You are tasked with implementing a Python class that manages network port scanning and result reporting. The class, named `PortScanner`, has a method `doSet` that sets up the port scanning parameters, and another method `doScan` that performs the actual port scanning and updates the result status accordingly.
The `Por... | ```python
class Result:
def __init__(self):
self.rst = ""
self.val = ""
self.raw = ""
class ResultStatus:
OK = "OK"
NG = "NG"
class PortScanner:
def __init__(self):
self.result = Result()
self.ports_to_scan = []
self.host = ""
def doSet(self, host, ... | magicoder | python |
You are tasked with creating a script to manage a system's Kerberos administration server. The script should handle various commands and execute the appropriate actions based on the input. The provided code snippet is a part of the script and shows the handling of a specific command.
Your task is to implement a functi... | ```bash
#!/bin/bash
manage_kerberos_server() {
case "$1" in
start)
/usr/sbin/kadmind -nofork
;;
stop)
# Logic to stop the Kerberos administration server
;;
restart)
# Logic to restart the Kerberos administration server
... | magicoder | shell |
You are working as a DevOps engineer for a company that manages a large number of macOS devices. Your team has decided to use Reposado, an open-source tool for managing Apple Software Updates. As part of the setup process, you need to configure Reposado to use a specific directory structure and a custom URL for serving... | ```python
import subprocess
# Step 1: Clone the Reposado repository from GitHub
subprocess.run(["git", "clone", "https://github.com/wdas/reposado"])
# Step 2: Navigate into the cloned reposado directory
subprocess.run(["cd", "reposado"])
# Step 3: Install Reposado
subprocess.run(["python", "setup.py", "install"])
#... | magicoder | python |
You are tasked with creating a Python class that represents a simple authentication system for a web application. The class should include a method for user authentication and a method for user registration. The user information will be stored in a database using Django's ORM (Object-Relational Mapping). The provided c... | ```python
from django.contrib.auth.models import User
class AuthenticationSystem:
def register_user(self, username, password):
# Create a new user in the database
user = User.objects.create_user(username, password=password)
user.save()
def authenticate_user(self, username, password):
... | magicoder | python |
You are given a 2D grid representing a game board with obstacles. The grid contains 0s for empty spaces and 2s for obstacles. Your task is to write a function that determines the shortest path from the top-left corner to the bottom-right corner of the grid, avoiding the obstacles. You can only move in four directions: ... | ```python
from typing import List
from collections import deque
def shortestPath(grid: List[List[int]]) -> int:
rows, cols = len(grid), len(grid[0])
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
queue = deque([(0, 0, 0)]) # (row, col, distance)
visited = set((0, 0))
while queue:
row, c... | magicoder | python |
You are tasked with implementing a class that manages the styling properties for a UI component. The class should allow for setting and getting the values of various styling properties, and it should support binding these properties to external values. Your task is to create a TypeScript class that fulfills these requi... | ```typescript
class UIStyler {
public marginEnds = '0px';
@bindable
public paddingSides = 'var(--s1)';
@bindable
public paddingEnds = 'var(--s0)';
setMarginEnds(value: string): void {
this.marginEnds = value;
}
getPaddingSides(): string {
return this.paddingSides;
}... | magicoder | typescript |
You are tasked with implementing a program to manage racers and the roads they are racing on. The program should handle adding racers to roads, removing racers from roads, and listing all the racers on a specific road.
You are given a partially completed code snippet that handles the removal of a road and its associat... | ```csharp
using System;
using System.Collections.Generic;
class RacerManager
{
private Dictionary<string, List<string>> roadsAndRacers = new Dictionary<string, List<string>>();
public void AddRacerToRoad(string road, string racer)
{
if (roadsAndRacers.ContainsKey(road))
{
roads... | magicoder | csharp |
You are tasked with implementing a read-only collection factory for aggregations in TypeScript. The `AggregationCollectionFactory` class extends the `CollectionFactory` class and takes in a configuration object of type `AggregationCollectionConfig` as a constructor parameter. The `AggregationCollectionConfig` interface... | ```typescript
interface AggregationCollectionConfig {
sync?: boolean;
}
class CollectionFactory<T> {
// Implementation of CollectionFactory class
// ...
// Method to add documents to the collection
public addDocument(document: T): void {
// Implementation to add document
// ...
}
}
class Aggregat... | magicoder | typescript |
You are tasked with creating a Python unit test for a class that interacts with a smoothie driver for a laboratory automation system. The class, `SmoothieConnection`, is responsible for establishing a connection with the smoothie driver and sending commands to it. The code snippet provided includes fixtures for mocking... | ```python
import pytest
from opentrons.drivers.smoothie_drivers.constants import SMOOTHIE_COMMAND_TERMINATOR
from smoothie_connection import SmoothieConnection # Assuming the class is defined in smoothie_connection module
@pytest.fixture
def mock_serial_connection() -> AsyncMock:
"""Mock serial connection."""
... | magicoder | python |
You are given a Rust function `get_missing_edge` that takes in a generic type `G` which implements the `BaseGraph` trait. The function is intended to find a missing edge in the graph and return it as an `Option` containing a tuple of two `usize` values representing the missing edge's endpoints.
The function contains a... | ```rust
use petgraph::graph::BaseGraph;
use std::collections::HashSet;
impl YourStruct {
fn get_missing_edge<G: BaseGraph>(&self, graph: &G) -> Option<(usize, usize)> {
let mut vertices: HashSet<_> = (0..graph.node_count()).collect();
graph.edge_indices().for_each(|edge| {
let (source, ... | magicoder | rust |
You are given a list of integers representing the scores of a series of games. Your task is to calculate the average score of the games, but with a twist. Instead of simply calculating the arithmetic mean, you need to implement a function that calculates the average score using the following formula:
Average Score = (... | ```python
def calculate_average_score(scores):
distinct_scores = set(scores) # Get distinct scores using a set
sum_of_scores = sum(scores) # Calculate the sum of all scores
average_score = sum_of_scores / len(distinct_scores) # Calculate the average score
return average_score
```
The `calculate_avera... | magicoder | python |
You are tasked with implementing a stack data structure that supports an additional operation for overriding elements at specific indices. The stack should be implemented using a template class in C++.
You need to implement the following functionalities:
1. `push` function: This function should add an element to the t... | ```cpp
#include <vector>
template<class T>
class Stack {
private:
std::vector<T> m_Stack;
unsigned int m_Index;
public:
Stack() : m_Index(0) {}
void push(const T& obj, bool override) {
if (override || m_Stack.size() == 0)
m_Stack.push_back(obj);
else
m_Stack.pu... | magicoder | cpp |
You are tasked with creating a Python function that processes data from a YAML file and updates a database with the information. The data represents mountains and their attributes. The code snippet provided initializes the process by loading the YAML file and querying existing mountain data from the database.
Your tas... | ```python
from app.models import db, Mountain
def update_mountains_db(mt_yaml, existing_mountains):
new_mountains = []
updated_mountains = []
for yaml_mountain in mt_yaml['mountains']:
existing_mountain = next((m for m in existing_mountains if m.name == yaml_mountain['name']), None)
if exi... | magicoder | python |
You are tasked with creating a script to manage smart plugs in a home automation system. The script should include a function to describe the status of a plug using the Kasa smart plug API and the `jq` command-line JSON processor.
You are provided with a code snippet that defines a function `kasa_describe_plug()` whic... | ```bash
# Define the function to query the plug status
kasa_query_plug() {
local host="${1}"
# Make a request to the Kasa smart plug API and retrieve the status
# Example: Use curl to make a GET request to the Kasa API
# Replace <API_ENDPOINT> and <PLUG_ID> with actual API endpoint and plug ID
local status=$(... | magicoder | shell |
You are tasked with creating a Python function that processes a given dataset and performs data cleaning operations. The function should take in several parameters and apply the specified data cleaning operations to the dataset. Your task is to implement the function according to the given requirements.
You are provid... | ```python
import pandas as pd
def clean_dataset(file_path, nrows=None, na_values=None, keep_default_na=True, na_filter=True):
# Read the dataset, considering the specified number of rows
dataset = pd.read_csv(file_path, nrows=nrows)
# Replace the NA/NaN values with the additional strings specified in ... | magicoder | python |
You are tasked with implementing a multi-threaded program that simulates a simple resource management system using read-write locks. The program should consist of a resource manager class that allows multiple threads to access a shared resource with the appropriate locking mechanisms.
Your task is to complete the impl... | ```cpp
#include <ace/Thread_Mutex.h>
class ResourceManager {
private:
ACE_RW_Thread_Mutex lock_;
public:
void acquireReadLock() {
lock_.acquire_read();
}
void releaseReadLock() {
lock_.release();
}
void acquireWriteLock() {
if (lock_.trywrlock() != 0) {
lo... | magicoder | cpp |
You are working on a machine learning project and need to automate the training process for an autoencoder model using Google Cloud Platform (GCP) services. The provided code snippet is part of a shell script used to set up the necessary environment variables and configurations for the training job.
Given the code sni... | ```bash
# Package the code
cd $PACKAGE_PATH
python setup.py sdist --formats=gztar
cd $PWD
# Submit the training job to GCP AI Platform
gcloud ai-platform jobs submit training $JOB_NAME \
--job-dir gs://$BUCKET/$JOB_NAME \
--module-name $MODULE_NAME \
--package-path $PACKAGE_PATH \
--region us-central1 ... | magicoder | shell |
You are working on a molecular dynamics simulation software and need to implement a parser for improper dihedral parameters. An improper dihedral is a type of potential energy function used to model the behavior of molecules. The parameters for an improper dihedral are typically defined in a database and need to be par... | ```python
def parse_improper_dihedral(db, entry_name):
if entry_name in db.improper:
style = db.improper[entry_name].style
params = list(map(int, db.improper[entry_name].params.split()))
return style, params
else:
return None
```
The `parse_improper_dihedral` function first chec... | magicoder | python |
You are tasked with implementing a function that parses a C++ source file and extracts the author's name and the copyright year from the file header comment. The file header comment is defined as a block of comments at the beginning of the file, enclosed by `/*` and `*/`, and containing the following information:
- Fil... | ```cpp
#include <string>
#include <regex>
#include <utility>
std::pair<std::string, std::string> extractFileInfo(const std::string& source) {
std::smatch match;
std::regex pattern(R"(/\*.*@author\s+(.*?)\s+.*Copyright\s+(\d{4})-(\d{4})\s+(.*?)\s+\*/)");
if (std::regex_search(source, match, pattern)) {
... | magicoder | cpp |
You are tasked with implementing a function to validate the merge of two bounding boxes in a 3D space. The function `ValidateMerge` takes in two flags `f1` and `f2`, two instances of the `Fbox` class `bb_base` and `bb`, and a reference to a `float` variable `volume`. The `Fbox` class represents a 3D bounding box and co... | ```cpp
IC BOOL ValidateMerge(u32 f1, const Fbox& bb_base, const Fbox& bb_base_orig, u32 f2, const Fbox& bb, float& volume) {
// Assuming merged, orig1, orig2, and c_SS_maxsize are defined and accessible
for (int iAxis = 0; iAxis < 3; iAxis++) {
if ((merged[iAxis] > (4 * c_SS_maxsize / 3)) &&
... | magicoder | cpp |
You are working on a software system for controlling a high-precision electron microscope used in material science research. The microscope has a stage that can move in three dimensions (x, y, z) and also rotate around the x-axis (r) and y-axis (t). The code snippet provided is from a test suite for the software system... | ```python
import numpy as np
class MicroscopeSpecimen:
def __init__(self, stage):
self.stage = stage
class Microscope:
def __init__(self, specimen):
self.specimen = specimen
def calculate_final_position(original_position, dx, dy, dz, dr, dt):
final_position = {
'x': original_posit... | magicoder | python |
You are tasked with implementing a generic function to join elements from a sequence container into a single string. The function should take a sequence container (e.g., vector, deque, list) of strings as input and return a concatenated string of all the elements in the container.
Your task is to implement the `join_s... | ```cpp
#include <iostream>
#include <string>
#include <vector>
#include <deque>
#include <list>
#include <algorithm>
#include <iterator>
template <template <typename...> class Container, typename T>
std::string join_sequence_container(const Container<T>& container) {
std::string result;
for (const auto& elemen... | magicoder | cpp |
You are tasked with implementing a Python class that interacts with a PostgreSQL database. The class, `PostgreSQLManager`, should provide methods for querying and updating data in the database. Your task is to complete the implementation of the `PostgreSQLManager` class by adding the necessary methods to perform the fo... | ```python
import psycopg2
class PostgreSQLManager:
def __init__(self, connection_string):
self.connection = psycopg2.connect(connection_string)
def query_all(self, table_name):
cursor = self.connection.cursor()
cursor.execute(f"SELECT * FROM {table_name}")
records = cursor.fetc... | magicoder | python |
You are tasked with creating a program that generates fake data for a fictional social media platform. The program should use the Faker library to create random user profiles with various attributes such as name, username, email, date of birth, and bio. Additionally, the program should allow for the generation of a spe... | ```python
from faker import Faker
import json
import csv
def generate_fake_profiles(num_profiles, output_format):
fake = Faker()
profiles = []
for _ in range(num_profiles):
profile = {
"name": fake.name(),
"username": fake.user_name(),
"email": fake.email(),... | magicoder | python |
You are tasked with implementing a custom permission class for a Django REST Framework (DRF) view that handles preprints. The provided code snippet is from a DRF view class and shows the configuration of the permission classes, serializer class, required read and write scopes, and a URL keyword argument.
Your task is ... | ```python
from rest_framework import permissions
class PreprintPublishedOrAdmin(permissions.BasePermission):
def has_permission(self, request, view):
# Check if the user is an admin
if request.user and request.user.is_staff:
return True
# Check if the preprint is published
... | magicoder | python |
You are tasked with implementing a Java class that simulates a simple banking system. The class should have the following functionalities:
1. Create a new bank account with a unique account number and an initial balance.
2. Deposit a specified amount into the account.
3. Withdraw a specified amount from the account.
4... | ```java
public class BankAccount {
private int accountNumber;
private double balance;
public BankAccount(int accountNumber, double initialBalance) {
this.accountNumber = accountNumber;
this.balance = initialBalance;
}
public void deposit(double amount) {
balance += amount;
... | magicoder | java |
You are working on a bioinformatics project that involves processing MHC allele and peptide data for predicting peptide-MHC binding. You have a dataframe `df_mhc` containing information about MHC alleles. You need to generate pairwise index data for the peptides and MHC alleles, and then save the generated data to disk... | ```python
import numpy as np
import pandas as pd
def generate_pairwise_index_data(df_peptides, df_mhc):
# Generate pairwise index data for peptides and MHC alleles
# ... (implementation details not provided)
# Example implementation using random data
num_peptides = len(df_peptides)
num_mhc = len(d... | magicoder | python |
You are tasked with creating a program that automates the generation of PHP mail classes based on predefined templates. The program should take a mail class name as input and generate the corresponding PHP file with the appropriate content. The template for the mail class is provided and contains placeholders that need... | ```php
class MailGenerator {
public static function generateMailClass($className) {
// Check if the mail class name is valid
if (!preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $className)) {
$message = "Invalid mail class name.\n\n";
fputs(STDERR, $message);
... | magicoder | php |
You are tasked with creating a class that represents an IP address. Your task is to implement a method within the class that validates whether the provided IP address is valid or not. An IP address is considered valid if it consists of four decimal numbers separated by periods, with each number ranging from 0 to 255. L... | ```csharp
public class IPAddressValidator
{
public string? IP { get; set; }
public bool IsValidIP()
{
if (string.IsNullOrEmpty(IP))
{
return false;
}
string[] parts = IP.Split('.');
if (parts.Length != 4)
{
return false;
}
... | magicoder | csharp |
You are tasked with implementing a Python function that processes a given MATLAB file and extracts specific data from it. The MATLAB file contains a multi-dimensional array named `mat`, and the function should extract and return a specific element from this array.
Write a function `extract_mat_element(file_path: str, ... | ```python
import scipy.io
from typing import Tuple, Any
def extract_mat_element(file_path: str, element_indices: Tuple[int, ...]) -> Any:
mat_data = scipy.io.loadmat(file_path)
mat_array = mat_data['mat']
result = mat_array
for index in element_indices:
result = result[index]
return result
... | magicoder | python |
You are tasked with creating a Swift data structure to represent a response object for a specific API endpoint. The response object should conform to Codable, JSONEncodable, and Hashable protocols and contain specific properties.
Your task is to design a Swift struct that represents the response for the POST request t... | ```swift
// Define the payload structure for EzsigntemplatepackagemembershipCreateObjectV1Response
public struct EzsigntemplatepackagemembershipCreateObjectV1ResponseMPayload: Codable, Hashable {
// Define properties for EzsigntemplatepackagemembershipCreateObjectV1ResponseMPayload
// ...
}
// Define the debug... | magicoder | swift |
You are tasked with creating a function that processes a list of user groups and their associated users to generate a queryset of task results. The function should take a list of users and their associated groups, and then filter the task results based on these users and their groups.
The function should perform the f... | ```python
from typing import List
from django.db.models import QuerySet
from myapp.models import TaskResult
def generate_task_queryset(users_list: List[str]) -> QuerySet:
# Create a set of all unique users from the input list of user groups
users_set = list(set(users_list))
# Initialize the queryset w... | magicoder | python |
You are tasked with debugging a section of code that interacts with an agent client to set parameters for a mission. The code snippet provided is a part of a larger program that communicates with an external agent to control a mission. The snippet includes setting parameters, retrieving resources, and handling potentia... | The code snippet provided is a part of a larger program that interacts with an agent client to set parameters for a mission. It seems to be attempting to set a parameter and handle any discrepancies or errors that may occur during the process. However, there are some issues in the code that need to be addressed.
Here'... | magicoder | python |
You are tasked with implementing a custom assertion system for a PHP authorization library. The system should support three types of assertions: callable, instances of `AssertionInterface`, and strings representing assertion names. If the provided assertion does not match any of these types, an `InvalidArgumentExceptio... | ```php
function applyAssertion($assertion, $result, $context) {
if (is_callable($assertion)) {
return call_user_func($assertion, $result, $context);
} elseif ($assertion instanceof AssertionInterface) {
return $assertion->assert($result, $context);
} elseif (is_string($assertion)) {
... | magicoder | php |
You are tasked with implementing a shape hierarchy in a software system. The hierarchy consists of three types of shapes: `roundishSquare`, `square`, and `circle`. Each shape has a method called `calculateArea` that returns the area of the shape. The `roundishSquare` is a special type of square that has rounded corners... | ```swift
class Shape {
func calculateArea() -> Double {
fatalError("Method calculateArea must be overridden")
}
}
class RoundishSquare: Shape {
let sideLength: Double
let cornerRadius: Double
init(sideLength: Double, cornerRadius: Double) {
self.sideLength = sideLength
self... | magicoder | swift |
You are tasked with creating a Python function that generates a 3D plot of a parametric curve. The parametric curve is defined by three functions: x(t), y(t), and z(t), where t is the parameter. Your function should take these three functions as input and produce a 3D plot of the parametric curve.
The function signatu... | ```python
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def plot_parametric_curve(x_func, y_func, z_func, t_range):
t_min, t_max = t_range
t = np.linspace(t_min, t_max, 100)
x = x_func(t)
y = y_func(t)
z = z_func(t)
fig = plt.figure()
ax = fig.a... | magicoder | python |
You are working on a data analysis project and need to create a function to group reactions into other functional groups based on given dataframes. The dataframes contain information about reactions, samples, and functional groups. Your task is to implement a function that takes two input dataframes and performs specif... | ```python
from pandas import DataFrame
def function2group(reaction_tab, f2gtab) -> DataFrame:
"""Group reactions into other functional group (EC, KO)
Args:
reaction_tab (DataFrame): reaction/sample
f2gtab (DataFrame): reaction/group
"""
g2ftab = f2gtab.transpose() # Transpose the f2gtab da... | magicoder | python |
You are tasked with implementing a function to convert a given dataset into a 2D array. The dataset is represented as a list of dictionaries, where each dictionary contains key-value pairs representing the attributes and values of a single data point. Your task is to write a Python function `dataset_to_array` that take... | ```python
def dataset_to_array(data: list) -> list:
if not data:
return []
attributes = list(data[0].keys())
result = []
for entry in data:
row = [entry[attr] for attr in attributes]
result.append(row)
return result
```
The `dataset_to_array` function first checks if the ... | magicoder | python |
You are tasked with implementing a custom testing framework for a programming language. The framework should support the creation of test suites and individual test cases, and provide a mechanism for running and reporting the results of the tests.
Your task is to implement a TestSuite class that allows users to define... | ```python
class Test:
def __init__(self, description, test_function):
self.description = description
self.test_function = test_function
def run(self):
return self.test_function()
def getDescription(self):
return self.description
class TestSuite:
def __init__(self):
... | magicoder | python |
You are tasked with creating a function that checks the version of a software tool and performs specific actions based on the version found. The function should determine if the "truffle" deployment system is available in the system's PATH and then check its version. If the version is found, the function should execute... | ```bash
check_truffle_version() {
if type -p truffle; then
echo "Found truffle executable in PATH, yay!"
_truffle=truffle
else
die "There is no truffle deployment system found."
fi
if [[ "$_truffle" ]]; then
truffle_version=$(truffle version | grep -oE '[0-9]+\.[0-9]+\.[... | magicoder | shell |
You are given a list of integers `numero_list` of length `n`. Your task is to write a function that determines whether the list is a palindrome, i.e., it reads the same forwards and backwards.
Write a function `is_palindrome(numero_list: List[int]) -> bool` that takes in a list of integers and returns `True` if the li... | ```python
from typing import List
def is_palindrome(numero_list: List[int]) -> bool:
n = len(numero_list)
for i in range(n // 2):
if numero_list[i] != numero_list[n - i - 1]:
return False
return True
```
The `is_palindrome` function takes in a list of integers `numero_list` and iterate... | magicoder | python |
You are tasked with creating a Python function that utilizes the `pyecore` and `textx` libraries to parse a simple DSL (Domain-Specific Language) and generate corresponding Python objects. The DSL represents a basic configuration language for defining shapes with attributes like color, size, and position.
Your task is... | ```python
import pyecore
import textx
from textx.metamodel import metamodel_from_str
class Shape(pyecore.ecore.EObject):
pass
class Circle(Shape):
color = pyecore.ecore.EAttribute()
radius = pyecore.ecore.EAttribute()
position = pyecore.ecore.EAttribute()
class Rectangle(Shape):
color = pyecore.e... | magicoder | python |
You are tasked with implementing a custom logging service in C#. The `Logger` class should provide functionality to log messages at different levels of severity, such as `Info`, `Warning`, and `Error`. Additionally, the logger should support the ability to write logs to different output sources, such as the console, a ... | ```csharp
using System;
namespace HandControl.Services
{
public class Logger
{
public string OutputSource { get; set; }
public void LogInfo(string message)
{
LogMessage("INFO", message);
}
public void LogWarning(string message)
{
LogMess... | magicoder | csharp |
You are tasked with implementing a generic ViewModel class for a mobile application framework. The base class `BaseViewModel` provides access to localized resources for the current language, while the derived class `BaseViewModel<TParameter>` extends the base class and implements the `IMvxViewModel<TParameter>` interfa... | ```csharp
public abstract class BaseViewModel<TParameter> : BaseViewModel, IMvxViewModel<TParameter>
{
public void Prepare(TParameter parameter)
{
// Implement parameter preparation logic here
}
public abstract Task Initialize();
public abstract Task NavigateToTarget(TParameter parameter);... | magicoder | csharp |
You are tasked with implementing a custom `SharedPtr` class in C++. The `SharedPtr` class is a smart pointer that manages the memory of a dynamically allocated object through reference counting. When multiple `SharedPtr` instances point to the same memory location, the reference count is used to track the number of `Sh... | ```cpp
#include <iostream>
template <typename T>
class SharedPtr {
private:
T* ptr;
size_t* refCount;
public:
// Constructor
explicit SharedPtr(T* p) : ptr(p), refCount(new size_t(1)) {}
// Copy constructor
SharedPtr(const SharedPtr& other) : ptr(other.ptr), refCount(other.refCount) {
... | magicoder | cpp |
You are working on a data processing system for atmospheric data collected by a remote sensing device. The system interacts with an API to download raw data and then processes it to correct any anomalies. The code snippet provided is a part of this system and shows the download process for ceilometer (CEIL) data using ... | ```python
def process_ceil_data(ceil_data):
# Calculate the median and standard deviation of CEIL measurements
ceil_measurements = [data[1] for data in ceil_data]
median_ceil = statistics.median(ceil_measurements)
std_dev_ceil = statistics.stdev(ceil_measurements)
# Define a threshold for outlier d... | magicoder | python |
You are tasked with implementing a class for adversarial attacks on image classification models. The class, named `AdversarialAttack`, has the following attributes and methods:
Attributes:
- `loss`: A string representing the loss function to be used for the adversarial attack.
- `data_name`: A string representing the ... | ```python
class AdversarialAttack:
def __init__(self, loss, data_name, device, target=False):
self.loss = loss
self.data_name = data_name
self.device = device
if self.data_name == "cifar10" and target:
raise AssertionError('cifar10 dont support targeted attack')
def ... | magicoder | python |
You are tasked with creating a program that reads data from an Excel file, performs some calculations, and then writes the results back to a new Excel file. You are provided with a sample Excel file named "input.xlsx" which contains data in the following format:
| Name | Quantity | Price |
|--------|----------|-----... | ```csharp
using Aspose.Cells;
class Program
{
static void Main(string[] args)
{
// Load input Excel file
Workbook inputWorkbook = new Workbook("input.xlsx");
Worksheet inputWorksheet = inputWorkbook.Worksheets[0];
// Create output Excel file
Workbook outputWorkbook = ne... | magicoder | csharp |
You are tasked with implementing a Python class that provides a view for interacting with Pandas DataFrames through GraphQL queries. The class should allow users to perform various operations on the DataFrame using GraphQL syntax, such as selecting specific columns, filtering rows, and aggregating data.
Your task is t... | ```python
import pandas as pd
class GraphQLPandasView:
def __init__(self, dataframe):
self.dataframe = dataframe
def execute_query(self, query):
tokens = query.split()
operation = tokens[0]
if operation == "select":
columns = tokens[2:-1]
return self.dat... | magicoder | python |
You are given a 2D grid representing a terrain map. Each cell in the grid contains a non-negative integer representing the height of the terrain at that location. You need to write a function to calculate the total water trapped within the grid.
The water trapped at a particular cell is determined by the surrounding t... | ```python
def calculateTrappedWater(grid):
if not grid or not grid[0]:
return 0
m, n = len(grid), len(grid[0])
left_max = [[0] * n for _ in range(m)]
right_max = [[0] * n for _ in range(m)]
top_max = [[0] * n for _ in range(m)]
bottom_max = [[0] * n for _ in range(m)]
for i in rang... | magicoder | python |
You are tasked with implementing a custom filter module in Python that can perform various filtering operations on a list of integers. The module should provide a set of filter functions that can be applied to the input list to produce the desired output.
Your task is to implement the following filter functions within... | ```python
class FilterModule(object):
def even_numbers(self, input_list):
return [num for num in input_list if num % 2 == 0]
def odd_numbers(self, input_list):
return [num for num in input_list if num % 2 != 0]
def positive_numbers(self, input_list):
return [num for num in input_l... | magicoder | python |
You are given a code snippet that uses Taichi, a domain-specific language for high-performance computing. Your task is to implement a function that performs a specific operation on a 2D array using Taichi.
You are given the following code snippet:
```python
m = 7
ti.root.dense(ti.i, n).dense(ti.j, m).place(val)
@ti.... | ```python
from typing import List
import taichi as ti
n = len(arr)
m = len(arr[0])
ti.init(arch=ti.cpu)
val = ti.field(dtype=ti.i32, shape=(n, m))
@ti.kernel
def test_numpy(arr: ti.ext_arr()):
for i in range(n):
for j in range(m):
arr[i, j] = arr[i, j] * arr[i, j]
def perform_square_operati... | magicoder | python |
You are working on a project that involves integrating a payment gateway into a web application. The payment gateway provides a Python SDK for interacting with its services. The SDK includes two main modules: `PushJuristek` and `Receiver`. The `PushJuristek` module is used for initiating payment requests, while the `Re... | ```python
from bipbop.client.pushjuristek import PushJuristek
from bipbop.client.receiver import Receiver
class PaymentGateway:
def __init__(self):
self.push_juristek = PushJuristek()
self.receiver = Receiver()
def initiate_payment(self, amount, customer_id):
try:
payment_r... | magicoder | python |
You are tasked with creating a script that automates the testing of a just-in-time (JIT) compiler for a programming language. The JIT compiler is responsible for dynamically compiling and executing code at runtime, and it needs to be thoroughly tested for correctness and error handling.
Your task is to write a shell s... | ```bash
#!/bin/bash
# Execute test_jit.sh and capture results
echo "Running JIT compiler functionality tests..."
if sh ${SCRIPT_PATH}/test_jit.sh; then
echo "All JIT functionality tests passed."
else
echo "Some JIT functionality tests failed."
fi
# Execute test_errors.sh and capture results
echo "Running JIT comp... | magicoder | shell |
You are tasked with creating a Python function that processes a General Transit Feed Specification (GTFS) dataset and stores it in a SQL database. The GTFS dataset contains public transportation information such as routes, stops, and schedules. Your function should take a list of GTFS files as input and convert them in... | ```python
import sqlite3
import csv
from typing import List
def SQLize_GTFS(files_to_sqlize: List[str]) -> None:
try:
conn = sqlite3.connect('gtfs_database.db')
cursor = conn.cursor()
for file in files_to_sqlize:
table_name = file.split('.')[0] # Use file name as table name
... | magicoder | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.