query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are given a list of integers `list_data` and an index `pivot_index`. Your task is to write a function `find_pivot_value` that returns the value at the pivot index in the list. If the pivot index is out of range, the function should return "Index out of range".
For example, given the list `list_data = [3, 7, 2, 8, ... | ```python
from typing import List, Union
def find_pivot_value(list_data: List[int], pivot_index: int) -> Union[int, str]:
if pivot_index < 0 or pivot_index >= len(list_data):
return "Index out of range"
else:
return list_data[pivot_index]
``` | magicoder | python |
You are tasked with implementing a custom error handling system for a networking library in Rust. The provided code snippet defines an enum `AdvertiseError` that represents various errors that can occur during the advertisement process. The `AdvertiseError` enum has three variants: `Timeout`, `NoFreeConn`, and `Raw`, w... | ```rust
/// Error for [`advertise_start`]
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum AdvertiseError {
Timeout,
NoFreeConn,
Raw(RawError),
}
// Define the RawError type for demonstration purposes
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
st... | magicoder | rust |
You are given a string representing a sequence of integers separated by commas. Each integer represents an opcode for an Intcode program. The Intcode program is a list of integers separated by commas, where each integer represents an opcode and its parameters. The opcode indicates the action to be taken, and the parame... | ```rust
fn process_intcode(program: &str) -> i32 {
let mut intcode: Vec<i32> = program
.split(',')
.map(|x| x.parse().unwrap())
.collect();
let mut i = 0;
loop {
match intcode[i] {
1 => {
let pos1 = intcode[i + 1] as usize;
let pos... | magicoder | rust |
You are tasked with creating a Python class that processes data related to photovoltaic systems. The class should read and store data from CSV files, perform temperature modeling, and load additional data if specified. Your task is to implement the missing parts of the Python class `PVSystem` as described below.
```py... | ```python
import os
import pandas as pd
import pvlib
class PVSystem:
def __init__(self, load_module_data=True):
# Read and store module and inverter data from CSV files
self.modules = pd.read_csv(
os.path.join(utils.HISIMPATH["photovoltaic"]["modules"]),
index_col=0,
... | magicoder | python |
You are tasked with creating a function that processes a given configuration object to construct a URL. The configuration object contains information about data sources and their corresponding load URLs. Your task is to implement a function that takes this configuration object and returns the constructed URL.
The conf... | ```rust
use std::path::Path;
struct DataSource {
load_url_with_config_dir: fn(&Path, bool) -> String,
}
struct Config {
subject: SubjectConfig,
}
struct SubjectConfig {
datasources: Vec<DataSource>,
}
fn construct_url(config: &Config, config_dir_path: &Path, from_env: bool) -> String {
if let Some(f... | magicoder | rust |
You are tasked with implementing a Python function that processes and manipulates text data. The function should take a string as input and perform a specific transformation on it. Your task is to write a function that replicates the behavior of the given code snippet.
The function should take a string as input and re... | ```python
def process_text(input_string):
modified_string = input_string.replace("With output:", "Processed output:")
modified_string = modified_string.replace("--------------", "==============")
modified_string = modified_string.replace("frombytes", "tostring")
return modified_string
```
The `process_... | magicoder | python |
You are tasked with creating a program to monitor the health status of a system. The program will take in a series of health measurements and determine if the system is unhealthy based on a given threshold. The health measurements are represented as integers, and the unhealthy threshold is a positive integer provided a... | ```python
from typing import List
def is_system_unhealthy(health_measurements: List[int], unhealthy_threshold: int) -> bool:
consecutive_unhealthy_count = 0
for measurement in health_measurements:
if measurement == 0: # Assuming 0 indicates an unhealthy measurement
consecutive_unhealthy_co... | magicoder | python |
You are given a list of items, each with a weight and a value. Your task is to implement a function `knapsackMethod(items, capacity)` that solves the 0/1 knapsack problem using a greedy approach. The function should return the maximum total value that can be obtained by selecting a subset of the items such that the tot... | ```python
class Item:
def __init__(self, weight, value):
self.weight = weight
self.value = value
self.ratio = value / weight
def knapsackMethod(items, capacity):
items.sort(key=lambda x: x.ratio, reverse=True)
usedCapacity = 0
totalValue = 0
for item in items:
if use... | magicoder | python |
You are working on a cloud management system and need to implement a feature for installing system templates. The system uses a unique identifier for each template and downloads the template from a specified URL before installing it. After installation, the system writes properties and prints a success message. You nee... | ```python
import uuid
class TemplateInstaller:
def __init__(self, templatesuffix, args):
self.templatesuffix = templatesuffix
self.args = args
def generateUniqueIdentifier(self):
return str(uuid.uuid1())
def constructTemplateName(self, uniqueIdentifier):
return uniqueIdent... | magicoder | python |
You are tasked with implementing a trait in PHP that handles the processing of request parameters for a web application. The trait, named `Post`, should include methods for validating and sanitizing the incoming POST parameters. Additionally, it should handle any errors that occur during the parameter processing and pr... | ```php
use \ErrorCode;
trait Post {
protected $errorCode;
public function validateParams($params) {
// Implement parameter validation logic
// Set error code if validation fails
}
public function sanitizeParams($params) {
// Implement parameter sanitization logic
}
pu... | magicoder | php |
You are tasked with implementing a method to merge two JSON objects into a single map and then using this merged map to create a specific data structure. The method `merge` takes two JSON objects `values` and `values1` and merges their key-value pairs into a single map. The method `toTableToTableDependenciesDataMap` ta... | ```java
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.TableData;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
public class DataProcessor {
private Map<String, Object> merge(JsonObject values, JsonObject values1) {
LinkedHashMap<String, ... | magicoder | java |
You are working on a project that involves implementing a module for electronic structure calculations in materials science. As part of this project, you need to develop a function that handles the creation of an auxiliary basis for a given molecular basis. The function should also handle the specification of the numbe... | ```python
import numpy
from pyscf.pbc.df import mdf
def create_auxiliary_basis(mol_basis, aux_basis, mesh, with_df):
if with_df is None:
if hasattr(mf, 'kpts'):
kpts = mf.kpts
else:
kpts = numpy.reshape(mf.kpt, (1,3))
# Further implementation of the function goes here
... | magicoder | python |
You are tasked with optimizing the given code snippet, which currently contains nested loops iterating over a large range of values. Your goal is to refactor the code to improve its efficiency and reduce the time complexity.
Given the code snippet:
```
#
# col = db.order
# db.order.create_index("uid")
#
# for i in ran... | To optimize the given code snippet, we can utilize the index created on the "uid" field to improve the efficiency of the nested loops. By leveraging the index, we can directly access the required data without the need for nested iterations.
Refactored code:
```python
# col = db.order
# db.order.create_index("uid")
# ... | magicoder | python |
You are tasked with implementing a function to count the occurrences of a specific pattern in a given array of integers. The pattern to be matched is "3-2-1-1", which means that the array should contain three identical elements, followed by two identical elements, and then one distinct element, and finally another dist... | ```swift
func countPatternOccurrences(_ arr: [Int]) -> Int {
var count = 0
for i in 0..<(arr.count - 5) {
if arr[i] == arr[i + 1] && arr[i] == arr[i + 2] && arr[i + 3] == arr[i + 4] && arr[i + 4] != arr[i + 5] {
count += 1
}
}
return count
}
```
The solution defines a functi... | magicoder | swift |
You are working on a machine learning optimization library and need to implement a method to return the optimums in a score model. The `get_optimums` method takes three parameters: `model`, a score model to be analyzed, `size`, the number of optimums to be returned, and `excludes`, a list of indices to be excluded from... | ```python
def get_optimums(self, model, size, excludes):
"""Return optimums in score model."""
# Initialize an empty list to store the optimums
optimums = []
# Loop until the number of optimums collected is equal to the specified size
while len(optimums) < size:
# Get categorical parame... | magicoder | python |
You are tasked with implementing a custom smart pointer type in Rust, similar to `Rc` (reference-counted) but with additional functionality. Your task is to create a new smart pointer type called `CustomRc` that has the following features:
1. It should have a field `inner` of type `Rc<T>` where `T` is the type being p... | ```rust
use std::rc::Rc;
use std::ops::Deref;
#[derive(Debug, Clone, PartialEq)]
pub struct CustomRc<T> {
inner: Rc<T>,
}
impl<T> CustomRc<T> {
// Create a new CustomRc pointing to the given value
pub fn new(value: T) -> Self {
CustomRc {
inner: Rc::new(value),
}
}
// ... | magicoder | rust |
You are tasked with implementing a function to calculate the average density of a set of chemical compounds based on experimental data. The function should take in a list of job objects, each containing experimental results for a specific compound, and return the average density of the compounds.
Each job object has t... | ```python
import json
import matplotlib.pyplot as plt
def calculate_average_density(jobs, plot_fail=False):
n_mols = [json.loads(job.result)['n_mols'] for job in jobs]
assert len(set(n_mols)) == 1, "Number of moles is not consistent across compounds"
T_list = [job.T for job in jobs]
P_list = [job.... | magicoder | python |
You are tasked with implementing a simplified version of a message loop system similar to the one used in Windows programming. The provided code snippet is a part of a C++ class `CDialogMessageLoop` that is responsible for processing messages for a dialog window. The class has a constructor, a destructor, and a method ... | ```cpp
#include <windows.h>
class CDialog {
public:
bool IsDialogMessage(LPMSG msg) {
// Implementation not shown
return true;
}
};
class CDialogMessageLoop {
private:
CDialog& _dialog;
const UINT exitMessage = WM_QUIT;
public:
CDialogMessageLoop(CDialog& dialog) : _dialog(dialog)... | magicoder | cpp |
You are tasked with creating a command-line utility that simulates the behavior of the `tini` process manager. The `tini` utility is used to adopt and re-parent orphaned processes, ensuring that they are properly managed within the process hierarchy. Your task is to implement a simplified version of this utility in Pyt... | ```python
import os
import signal
import subprocess
import sys
def adopt_and_reparent(command, args):
try:
# Create a new process using the specified command and arguments
child = subprocess.Popen([command] + args)
# Monitor the child process and re-parent it if it becomes orphaned
... | magicoder | python |
You are tasked with implementing a custom sorting algorithm for a specific set of data. The data consists of financial records, each containing information about a fiscal year and its corresponding financial data. The records are represented as dictionaries with the following structure:
```python
{
'fiscal_year': ... | ```python
def custom_sort(records):
leap_year_records = []
non_leap_year_records = []
for record in records:
if record['fiscal_year'] % 4 == 0 and (record['fiscal_year'] % 100 != 0 or record['fiscal_year'] % 400 == 0):
leap_year_records.append(record)
else:
non_l... | magicoder | python |
You are tasked with implementing a custom error handling system in Rust. Your goal is to create a macro that generates error handling code for a given type. The macro should generate an implementation of the `std::error::Error` trait for the specified type and provide a `from` macro for converting other error types int... | ```rust
macro_rules! error {
($typ:ty) => {
impl ::std::error::Error for $typ {
}
};
}
macro_rules! from {
($src:ty, $target:ty) => {
impl From<$src> for $target {
fn from(err: $src) -> Self {
// Convert the source error to the target error type
... | magicoder | rust |
You are tasked with creating a program to parse and extract information from HTML code. Specifically, you need to extract the labels and corresponding input types from the given HTML snippet.
Write a function `extractHTMLInfo(html)` that takes a string `html` representing the HTML code as input and returns a dictionar... | ```python
import re
def extractHTMLInfo(html):
pattern = r'<label for="(\w+)" class="control-label">(\w+)</label>\s+<input type="(\w+)"'
matches = re.findall(pattern, html)
info_dict = {}
for match in matches:
label_for, label_text, input_type = match
info_dict[label_text] = input_type
... | magicoder | python |
You are tasked with implementing a simplified version of an entity persistence system. The system consists of an `Entity` class, a `Repository` class, and a `Value` class. The `Entity` class represents an entity to be persisted, the `Repository` class is responsible for persisting entities, and the `Value` class repres... | ```java
import org.mockito.Mockito;
public class Entity {
private Repository repository;
private Value originalValue;
private Value modifiedValue;
private boolean persisted;
public Entity(Repository repository) {
this.repository = repository;
}
public Value modify() {
orig... | magicoder | java |
You are tasked with creating a multithreaded C# program that simulates a simple ticket booking system for a concert. The program should utilize the `System.Threading.Tasks` namespace to handle concurrent ticket bookings.
The concert venue has a limited capacity of 1000 seats, and the ticket booking system should allo... | ```csharp
using System;
using System.Threading.Tasks;
namespace ConcertBookingSystem
{
public class TicketBookingSystem
{
private object lockObject = new object();
private int availableTickets = 1000;
public async Task<bool> BookTickets(int numTickets)
{
bool bookin... | magicoder | csharp |
You are tasked with implementing a Java class that represents a tree node for a scenery in a video game. The provided code snippet is a part of the implementation of the `SceneryTreeNode` class. The class extends a superclass `Node` and has a private field `node` of type `Node`. The `toString` method is overridden to r... | ```java
public int countNodes() {
int count = 1; // Count the current node
for (SceneryTreeNode child : getChildren()) {
count += child.countNodes(); // Recursively count nodes in the subtree
}
return count;
}
```
In the `countNodes` method, we initialize a count with 1 to account for the curre... | magicoder | java |
You are tasked with creating a simple dependency injection framework for a Java application. The framework should support the injection of dependencies into various components of the application. To achieve this, you need to implement the core functionality of the dependency injection framework using annotations and re... | ```java
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
public class DependencyInjector {
private Map<Class<?>, Object> singletonInstances = new HashMap<>();
public void processAnnotations(Object target) {
Class<?> targetClass = target.getClass();
if (targetClas... | magicoder | java |
You are tasked with creating a script to automate the encryption and upload of JSON files to an AWS S3 bucket using AWS Encryption CLI and AWS KMS for key management. Your script should take a directory path as input and perform the following steps for each JSON file in the directory:
1. Encrypt the JSON file using AWS... | ```bash
#!/bin/bash
# Retrieve S3 bucket name from AWS resources
s3_bucket=$(aws ec2 describe-tags --filters Name=key,Values=s3_bucket | jq --raw-output '.Tags[0].Value')
# Retrieve S3 output path from AWS resources
s3_output_path=$(aws ec2 describe-tags --filters Name=key,Values=s3_out | jq --raw-output '.Tags[0].Va... | magicoder | shell |
You are tasked with implementing a simplified version of a counter system for tracking and processing interactions. The system consists of a `CounterBasket` class, a `CountStat` class, and a method for gathering and sending interaction counters. The `gatherAndSendCounter` method iterates through a list of `CountStat` o... | ```java
interface Counter {
long interval();
void process(CounterBasket basket);
}
class CounterBasket {
void process(CountStat stat) {
// Update the counter values in the basket based on the provided CountStat
// Example: Increment the corresponding counter values in the basket
}
}
cl... | magicoder | java |
You are tasked with implementing a function that takes a list of software versions and generates a formatted string representing the versions. The function should handle cases where the input list is null or empty.
You are given the following code snippet as a starting point:
```csharp
string versions = null;
if (Ver... | ```csharp
using System;
using System.Linq;
using System.Collections.Generic;
public class VersionFormatter
{
public static string GenerateVersionString(List<string> Versions)
{
if (Versions == null || Versions.Count == 0)
{
return "No versions available";
}
else
... | magicoder | csharp |
You are tasked with implementing a simple drawing program using the provided code snippet as a starting point. The code snippet is part of a Swift program that sets up a scene for drawing and provides functions for controlling a sprite to create drawings. Your task is to extend this program to draw a specific shape.
Y... | ```swift
public func drawSquare() {
penDown()
for _ in 1...4 {
moveForward(100)
turnRight(90)
}
penUp()
}
```
In the `drawSquare()` function, the `penDown()` function is called to start drawing. Then, a loop is used to move the sprite forward by 100 units and turn it right by 90 degrees ... | magicoder | swift |
You are tasked with creating a Python function that reads settings from a JSON file and performs specific operations based on the settings. The settings are stored in a file named "roots-settings.json" and include the following fields:
- "input_folder": a string representing the path to the input folder
- "document_cou... | ```python
import json
import logging
import sys
def process_settings():
"""
Reads settings from 'roots-settings.json' and processes them.
Returns:
dict: A dictionary containing the processed settings.
"""
with open('roots-settings.json') as data_file:
data = json.load(data_file)
... | magicoder | python |
You are tasked with implementing a role-based access control system for a database. The system should allow or deny access to specific database resources based on the roles assigned to a user. You are given a code snippet that represents a method call to query the database for the grants assigned to a user.
The method... | ```python
class AccessControlSystem:
def __init__(self, db):
self.db = db
self.role_grants = {
'admin': ['read', 'write', 'delete'],
'manager': ['read', 'write'],
'analyst': ['read']
}
self.user_roles = {
'user1': ['admin', 'manager'],
... | magicoder | python |
You are tasked with creating a function that validates email addresses for a password reset feature in a mobile application. The function should take an email address as input and return a boolean value indicating whether the email address is valid for password reset. An email address is considered valid if it meets th... | ```swift
func validateEmailForPasswordReset(email: String) -> Bool {
let emailRegex = try! NSRegularExpression(pattern: "^[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$", options: .caseInsensitive)
let trimmedEmail = email.trimmingCharacters(in: .whitespaces)
let range = NSRange(location: 0, length: trimm... | magicoder | swift |
You are tasked with implementing a C++ program that manipulates a data structure representing a packed and unpacked version of a specific struct. The struct definition is provided as a code snippet below:
```cpp
#define P __attribute__((packed))
#else
#define P
#endif
struct UnPacked {
int X;
// ... other mem... | ```cpp
#include <iostream>
#define P __attribute__((packed))
#else
#define P
#endif
struct UnPacked {
int X;
// ... other members
};
struct Packed PackedStruct {
int X;
// ... other members
};
Packed packStruct(const UnPacked& unpacked) {
Packed packed;
packed.X = unpacked.X;
// ... pack... | magicoder | cpp |
You are given a code snippet containing Swift code. Your task is to analyze the code and identify the errors, missing components, and potential improvements.
Your specific tasks are as follows:
1. Identify and correct any syntax errors in the code.
2. Identify and correct any logical errors in the code.
3. Add missin... | The given code snippet contains several syntax errors and incomplete components. Let's analyze and correct the issues step by step.
1. Syntax Errors:
- The function `j` is missing its parameter list and return type declaration.
- The class method `j` is missing its implementation.
- The `d` function is missin... | magicoder | swift |
You are tasked with creating a Python function that retrieves and processes data from a web API to obtain information about stock market indices. The function should make an HTTP request to a specific URL, parse the JSON response, and then return a processed result as a pandas DataFrame.
Write a function `fetch_index_... | ```python
import requests
import pandas as pd
def fetch_index_data() -> pd.DataFrame:
try:
url = "http://www.cnindex.com.cn/index/indexList"
response = requests.get(url)
response.raise_for_status() # Raise an exception for 4xx or 5xx status codes
data = response.json()
# A... | magicoder | python |
You are tasked with creating a Python function that processes vehicle status changes based on a given input. The function should take in a list of vehicle documents and update their status and reference document name based on certain conditions. Each vehicle document is represented as a dictionary with the following ke... | ```python
from typing import List, Dict
def process_vehicle_status(vehicle_docs: List[Dict[str, str]], action: str) -> List[Dict[str, str]]:
for vehicle_doc in vehicle_docs:
if action == "reserve":
vehicle_doc["vehicle_status"] = "Reserved"
vehicle_doc["reference_doc_name"] = "R001"... | magicoder | python |
You are tasked with creating a PHP class that manages courses and their enrollment. The class should include methods to add a new course, enroll a student in a course, and retrieve the list of enrolled students for a given course. The course and student data will be stored in a MySQL database using Doctrine ORM.
Your ... | ```php
<?php
use Doctrine\ORM\EntityManagerInterface;
class CourseManager
{
private $entityManager;
public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
}
public function addCourse($courseName)
{
$course = new Course();
... | magicoder | php |
You are tasked with creating a program that parses a given HTML file and extracts the URLs present in the anchor (`<a>`) tags. The program should then output the unique URLs in alphabetical order.
For example, given the following HTML snippet:
```html
<div class="col-xl-3 col-md-6 mb-4">
<div class="card border-left... | ```python
from bs4 import BeautifulSoup
import requests
from urllib.parse import urljoin
def extract_unique_urls(html_content):
soup = BeautifulSoup(html_content, 'html.parser')
anchor_tags = soup.find_all('a')
urls = set()
for tag in anchor_tags:
href = tag.get('href')
if href and href... | magicoder | python |
You are tasked with creating a Python function that processes statistical data from a set of pickle files and populates a pandas DataFrame with the results. The function should take in the path to a directory containing the pickle files, and the list of types for which the statistics are to be computed. The function sh... | ```python
import pandas as pd
import pickle
from typing import List
def process_stats(directory_path: str, type_list: List[str]) -> pd.DataFrame:
metrics = pd.DataFrame(columns=['source_type', 'target_type', 'stats'])
for source_type in type_list:
for target_type in type_list:
logs_path = f... | magicoder | python |
You are given a code snippet that appears to be part of a function for calculating the IoU (Intersection over Union) metric for bounding boxes. The code snippet uses the PyTorch library to initialize a tensor `cious` with zeros, and then performs some conditional checks and variable assignments based on the shapes of i... | ```python
import torch
def calculate_iou(bboxes1, bboxes2):
rows, cols = bboxes1.shape[0], bboxes2.shape[0]
cious = torch.zeros((rows, cols))
if rows * cols == 0:
return cious
exchange = False
if bboxes1.shape[0] > bboxes2.shape[0]:
bboxes1, bboxes2 = bboxes2, bboxes1
ciou... | magicoder | python |
You are tasked with implementing a pagination algorithm for a list of S3 inputs in a PHP application. The `S3InputPaginationResponse` class is provided as a starting point, and you need to complete the implementation by adding pagination functionality to retrieve and display the S3 inputs in a controlled manner.
Your ... | The `getNextPage()` method calculates the start and end indices of the next page based on the current page and page size. It then returns the subset of S3 inputs within the specified range. The `getPreviousPage()` method calculates the start and end indices of the previous page and returns the corresponding subset of S... | magicoder | php |
You are tasked with implementing a program that processes a given text to extract and count the occurrences of unique words. The program should ignore punctuation marks and consider words in a case-insensitive manner. Additionally, the program should exclude any common English stop words from the word count.
You are p... | ```python
import sys
import re
from collections import Counter
def word_count(text):
# Convert text to lowercase and remove punctuation
text = re.sub(r'[^\w\s]', '', text.lower())
# Define common English stop words
stop_words = {'a', 'an', 'the', 'in', 'on', 'at', 'to', 'for', 'of', 'and', 'or', '... | magicoder | python |
You are tasked with implementing a custom data structure in Java called `ReanimatedArray`. This data structure should extend the `WritableArray` interface and implement the `ReadableArrayResolver.Resolvable` interface. The `ReanimatedArray` should support the addition of dynamic values using the `pushDynamic` method.
... | ```java
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.ReadableArrayResolver;
public interface ReanimatedArray extends WritableArray, ReadableArrayResolver.Resolvable {
void pushDynamic(Object value);
// Implementing the pushDynamic method
default void pushDynamic(Object ... | magicoder | java |
You are tasked with implementing a system for managing game components in a game engine. The game engine uses the Bevy framework, which employs a stage-based system for executing systems. Each stage represents a specific phase of the game loop, such as updating, rendering, and post-processing.
The provided code snippe... | ```rust
use bevy::prelude::*;
// Define a custom component for the game
struct CustomComponent;
// Define a resource to store removed components for reaction
struct RemovedComponents(Vec<Entity>);
fn main() {
App::build()
.add_plugins(DefaultPlugins)
.add_startup_system(setup.system())
.a... | magicoder | rust |
You are tasked with creating a TypeScript function that takes in a React component and returns a new component with additional functionality. The input component is of type `FC<BannerProps>`, which is a functional component that accepts `BannerProps` as its props. Your task is to implement a function that takes this co... | ```typescript
import React, { FC, ReactElement } from 'react';
interface BannerProps {
// Define the original props for the Banner component
// ...
}
interface EnhancedBannerProps extends BannerProps {
showCloseButton: boolean;
onClose: () => void;
}
export type BannerFunctionType = FC<BannerProps>;
functio... | magicoder | typescript |
You are tasked with implementing a function to convert a given duration in seconds into a human-readable format. The function should take an integer representing the duration in seconds and return a string representing the duration in the format "X hours, Y minutes, Z seconds". If a unit of time is not present in the d... | ```rust
use std::time::Duration;
fn format_duration(seconds: u64) -> String {
if seconds == 0 {
return "now".to_string();
}
let mut remaining_seconds = seconds;
let mut result = String::new();
let units = [("year", 60 * 60 * 24 * 365), ("day", 60 * 60 * 24), ("hour", 60 * 60), ("minute", 6... | magicoder | rust |
You are working on a project that involves using TensorFlow for matrix operations. You are given two matrices, m1 and m2, both of shape [batch_size, height, width]. Your task is to implement a function that takes these two matrices as input and performs the following operations using TensorFlow:
1. Calculate the sum o... | ```python
# Sample usage
import tensorflow as tf
# Create sample matrices
m1 = tf.constant([[[1, 2], [3, 4]], [[5, 6], [7, 8]]], dtype=tf.float32)
m2 = tf.constant([[[2, 3], [4, 5]], [[6, 7], [8, 9]]], dtype=tf.float32)
# Perform the matrix operation
result = matrix_operation(m1, m2)
# Start a TensorFlow session and... | magicoder | python |
You are tasked with implementing a file monitoring system in a macOS application using the NSFilePresenter protocol. The NSFilePresenter protocol is used to monitor changes to files and directories in a coordinated manner. Your goal is to create a class that conforms to the NSFilePresenter protocol and handles the noti... | ```swift
import Foundation
class FileMonitor: NSObject, NSFilePresenter {
var presentedItemURL: URL?
func presentedItemDidChange() {
// Handle the change to the presented item (file or directory)
}
func presentedSubitem(at url: URL, didChange change: NSFilePresenter.FilePresenterChang... | magicoder | swift |
You are tasked with creating a Rust module system for a cryptographic library. The code snippet provided is a simplified representation of the module structure for the library. Your goal is to design the module hierarchy and define the necessary modules to implement a basic cryptographic scheme.
Your task is to create... | ```rust
// Define the module hierarchy and relationships
mod aggregate {
// Implementation for cryptographic proof or key aggregation
}
mod ext {
// Extensions and utility functions for cryptographic operations
}
mod generator {
// Implementation for generating cryptographic parameters or keys
}
mod mapp... | magicoder | rust |
You are tasked with implementing a garbage classification system using a pre-trained neural network model. The system is designed to classify images of garbage into different categories using a specified backbone model and training on a GPU. Your task is to complete the implementation by defining the `GarbageClassifica... | ```python
class GarbageClassification:
def __init__(self, backbone, gpu, logname):
self.backbone = backbone
self.gpu = gpu
self.logname = logname
def set_environment(self):
# Set up environment for training
print(f"Setting up environment for training with {self.backbone}... | magicoder | python |
You are tasked with creating a RESTful API for managing medical specialties using Django and Django REST framework. Your goal is to implement the necessary viewsets and routes to support CRUD (Create, Read, Update, Delete) operations for medical specialties.
Your task is to complete the implementation of the `Especial... | ```python
from rest_framework import viewsets
from rest_framework import routers
from django.urls import path, include
from .views import EspecialidadeViewSet
# Define the viewset for handling CRUD operations on medical specialties
class EspecialidadeViewSet(viewsets.ModelViewSet):
queryset = Especialidade.objects... | magicoder | python |
You are given a list of strings representing a reverse Polish notation expression. Reverse Polish notation (RPN) is a mathematical notation in which every operator follows all of its operands. The list of strings contains either operands or operators. The operators are "+", "-", "*", and "/". You need to evaluate the R... | ```python
def evaluateRPN(tokens):
stack = []
for token in tokens:
if token in "+-*/":
b = stack.pop()
a = stack.pop()
if token == "+":
stack.append(a + b)
elif token == "-":
stack.append(a - b)
elif token == "*"... | magicoder | python |
You are tasked with implementing a simple animation system for a graphical user interface. The system should allow for the creation and execution of animations on various UI elements. Each animation should be defined by a set of keyframes, and the system should be able to interpolate between these keyframes to produce ... | ```swift
class UIAnimation {
var keyframes: [(time: Double, properties: [String: Any])] = []
var isPlaying: Bool = false
var targetView: UIView // Assuming a UIView as the target UI element
init(targetView: UIView) {
self.targetView = targetView
}
func addKeyframe(time: Double, propert... | magicoder | swift |
You are tasked with creating a bash script that automates the process of running unit tests for a given repository. Your script should be able to clone the repository, install any necessary dependencies, and execute the unit tests. The repository to be tested is specified by the `<reponame>` placeholder in the code sni... | ```bash
#!/usr/bin/env bash
set -e
REPO="AlexAvlonitis/facter-ng"
CLONE_DIR="facter-ng"
# Step 1: Clone the specified repository from GitHub
git clone "https://github.com/$REPO.git" "$CLONE_DIR"
# Step 2: Navigate into the cloned repository directory
cd "$CLONE_DIR"
# Step 3: Install any necessary dependencies req... | magicoder | shell |
You are tasked with implementing a network communication protocol for a simple messaging application. The application uses a client-server architecture, where the server listens for incoming connections and the client connects to the server to send and receive messages.
The provided code snippet is a part of the serve... | ```java
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
public class Server {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8080);
while (true... | magicoder | java |
You are tasked with implementing a custom debugging feature for a shell script. The provided code snippet contains a line that sets the `PS4` environment variable, which is used to customize the debugging output in Bash scripts. The `PS4` variable is a string that is displayed before each command when the `set -x` opti... | ```bash
# Define the custom_debug function
custom_debug() {
# Enable debugging
set -x
# Execute the provided command
eval "$1"
# Check the exit status of the command
if [ $? -ne 0 ]; then
echo "Error: Command execution failed"
fi
# Disable debugging
set +x
}
# Test the custom_debug function
custo... | magicoder | shell |
You are working on a grid manipulation library that deals with grid ranges and columns. The library contains a method `FilterColumns` that filters the columns of a grid based on a given predicate function. The `FilterColumns` method takes a predicate function as an argument and returns a filtered list of grid columns.
... | ```csharp
internal IConcatList<GridColumn> FilterColumns(Func<GridColumn, bool> predict, Action<GridColumn> action = null)
{
Debug.Assert(!IsEmpty); // Ensure that the grid range is not empty
// Filter the columns based on the given predicate function within the specified grid range
return Template.Intern... | magicoder | csharp |
You are tasked with implementing a Python class that manages a collection of points in a 3D space. The class should provide methods for adding points, accessing point colors, and preparing transformations for rendering. Your task is to complete the implementation of the class by adding the missing functionality for set... | ```python
class PointManager:
def __init__(self):
self.points = [] # List to store points in 3D space
self._draw_mode = None # Mode for drawing points
self._index_buffer = None # Buffer for indices
def append(self, *args, **kwargs):
# Add a new point to the collection
... | magicoder | python |
You are given a binary tree data structure and two methods defined for the tree: `get_max_in_binary_tree` and `print_k_dist_nodes`. The `get_max_in_binary_tree` method is used to find the maximum value in the binary tree, while the `print_k_dist_nodes` method is used to print all nodes at distance `k` from the root nod... | ```python
class TreeNode:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
class BinaryTree:
def __init__(self):
self.root = None
def print_k_dist_nodes(self, root, k):
if root is None:
return
if k == 0:
prin... | magicoder | python |
You are tasked with creating a Python function that generates a migration script for a hypothetical database migration tool. The migration script should take in two parameters: a list of tuples representing the current state of the database tables and a list of tuples representing the desired state of the database tabl... | ```python
def generate_migration_script(current_state, desired_state):
migration_script = ""
# Tables to be created
for table, columns in desired_state:
if table not in [t[0] for t in current_state]:
migration_script += f"CREATE TABLE {table} ({', '.join(columns)});\n"
# Tables to ... | magicoder | python |
You are tasked with implementing a Python class to parse and process APDU (Application Protocol Data Unit) commands used in the Zcash cryptocurrency protocol. The provided code snippet contains a list of `LedgerjsApdu` objects, each representing a specific APDU command for interacting with a Zcash ledger. Your task is ... | ```python
class ZcashAPDUParser:
def parse_commands(self, apdu_commands):
parsed_commands = {}
for apdu in apdu_commands:
for command in apdu.commands:
command_type = self.identify_command_type(command)
if command_type in parsed_commands:
... | magicoder | python |
You are tasked with implementing a command-line argument parser for a C++ program. The argument parser should support parsing various types of command-line arguments, such as flags, options, and positional arguments.
Your task is to implement a class `ArgumentParser` with the following requirements:
1. The class shou... | ```cpp
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <set>
class ArgumentParser {
public:
void add_flag(const std::string& flag) {
flags.insert(flag);
}
void add_option(const std::string& option, const std::string& description) {
options[option] = descript... | magicoder | cpp |
You are tasked with creating a program to manage shipping orders. The program should include a method to create a new shipping order based on various parameters such as sender, recipient, weight, and shipping cost. You are provided with a code snippet that outlines the creation of a shipping order using the given param... | ```java
public Envio crear(ComandoEnvio comandoEnvio, RepositorioUsuario repositorioUsuario,
RepositorioCostoEnvio repositorioCostoEnvio, RepositorioDiasEspera repositorioDiasEspera) {
Usuario remitente = repositorioUsuario.optenerPorCedula(comandoEnvio.getCedulaRemitente());
Usuario destina... | magicoder | java |
You are tasked with implementing a function that takes a list of integers as input and returns the maximum sum of a contiguous subarray within the input list. The function should efficiently handle both positive and negative integers.
You need to implement the following function:
```python
def max_subarray_sum(nums: ... | ```python
from typing import List
def max_subarray_sum(nums: List[int]) -> int:
max_sum = float('-inf')
current_sum = 0
for num in nums:
current_sum = max(num, current_sum + num)
max_sum = max(max_sum, current_sum)
return max_sum
```
The solution uses Kadane's algorithm to ef... | magicoder | python |
You are given a string `s` and an integer `nRows`. Your task is to write a function that converts the input string into a zigzag pattern with a specified number of rows. The zigzag pattern is formed by writing the characters of the string in a zigzag pattern and then reading them out row by row.
For example, if the in... | ```python
def convertToZigzag(s: str, nRows: int) -> str:
if nRows == 1 or nRows >= len(s):
return s
res = [''] * nRows
index, step = 0, 1
for char in s:
res[index] += char
if index == 0:
step = 1
elif index == nRows - 1:
step = -1
index ... | magicoder | python |
You are working on a project that involves interacting with a database using the QxOrm library in C++. As part of this project, you need to implement a function that retrieves and saves data with relations in the database. The QxOrm library provides various methods for fetching, saving, and invoking functions using ref... | ```cpp
#include <QxOrm.h>
// Define a structure for blog data
class Blog {
public:
QString blog_text;
Author author;
QList<Comment> ListComment;
};
// Define a structure for author data
class Author {
public:
QString name;
QDate birthday;
QString sex;
int age() {
// Method to calcu... | magicoder | cpp |
You are working on a data processing pipeline that involves validating a destination table format and then converting an XML file to entities. The `bq_table_format_validator` function is responsible for validating the format of the destination table, and the `xml2entities.main` function is used to convert the XML file ... | ```python
def bq_table_format_validator(dest):
# Assuming the destination table format should start with 'table_' and contain only alphanumeric characters and underscores
if dest.startswith('table_') and dest.replace('_', '').isalnum():
return dest
else:
raise ValueError("Invalid destination... | magicoder | python |
You are tasked with implementing a cache data structure that supports the following operations: `setValue` and `getValue`. The cache should have a maximum capacity, and if the number of elements exceeds this capacity, the least recently used item should be evicted.
The `setValue` function takes a key-value pair and st... | ```swift
class DoublyLinkedListNode<Key, Value> {
var payload: CachePayload<Key, Value>
var prev: DoublyLinkedListNode?
var next: DoublyLinkedListNode?
init(payload: CachePayload<Key, Value>) {
self.payload = payload
}
}
class DoublyLinkedList<Key, Value> {
private var head: Doubly... | magicoder | swift |
You are tasked with implementing a function to validate a Sudoku board. A Sudoku board is a 9x9 grid, where each row, column, and 3x3 subgrid must contain the numbers 1-9 without repetition. You are given a code snippet that checks if the input sequence representing a row, column, or subgrid contains 9 elements. Your t... | ```csharp
bool IsValidSudoku(char[][] board)
{
for (int i = 0; i < 9; i++)
{
if (!IsValidSequence(GetRow(board, i)) ||
!IsValidSequence(GetColumn(board, i)) ||
!IsValidSequence(GetSubgrid(board, i / 3 * 3, i % 3 * 3)))
{
return false;
}
}
ret... | magicoder | csharp |
You are tasked with implementing a function that decodes a JSON string into a Swift object and performs specific validations on the decoded data. The JSON data represents a dictionary with string keys and nested JSON objects as values. Your task is to write a function that decodes the JSON data and checks for the follo... | ```swift
import Foundation
func validateAndDecodeJSON(_ jsonString: String) -> Bool {
guard let data = jsonString.data(using: .utf8) else {
return false
}
do {
let object = try JSONDecoder().decode([String: Any].self, from: data)
if object.isEmpty {
return false
... | magicoder | swift |
You are tasked with implementing a function to process and save a report based on a given source, record type counts, and any errors encountered during the process. The function should take in the source data, report data, record type counts, and errors as input and return a summary of the save operation.
The function... | ```php
function saveReport($source, $report, $recordTypeCounts, $errors) {
// Process the source data and generate the report based on the provided source and record type counts
// ...
// Save the report data
$savedRecordsCount = saveReportData($report);
// Return a summary of the save operation
... | magicoder | php |
You are tasked with creating a Python function that generates a video animation of two pulses moving across the screen. The animation should display two pulses, each moving in opposite directions, and the entire animation should be saved to a file named "twoPulse.mp4".
The function should take the following parameters... | ```python
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def create_two_pulse_animation(filename, duration, pulse_color):
fig, ax = plt.subplots()
ax.set_xlim(0, 100)
ax.set_ylim(0, 1)
x = np.linspace(0, 100, 1000)
y = np.sin(x)
line1, = ax.plot(x,... | magicoder | python |
You are tasked with creating a Python class that represents pending modifications to an Amazon Redshift cluster. The class should be able to deserialize data from a source and provide type validation for the attributes. Your task is to implement the `PendingModifiedValues` class with the specified attributes and their ... | ```python
from schematics.models import Model
from schematics.types import StringType, IntType, BooleanType
class PendingModifiedValues(Model):
master_user_password = StringType(deserialize_from="<PASSWORD>")
node_type = StringType(deserialize_from="NodeType")
number_of_nodes = IntType(deserialize_from="Nu... | magicoder | python |
You are tasked with creating a command-line tool that processes coverage analysis data and submits it to a service for further analysis. The tool should support global options and two distinct modes of operation: regular and debug mode.
The regular mode should submit the coverage data to the specified service, while t... | ```python
import argparse
import json
def submit_coverage_data(service, debug_mode=False):
# Simulate submitting coverage data to the specified service
if debug_mode:
print(json.dumps({"coverage_stats": "sample_data"}, indent=4)) # Output coverage data in JSON format
else:
print(f"Submitti... | magicoder | python |
You are tasked with implementing a function that parses a given Rust code snippet and extracts the names of the structs defined within it. The code snippet will contain Rust struct definitions, and your function should return a list of the names of these structs.
Write a function `extract_struct_names` that takes a Ru... | ```rust
fn extract_struct_names(code_snippet: &str) -> Vec<String> {
let mut struct_names = Vec::new();
let lines: Vec<&str> = code_snippet.lines().collect();
for line in lines {
if let Some(trimmed) = line.trim().strip_prefix("pub struct ") {
let struct_name = trimmed.split_whitespace(... | magicoder | rust |
You are tasked with implementing a Python class that extends functionality from two different parent classes. Your goal is to create a class that inherits from `BoxCommand` and `Math.math` and implements a property called `source`. The `source` property should return `True` if the `MHBoxCommand` instance has child node... | ```python
class MHBoxCommand(BoxCommand, Math.math):
@property
def source(self):
if self.hasChildNodes():
return True
else:
return False
```
In the solution, the `MHBoxCommand` class is defined to inherit from `BoxCommand` and `Math.math`. The `source` property is implem... | magicoder | python |
You are tasked with implementing a generic C++ class that provides a multi-value read view for a specific data structure. The data structure consists of weighted values, where each value is associated with an atomic entry reference. Your task is to create a class template `CopyMultiValueReadView` that can be instantiat... | ```cpp
#include <mutex>
#include <vector>
// Define the WeightedValue template
template <typename T>
struct WeightedValue {
T value;
double weight;
};
// Define the CopyMultiValueReadView class template
template <typename W, typename A>
class CopyMultiValueReadView {
public:
// Constructor taking a refere... | magicoder | cpp |
You are tasked with implementing a data synchronization mechanism for a distributed database system. The system consists of multiple nodes, each running an instance of a database model. The goal is to ensure that the data across all nodes remains consistent and up to date. To achieve this, you need to design a synchron... | ```python
class DataSynchronizer:
def __init__(self, database_models):
self.database_models = database_models
def delete(self):
for model in self.database_models:
model.delete_outdated_data() # Assuming a method delete_outdated_data exists in the database model
def sync_batch_... | magicoder | python |
You are tasked with creating a program to parse and extract information from HTML breadcrumb elements. Breadcrumbs are a navigation aid used in user interfaces to show the user's location within the application's hierarchy. Each breadcrumb item is represented by an anchor tag `<a>` within a list item `<li>`.
Your task... | ```python
from bs4 import BeautifulSoup
from typing import List
def extract_breadcrumbs(html: str) -> List[str]:
soup = BeautifulSoup(html, 'html.parser')
breadcrumb_items = soup.find_all('li', class_='breadcrumb-item')
return [item.get_text() for item in breadcrumb_items]
``` | magicoder | python |
You are given a string `s` and a list of words `words`. Your task is to find the minimum number of indices that need to be changed in `s` so that all the words in the list `words` can be formed by concatenating non-overlapping substrings of `s`.
For example, if `s = "barfoothefoobarman"` and `words = ["foo", "bar"]`, ... | ```swift
func minIndicesToChange(_ s: String, _ words: [String]) -> Int {
var map: [Character : [Int]] = [:]
for (index, c) in s.enumerated() {
map[c, default: []].append(index)
}
var result = 0
for word in words {
var indices = map[word.first!, default: []]
var found = fals... | magicoder | swift |
You are tasked with creating a Python function that processes image metadata and generates a license information object based on the provided parameters. The function should take in the following parameters:
- `thumbnail_url` (string): The URL of the thumbnail image.
- `width` (integer): The width of the image.
- `heig... | ```python
def mock_license_chooser(license_url, license_, license_version):
from image.licenses import LicenseInfo # Importing the LicenseInfo class from the image.licenses module
return LicenseInfo(license_url, license_, license_version) # Returning an instance of LicenseInfo with the provided parameters
``` | magicoder | python |
You are tasked with implementing a class for controlling a signal generator instrument. The class should have methods for setting the frequency, status, and modulation pulse of the signal generator. The frequency can be set to specific values in megahertz, the status can be turned on or off, and the modulation pulse ca... | ```python
import types
class SignalGenerator:
def __init__(self):
self.parameters = {}
def add_parameter(self, name, flags, type, format_map):
self.parameters[name] = {'flags': flags, 'type': type, 'format_map': format_map}
def set_frequency(self, frequency_mhz):
if frequency_mhz ... | magicoder | python |
You are tasked with implementing a custom `equals` method for a class representing a geometric shape. The `equals` method should compare two shapes for equality based on their properties. The geometric shape class has the following properties:
- `name` (a string representing the name of the shape)
- `area` (a double re... | ```java
public class GeometricShape {
private String name;
private double area;
private double perimeter;
// Constructor and other methods are not shown for brevity
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == nu... | magicoder | java |
You are tasked with implementing a Python class that manages the layout of build products, both final and intermediate disposables. The class should adhere to the `merlin.protocol` and belong to the "merlin.layouts.prefix" family. Your task is to create the `PrefixLayout` class with appropriate methods to manage the bu... | ```python
import merlin
class PrefixLayout(merlin.protocol, family="merlin.layouts.prefix"):
"""
The manager of all build products, both final and intermediate disposables
"""
def __init__(self):
self.build_products = []
def add_build_product(self, product):
"""
Add a buil... | magicoder | python |
You are tasked with implementing a function to retrieve the current date in the format "yyyy-MM-dd". The function should return a string representing the current date in the specified format. You are not allowed to use any date/time libraries or built-in date functions provided by the programming language. Instead, you... | ```python
def get_current_date() -> str:
# Manually retrieve the current date components
year = str(2023) # Replace with actual logic to get the current year
month = str(5).zfill(2) # Replace with actual logic to get the current month
day = str(15).zfill(2) # Replace with actual logic to get the curr... | magicoder | python |
You are working on a project that involves optimizing and transforming neural network models represented in the ONNX format. As part of this process, you need to implement a Python function that checks for a specific condition in the ONNX graph and raises an exception if the condition is met. The provided code snippet ... | ```python
def check_inplace_not_supported(trace):
"""
Should be run after the ONNX pass.
"""
graph = trace.graph()
for node in graph.nodes():
if node.kind() == 'PythonOp':
if node.i('inplace'):
raise RuntimeError("inplace {} not supported in the JIT".format(node.p... | magicoder | python |
You are tasked with implementing a custom automatic differentiation framework for array operations. In this framework, you need to define the forward-mode automatic differentiation for the `concatenate_args` and `sort` functions.
The `concatenate_args` function takes a sequence of arrays and concatenates them along a ... | ```python
def fwd_grad_concatenate_args(g, ans, axis_args, *args):
result = []
for i, arg in enumerate(args):
if i == 0:
result.append(g)
else:
result.append(acp.zeros_like(arg))
return acp.concatenate_args(axis_args[0], *result)
def fwd_grad_sort(g, ans, x, axis=-1,... | magicoder | python |
You are tasked with implementing a data type conversion system for a robotics software framework. The system needs to map specific data types used in the framework to their corresponding Python data types. The provided code snippet shows a partial mapping of data types to Python types. Your task is to complete the mapp... | ```python
def convert_data(data, data_type):
data_type_mapping = {
'int8': int,
'int16': int,
'int32': int,
'int64': six_long,
'uint8': int,
'uint16': int,
'uint32': int,
'uint64': six_long,
'float32': float,
'float64': float,
'... | magicoder | python |
You are tasked with implementing a program to simulate a simple inventory management system for a warehouse. The warehouse contains a variety of items, each with a specific weight and balance value. Your program should generate random values for the balance and weight of these items and then perform certain operations ... | ```python
import random
from typing import List, Tuple
def generate_inventory_data(min_balance: float, max_balance: float, growth_factor_balance: float, min_weight: float, max_weight: float, growth_factor_weight: float, num_items: int) -> List[Tuple[float, float]]:
inventory_data = []
for _ in range(num_items)... | magicoder | python |
You are tasked with implementing a custom resolver in an Angular application. Resolvers in Angular are used to fetch data before a route is activated, ensuring that the necessary data is available before the component is displayed. In this scenario, you need to create a resolver called `CustomDataResolver` that fetches... | ```typescript
import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
... | magicoder | typescript |
You are tasked with implementing a function that processes a table of data and calculates the average value of a specific column. The table is represented as an array of objects, where each object corresponds to a row in the table. Each object contains key-value pairs, where the keys represent the column names and the ... | ```javascript
function calculateAverage(data, columnName, decimalPlaces) {
const columnValues = data.map(row => row[columnName]);
const sum = columnValues.reduce((acc, val) => acc + val, 0);
const average = sum / columnValues.length;
return average.toFixed(decimalPlaces);
}
``` | magicoder | javascript |
You are tasked with implementing a function to retrieve a list of file paths that have been copied to the clipboard. The function should return a list of file paths if the clipboard contains files, and return an error if the clipboard cannot be accessed or does not contain files.
You are provided with a partial code s... | ```rust
use std::io;
use std::path::PathBuf;
use winapi::um::shellapi::{CF_HDROP, DragQueryFileW};
use winapi::um::winuser::GetClipboardData;
impl ClipboardHandler {
/// Returns a list of file paths that have been copied to the clipboard.
///
/// Will return `Err` if the clipboard cannot be accessed or doe... | magicoder | rust |
You are working on a soccer analytics project and have been tasked with adding the abbreviated player positions to a players dataframe based on a given formation dictionary. The formation dictionary maps the player position index to its abbreviated form.
You are given the following code snippet as a starting point:
`... | ```python
import pandas as pd
def add_abbreviated_position(df, formation_dict):
df['Position'] = df['Position Index'].map(formation_dict)
return df
# Example usage
players_df = pd.DataFrame({'Player': ['John', 'Mike', 'Sarah', 'Emma'],
'Position Index': [1, 4, 6, 11]})
formation_dic... | magicoder | python |
You are tasked with implementing a function to calculate the number of differing bits between two given integers and formatting the result using a specific formatter. The function should take two integer values as input and return the formatted result.
You are provided with a code snippet that demonstrates the usage o... | ```swift
func calculateDifferingBits(_ value1: Int, _ value2: Int) -> String {
let differingBits = value1 ^ value2
var count = 0
var differingBitsCopy = differingBits
while differingBitsCopy != 0 {
count += differingBitsCopy & 1
differingBitsCopy >>= 1
}
return BitDiffResultForma... | magicoder | swift |
You are tasked with creating a Python function to manage database operations. The function will interact with a database using a cursor and connection, and will perform table creation and insertion operations. Your task is to complete the implementation of the `runQuery` function, which takes two parameters: `operation... | ```python
import sqlite3
def runQuery(operation, action):
conn = sqlite3.connect('database.db')
cursor = conn.cursor()
if action == "create":
if operation == 0:
cursor.execute('''CREATE TABLE Table0 (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)''')
elif operation == 1:
... | magicoder | python |
You are tasked with implementing a Python function that mimics the behavior of the provided code snippets. Your function should take in a variable number of arguments and optional keyword arguments, and then print the arguments to the standard output with specific formatting and flushing behavior.
You are to implement... | ```python
def custom_print(*items, sep='\n', end='\n', flush=False) -> None:
if flush:
import sys
print(*items, sep=sep, end=end, file=sys.stdout, flush=True)
else:
print(*items, sep=sep, end=end)
```
The `custom_print` function takes advantage of the built-in `print` function in Python... | magicoder | python |
You are working on a project to build a machine learning model for a graph-based dataset. The code snippet provided is part of the training process for the model. Your task is to implement a function that calculates the sample weights based on the dataset and the given sample indices.
You are given the following infor... | ```python
import numpy as np
def calculate_sample_weights(X, Y, dataset, sample_indices):
"""
Calculate the sample weights based on the dataset and the given sample indices.
Args:
X (numpy.ndarray): Feature matrix of the graph nodes
Y (numpy.ndarray): Target labels for the graph nodes
dataset ... | magicoder | python |
You are tasked with creating a Python class that represents a network device using the pyangbind library. The network device has various attributes such as IP address, hostname, and interface details. Your task is to create a Python class definition that utilizes the pyangbind library to define these attributes and the... | ```python
from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
class NetworkDevice(yangbind.Entity):
... | magicoder | python |
You are working on a reinforcement learning environment and need to manipulate the terminal states. The environment is represented by a grid, and the terminal states are marked with a specific value. You want to find the coordinates of all the terminal states in the grid and store them for further processing.
You are ... | ```python
import numpy as np
from typing import List, Tuple
def find_terminal_states_coordinates(terminals: np.ndarray) -> List[Tuple[int, int]]:
terminal_coordinates = np.argwhere(terminals == 1)
return [(coord[0], coord[1]) for coord in terminal_coordinates]
```
The `find_terminal_states_coordinates` functi... | magicoder | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.