query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with simulating a simplified version of the board game Nine Men's Morris. In this game, two players, 'W' and 'B', take turns placing their pieces on the board until one player forms a mill (three pieces in a row along a straight line), at which point they can remove one of their opponent's pieces. Once a... | ```python
def determine_game_phase(num_pieces, current_phase):
if num_pieces == 3 and current_phase != 'INIT':
return 'FLY'
else:
return current_phase
def human_play_mill(state):
# Implement the logic for the human player's move when a mill is formed
pass
def human_play_init(state):
... | magicoder | python |
You are tasked with creating a script to test the PUT method on a list of domains. The script should read a list of domains from a file, then for each domain, it should send a PUT request with a specific payload and record the response code and the URL. Your task is to write a Bash script that accomplishes this.
Your ... | ```bash
#!/bin/bash
if [ -z "$1" ]; then
echo "Usage: $0 <domain_file>"
exit 1
fi
while IFS= read -r domain; do
response=$(curl -s -o /dev/null -w "URL: %{url_effective} - Response: %{response_code}\n" -X PUT -d "hello world" "${domain}/evil.txt")
echo "$response"
done < "$1"
```
Save the above script in a f... | magicoder | shell |
You are tasked with implementing a Python function that simulates a simple text-based game. The game involves a player navigating through a grid-based world, collecting treasures, and avoiding obstacles. The player can move up, down, left, or right within the grid. The grid is represented as a 2D list where each cell c... | ```python
from typing import List
def play_game(grid: List[List[str]]) -> bool:
rows, cols = len(grid), len(grid[0])
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
def is_valid_move(row, col):
return 0 <= row < rows and 0 <= col < cols and grid[row][col] != 'X'
def dfs(row, col):
if ... | magicoder | python |
You are tasked with creating a custom decorator in Python that replicates the functionality of the `@login_required` decorator from the Django web framework. The `@login_required` decorator ensures that the wrapped view function can only be accessed by authenticated users. Your custom decorator should perform the same ... | ```python
from functools import wraps
from django.http import HttpResponseRedirect
from django.urls import reverse
def custom_login_required(view_func):
@wraps(view_func)
def wrapper(request, *args, **kwargs):
if request.user.is_authenticated:
return view_func(request, *args, **kwargs)
... | magicoder | python |
You are tasked with creating a Python function that simulates a file moving operation. Your function should take in two parameters: `source_path` and `destination_path`. The function should move the file located at `source_path` to the `destination_path`. If the parent directory of the `destination_path` does not exist... | ```python
import shutil
from pathlib import Path
def move_file(source_path, destination_path):
try:
destination_parent = Path(destination_path).parent
destination_parent.mkdir(parents=True, exist_ok=True)
shutil.move(source_path, destination_path)
return True
except Exception as... | magicoder | python |
You are working on a graph manipulation module for a machine learning framework. The code snippet provided is a part of a method that adds a new node to the graph and performs some initialization tasks. The `self` object represents an instance of a graph manipulation class. The method `_add_node_shapetype` is responsib... | ```python
class GraphManipulation:
def __init__(self):
self.nodes = {}
self.blob_version = {}
self._tb_graph = Graph() # Assume Graph class is defined elsewhere
def _add_node_shapetype(self, in_node, c2_input):
# Implementation not provided
def add_and_initialize_node(self... | magicoder | python |
You are tasked with implementing a simple key-value store API for managing properties of "things". The API provides two main functions: `onGet` for retrieving the value of a property and `onSet` for updating the value of a property. The properties are identified by a key and are associated with a specific "thing" ident... | ```python
from typing import Any, Tuple
class KeyValueStore:
def __init__(self):
self.store = {}
def onGet(self, key: str, thing_id: Tuple[int]) -> Any:
property_key = (key, thing_id[0])
return self.store.get(property_key)
def onSet(self, key: str, thing_id: Tuple[int], value: Any... | magicoder | python |
You are working on a script to automate the setup of the OpenCV framework for iOS development. The given code snippet is part of the script and is responsible for downloading and extracting the OpenCV framework if it does not already exist.
Your task is to write a Bash script that completes the automation process by a... | ```bash
OPENCV_FRAMEWORK_DIR=$OPENCV_DIR/opencv2.framework
if [ ! -d $OPENCV_DIR ]; then
mkdir $OPENCV_DIR
fi
if [ ! -f $OPENCV_ZIP_FILE ]; then
curl -L -o $OPENCV_ZIP_FILE -O https://github.com/opencv/opencv/releases/download/$OPENCV_VERISON/opencv-$OPENCV_VERISON-ios-framework.zip
fi
unzip -o $OPENCV_ZIP_F... | magicoder | shell |
You are given a Python code snippet that prompts the user to input a sentence. The code then aims to determine the ordinal numbers of the first pair of adjacent identical characters in the input sentence. If no such pair exists, a corresponding message is printed. Your task is to write a Python function that achieves t... | ```python
from typing import Union, Tuple
def find_first_pair_indices(sentence: str) -> Union[Tuple[int, int], str]:
for ind in range(len(sentence) - 1):
if sentence[ind] == sentence[ind + 1]:
return (ind + 1, ind + 2)
return "No matching pair found"
# Test cases
print(find_first_pair_indi... | magicoder | python |
You are tasked with creating a program to evaluate a neural network model using the PyTorch library. The given code snippet is part of a larger program and indicates the transition from training to testing the model. The `net` object represents the neural network model, and the `torch::NoGradGuard` is used to disable g... | ```cpp
// Assuming the neural network model and test dataset are already defined and loaded
// Transition from training to testing phase
std::cout << "Training finished!\n\n";
std::cout << "Testing...\n";
// Test the model
net->eval();
torch::NoGradGuard no_grad;
// Define variables to store the total and correct pr... | magicoder | cpp |
You are tasked with implementing a custom reader for a hyper body, which is used in a web server framework. The `HyperBodyReader` struct implements the `io::Read` trait, and the `read` method is responsible for reading data into the provided buffer. However, the current implementation is incomplete, and your task is to... | ```rust
impl io::Read for HyperBodyReader {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let mut cnt = 0;
loop {
match self.body.read(buf) {
Ok(0) if cnt > 0 => return Ok(cnt),
Ok(0) => return Err(io::ErrorKind::UnexpectedEof.into()),
... | magicoder | rust |
You are tasked with implementing a method to retrieve user data from a social media platform using OAuth authentication. The method is part of a larger class that handles OAuth requests. The code snippet provided is a part of the method that constructs and sends the HTTP request to the platform's API endpoint. Your tas... | ```java
public class OAuth {
private String getTokenUrl() {
// implementation not shown
}
private HttpRequest getRequest() {
// implementation not shown
}
public String getUserData() {
String tokenUrl = getTokenUrl();
String userDataUrl = (tokenUrl == null) ? "https... | magicoder | java |
You are tasked with implementing a simple task scheduler for a real-time operating system. The scheduler will manage a set of tasks and execute them based on their priority and timing requirements. You are provided with a code snippet that includes some relevant imports and a lazy-initialized static timer instance.
Yo... | ```rust
use core::sync::atomic::{AtomicUsize, Ordering};
use alloc::binary_heap::BinaryHeap;
use alloc::vec::Vec;
use alloc::sync::Arc;
use spin::Mutex;
use core::cmp::Ordering as CmpOrdering;
pub struct Timer {
tasks: Mutex<BinaryHeap<Arc<Task>>>,
}
impl Timer {
pub fn new() -> Self {
Timer {
... | magicoder | rust |
You are tasked with creating a script to automate the process of importing data into a MongoDB database. The script should take in the database name, collection name, and the file containing the data to be imported. The script should handle the following requirements:
- Connect to the MongoDB instance and import the da... | ```python
import sys
import pymongo
import os
def import_data_to_mongodb(database, collection, file_path):
try:
client = pymongo.MongoClient('localhost', 27017)
db = client[database]
col = db[collection]
# Drop the collection if it already exists
if collection in db... | magicoder | python |
You are tasked with creating a program that simulates a simple logging system for a software development environment. The program should be able to handle different types of log messages and display them in a specific format.
Your task is to implement a class called `Logger` with the following requirements:
- The clas... | ```php
class Logger {
private $logs = [];
public function info($message) {
$this->logs[] = "INFO: $message";
}
public function error($message) {
$this->logs[] = "ERROR: $message";
}
public function display() {
foreach ($this->logs as $log) {
echo $log . PHP... | magicoder | php |
You are tasked with implementing a Python class for a card game. The class should contain a method `hand_value` that calculates the value of a player's hand based on the cards they hold. The value of each card is determined as follows:
- Cards 2 to 10 have a value equal to their number.
- Face cards (Jack, Queen, King)... | ```python
def hand_value(self) -> int:
"""Calculate player's hand value and return it"""
card_sum = 0
aces = 0
for card in self._cards:
if card == 14:
aces += 1
elif 11 <= card <= 13:
card_sum += 10
else:
card_sum += card
if aces > 0:
... | magicoder | python |
You are tasked with creating a function that processes project data and returns a modified project object based on certain conditions. The function should take in the original project object and an optional `forkOptions` object, and it should return the modified project object according to the following rules:
1. If t... | ```javascript
function processProject(project, forkOptions) {
const inputProject = project;
const getProject = () => {
// Implementation of getProject function to retrieve project data
};
const session = {
user: {
id: "<currentUserId>",
name: "<currentUserName>"
}
};
const projectT... | magicoder | javascript |
You are tasked with creating a Unity script that integrates a webcam feed into a video streaming application. The script should handle the initialization of the webcam streaming and provide functionality to start and stop the streaming process. Additionally, the script should be able to control the streaming view and m... | ```csharp
void InitializeUnityWebCamStreaming()
{
_WebCamTexture = new WebCamTexture();
_WebCamImage.texture = _WebCamTexture;
_WebCamTexture.Play();
}
void StartWebCamStreaming()
{
if (_WebCamTexture != null)
{
_WebCamTexture.Play();
}
}
void StopWebCamStreaming()
{
if (_WebCamTex... | magicoder | csharp |
You are tasked with implementing a generic property wrapper in Rust that allows for the observation of changes to the wrapped value. The property wrapper should provide functionality to get and set the value, as well as to register and notify observers when the value changes.
You need to implement the `Property` struc... | ```rust
use std::fmt;
struct Property<T> {
value: T,
observers: Vec<Box<dyn Fn(&T)>>,
}
impl<T> Property<T> {
fn new(value: T) -> Self {
Property {
value,
observers: Vec::new(),
}
}
fn get(&self) -> &T {
&self.value
}
fn set(&mut self, new_... | magicoder | rust |
You are tasked with implementing a hash table data structure in C++. The hash table should support the following operations:
1. Insertion of a key-value pair.
2. Retrieval of the value associated with a given key.
3. Deletion of a key-value pair.
Your implementation should handle potential naming conflicts with the `h... | ```cpp
#include <iostream>
#include <list>
#include <utility>
class HashTable {
private:
static const int tableSize = 10;
std::list<std::pair<int, int>> table[tableSize];
int hashFunction(int key) {
return key % tableSize;
}
public:
void insert(int key, int value) {
int index = ha... | magicoder | cpp |
You are given a 2D list representing a grid of percentages. Each cell in the grid contains a percentage value. However, some cells contain "NaN" (Not a Number) instead of a valid percentage. Your task is to write a function to replace the "NaN" values with the average of the neighboring valid percentage values (up, dow... | ```python
def replace_nan_with_avg(grid):
rows, cols = len(grid), len(grid[0])
def is_valid(row, col):
return 0 <= row < rows and 0 <= col < cols and type(grid[row][col]) == float
def get_neighbors_avg(row, col):
total, count = 0, 0
for dr, dc in [(0, 1), (0, -1), (1, 0), (-1, 0)]:... | magicoder | python |
You are tasked with implementing a Python class method that parses data from a JSON object and uses it to create an instance of a specific class. The class, `AbstractTrimmingInputStream`, has the following attributes: `input_stream_id`, `id_`, `custom_data`, `name`, and `description`. Your goal is to complete the imple... | ```python
class AbstractTrimmingInputStream:
def __init__(self, input_stream_id, id_, custom_data, name, description):
self.input_stream_id = input_stream_id
self.id_ = id_
self.custom_data = custom_data
self.name = name
self.description = description
@classmethod
de... | magicoder | python |
You are tasked with creating a Python program that processes a bibliography file and extracts relevant information from it. The bibliography file contains citation information for various scientific publications. Each citation is enclosed within a pair of triple double quotes (`"""`) and may span multiple lines. The in... | ```python
import re
def extract_citation_info(bibliography):
citations = re.findall(r'"""(.*?)"""', bibliography, re.DOTALL)
extracted_info = []
for citation in citations:
info = {}
lines = citation.strip().split('\n')
authors_year = lines[0].strip().split('.')
info["authors... | magicoder | python |
You are tasked with implementing a `BlockCharacterManager` class that manages a collection of characters in a block-based system. Each block can hold a fixed number of characters, and the manager should support operations for adding, removing, and retrieving characters within the blocks.
Your task is to implement the ... | ```java
import java.util.ArrayList;
import java.util.List;
public class BlockCharacterManager {
private List<List<Character>> blocks;
private int blockSize;
public BlockCharacterManager(int blockSize) {
this.blockSize = blockSize;
blocks = new ArrayList<>();
}
public void addChara... | magicoder | java |
You are given a Python class representing a simple bank account. The class has methods for depositing funds, withdrawing funds, and checking the current balance. Your task is to implement the `transfer` method, which allows transferring funds from one account to another.
The `BankAccount` class has the following metho... | ```python
class BankAccount:
def __init__(self, balance):
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if self.balance >= amount:
self.balance -= amount
else:
print("Insufficient funds")
de... | magicoder | python |
You are given a singly linked list with a head node `head`. Each node in the linked list has a `val` field containing an integer value, and a `next` field pointing to the next node in the list. Additionally, you are given a positive integer `n` representing the number of nodes in the linked list.
You need to write a f... | ```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def rearrangeLinkedList(head: ListNode, n: int) -> ListNode:
if not head or not head.next:
return head
even_head = ListNode(0)
odd_head = ListNode(0)
even_ptr = even_head
odd... | magicoder | python |
You are tasked with implementing a Python coroutine that simulates a simple asynchronous server using the `asyncio` library. The server should continuously send a sequence of messages in the format "hello {number}\n" to a client at regular intervals. Your task is to complete the `send_messages` coroutine function, whic... | ```python
import asyncio
class AsyncServer:
def __init__(self):
self.writer = None
async def send_messages(self):
i = 0
while True:
i += 1
message = f'hello {i}\n'.encode('utf-8')
if self.writer:
self.writer.write(message)
... | magicoder | python |
You are tasked with implementing a function that filters and rebuilds a tree-like data structure based on a set of allowed nodes. The tree is represented as a collection of nodes, each having a name and possibly child nodes. The goal is to create a new tree structure containing only the allowed nodes and their children... | ```rust
fn recursive_rebuilder(allowed_nodes: &HashSet<String>, node: &Node) -> Option<Node> {
if allowed_nodes.contains(&node.name) {
let children = node.children.iter()
.filter_map(|c| recursive_rebuilder(allowed_nodes, c))
.collect();
Some(Node {
name: node.nam... | magicoder | rust |
You are tasked with implementing a web crawler that adheres to the rules specified in a robots.txt file. The robots.txt file specifies which URLs on a website can be accessed by web crawlers. The web crawler should also build a site graph, representing the relationships between different URLs on the website.
You are g... | ```python
# Initialize variables
visited_urls = {} # Dictionary to store visited URLs and their depths
enqueue_count = 0 # Counter for the number of URLs enqueued for processing
# Assuming current_url and current_depth are defined elsewhere in the code
# Check if the URL has not been visited before and can be fetch... | magicoder | python |
You are working on a system that manages various types of jobs, such as cleanup, backup, and restore operations. The system has a set of predefined filters represented as lambda functions, which are used to categorize and process these jobs. Additionally, there is a private function `_is_running` that checks whether a ... | ```python
import requests
def _is_running(job):
return status.busy(job['CurrentState'])
def _jobs(connection, predicate, agent_id=None):
if agent_id is not None:
url = '{0}/activity'.format(connection.host)
else:
url = '{0}/activity/{1}'.format(connection.host, agent_id)
response = re... | magicoder | python |
You are given two strings, `str1` and `str2`, along with an integer `k`. Your task is to determine whether it is possible to convert `str1` into `str2` by performing at most `k` operations. An operation is defined as either inserting a character, deleting a character, or replacing a character in `str1`.
Write a functi... | ```python
def isKPal(str1, str2, k):
m, n = len(str1), len(str2)
if abs(m - n) > k:
return False
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1):
for j in range(n + 1):
if i == 0:
dp[i][j] = j
elif j == 0:
dp[i][j... | magicoder | python |
You are tasked with creating a program that analyzes HTML and CSS files to identify and count the occurrences of specific classes within the HTML elements. Your program should be able to handle both single and double quotes around the class names in the HTML files.
Write a function `countClassOccurrences` that takes i... | ```javascript
function countClassOccurrences(htmlContent, classNames) {
const classCounts = {};
classNames.forEach(className => {
const regex = new RegExp(`\\b${className}\\b`, 'g');
const matches = htmlContent.match(regex);
classCounts[className] = matches ? matches.length : 0;
});
return classCo... | magicoder | javascript |
You are given an array of integers representing a sequence of numbers. Your task is to find the length of the longest increasing subsequence (LIS) within the array. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.... | ```java
public class Solution {
public int longestIncreasingSubsequence(int[] nums) {
int n = nums.length;
int[] dp = new int[n];
Arrays.fill(dp, 1);
int max = 1;
for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
if (nums[i] > nums[j]) {
dp[i] = Math.max(dp[i], d... | magicoder | java |
You are tasked with implementing a PrefixMapSum class that supports two operations: insert(key, value) and sum(prefix). The insert operation will insert a key-value pair into the map, and the sum operation will return the sum of all the values whose keys start with a given prefix.
You need to implement the PrefixMapSu... | ```python
class PrefixMapSum:
def __init__(self):
self._prefix = {}
def insert(self, key, value):
"""
:type key: str
:type value: int
"""
dv = value - self._prefix.get(key, 0)
for i in range(len(key)):
prefix = key[:i + 1]
self._pr... | magicoder | python |
You are tasked with implementing a program to parse and process a specific type of ASCII art. The ASCII art represents a stylized tree, and your program needs to extract relevant information from the input and perform specific calculations.
The input will consist of multiple lines, each representing a level of the tre... | ```python
def treeStats(ascii_art):
lines = ascii_art.split('\n')
height = len(lines)
width = max(len(line) for line in lines)
leaves = sum(line.count('|') for line in lines)
return {"height": height, "width": width, "leaves": leaves}
``` | magicoder | python |
You are tasked with implementing a reinforcement learning environment for a robotic system. The provided code snippet is a part of the initialization process for the environment. Your task is to complete the implementation of the environment by defining the action and observation spaces, as well as the step function.
... | ```python
import gym
from gym import spaces
import numpy as np
class RoboticSystemEnv(gym.Env):
def __init__(self, initial_pos_noise, initial_orn_noise, step_pos_noise, step_orn_noise,
step_max_pos, step_max_orn, reward):
self.reward = reward
self.max_initial_pos_noise = initial_p... | magicoder | python |
You are tasked with creating a Python class to manage genomic sequences obtained from the UCSC Browser. The class should handle the retrieval of genomic sequences while adhering to the UCSC Browser's rate limits. The provided code snippet is a method within the class that demonstrates the process of creating a genomic ... | ```python
import datetime
import time
SECONDS_BETWEEN_UCSC_REQUESTS = 5 # Rate limit for UCSC Browser requests
def get_time_of_last_request_to_ucsc_browser() -> datetime.datetime:
"""Retrieve the timestamp of the last request made to the UCSC Browser."""
# Implementation not provided for this function
class... | magicoder | python |
You are tasked with creating a Python class that simulates a simple banking system. The class should have methods to deposit funds, withdraw funds, check the balance, and transfer funds between accounts. Additionally, the class should keep track of the account holder's name and account number.
Create a Python class `B... | ```python
import random
class BankAccount:
def __init__(self, account_holder_name):
self.account_holder_name = account_holder_name
self.account_number = self.generate_account_number()
self.balance = 0
def generate_account_number(self):
return random.randint(100000, 999999)
... | magicoder | python |
You are tasked with creating a program that simulates a simplified version of the `git diff` command. The `git diff` command is used to show the difference between the working directory and the staging area. In this simplified version, you are given two strings representing the working directory and the staging area. Y... | ```python
def gitDiff(workingDirectory, stagingArea):
difference = ""
for char in stagingArea:
if char not in workingDirectory:
difference += char
return difference
```
The `gitDiff` function iterates through each character in the staging area and checks if it is not present in the work... | magicoder | python |
You are tasked with implementing a Java program to generate a unique chessboard configuration using the given code snippet as a starting point. The chessboard configuration should be represented as an 8x8 grid with pieces placed in their initial positions according to standard chess rules.
Your task is to complete the... | ```java
import java.util.Random;
import java.util.UUID;
public class chess {
private static String word() {
String a = UUID.randomUUID().toString();
return a.substring(0, 1);
}
public static String[][] generateChessboard() {
String[][] chessboard = new String[8][8];
// In... | magicoder | java |
You are tasked with implementing a medication reminder system that sends notifications to users at specified times. The system should allow users to schedule medication reminders and receive notifications at the scheduled times. Each user can have multiple medication reminders, and each reminder should include the medi... | ```python
import datetime
import uuid
class MedicationReminder:
def __init__(self):
self.users = {}
def add_medication_reminder(self, user_id, medication_name, dosage, reminder_time):
if user_id not in self.users:
self.users[user_id] = User(user_id)
self.users[user_id].add_... | magicoder | python |
You are tasked with implementing a file attribute retrieval system using Swift. Your goal is to create a function that retrieves and returns the attributes of a file using extended file attributes.
You are given a code snippet that demonstrates part of the implementation. The code snippet uses the `listxattr` function... | ```swift
func getAttribute(name: String) throws -> String? {
let length = getxattr(self.path, name, nil, 0, 0, 0)
if length == -1 {
if errno == ENOATTR {
return nil // Attribute does not exist
} else {
throw NSError(domain: String(cString: strerror(errno)), code: Int(err... | magicoder | swift |
You are tasked with implementing a function that processes a given array of integers and returns a modified version of the array based on specific rules. The function should take an array of integers as input and return a new array based on the following rules:
1. If the input array is empty, the function should retur... | ```javascript
function processArray(arr) {
if (arr.length === 0) {
return [];
} else if (arr.length === 1) {
return [arr[0], arr[0]];
} else if (arr.length % 2 === 0) {
let modifiedArray = [];
for (let i = 0; i < arr.length; i += 2) {
modifiedArray.push(arr[i] + a... | magicoder | javascript |
You are tasked with creating a Python function that processes and visualizes data from a set of 2D arrays. The function should take in three input arrays: `unique_indexes`, `x_array`, and `y_array`, as well as a 3D array `Bmat_array`. The goal is to generate contour plots for specific thresholds from the `Bmat_array` d... | ```python
import matplotlib.pyplot as plt
def generate_contour_plots(unique_indexes, x_array, y_array, Bmat_array, thr_fixed, colors, linewidth):
fig, ax = plt.subplots()
for i, k in zip(unique_indexes, range(len(colors))):
cs = plt.contour(y_array[i], x_array[i], Bmat_array[i], [thr_fixed], colors=col... | magicoder | python |
You are tasked with creating a Python function that determines the appropriate logging module to import based on the version of the Sphinx documentation generator being used. The function should take the version of Sphinx as input and return the correct logging module to import.
The code snippet provided demonstrates ... | ```python
from packaging.version import parse as parse_version
import sphinx
def select_logging_module(sphinx_version):
if parse_version(sphinx_version) >= parse_version("1.6"):
from sphinx.util import logging
return logging
else:
import logging
return logging
```
The `select_lo... | magicoder | python |
You are working on a bioinformatics project and need to implement a method for identifying differentially expressed genes (DEGs) and posting them to the Enrichr platform for enrichment analysis. You have a class with the following relevant methods and attributes:
- `self.DEGs_posted(db, etype)`: A method that checks i... | ```python
from collections import OrderedDict
class GeneAnalysis:
# Other methods and attributes are assumed to be defined in the class
def post_DEGs_to_enrichr(self, db, cutoff, etype, genes_meta):
d_sample_userListId = OrderedDict()
if not self.DEGs_posted(db, etype):
up_DEGs_df... | magicoder | python |
You are tasked with implementing a custom data structure in C# that simulates a queue with the ability to efficiently retrieve the maximum element within a given range of elements. You need to implement the following operations for this data structure:
1. `Enqueue(int element)`: Add the specified element to the queue.
... | ```csharp
using System;
using System.Collections.Generic;
public class MaxInRangeQueue
{
private Queue<int> queue;
private SortedDictionary<int, int> maxCountMap;
public MaxInRangeQueue()
{
queue = new Queue<int>();
maxCountMap = new SortedDictionary<int, int>();
}
public void... | magicoder | csharp |
You are tasked with implementing a custom version of the `useFakeTimers` function, which is commonly used in testing frameworks like Jest. The function takes an optional parameter `implementation` that can be either `'modern'` or `'legacy'`. The function should return an object of type `jest`, which is a testing framew... | ```typescript
type JestFakeTimers = {
// Define the properties and methods of the Jest fake timers object
// ...
// Example properties/methods:
clearAllTimers: () => void;
runAllTimers: () => void;
// ...
};
type Jest = {
useFakeTimers: (implementation?: 'modern' | 'legacy') => JestFakeTimers;
// Othe... | magicoder | typescript |
You are tasked with creating a build automation tool similar to `make` for a software project. Your tool should be able to handle dependencies between different components of the project and execute the necessary build steps to ensure the project is up to date.
Your task is to implement a simplified version of the bu... | ```python
def build_project(components):
build_order = []
visited = set()
def dfs(component):
if component in visited:
return
visited.add(component)
if component in components:
for dependency in components[component]:
dfs(dependency)
b... | magicoder | python |
You are tasked with creating a script to monitor the memory usage of a server application and take appropriate action based on the memory consumption. Your script should be able to start the server application with a specified maximum heap size and monitor its memory usage. If the memory usage exceeds a certain thresho... | ```bash
#!/bin/bash
# Input parameters
start_command="./run.sh"
app_name="APMServer"
max_heap_size="1024m"
memory_threshold="80" # in percentage
# Start the server application with the specified maximum heap size
nohup $start_command $app_name -Xmx$max_heap_size >/dev/null 2>&1 &
# Continuously monitor the memory us... | magicoder | shell |
You are tasked with creating a performance testing utility for a custom data structure. The data structure is a custom implementation of a priority queue, and you need to measure the time taken for various operations on this priority queue. Your task is to implement a performance testing method that measures the time t... | ```swift
class CustomPriorityQueue {
private var elements: [(value: Int, priority: Int)] = []
func insert(value: Int, priority: Int) {
elements.append((value, priority))
}
func removeHighestPriority() -> Int? {
guard !elements.isEmpty else { return nil }
elements.sort {... | magicoder | swift |
You are tasked with implementing a function that checks whether a given HTML string has properly matched opening and closing tags. In HTML, tags must be properly nested and closed in the correct order. For example, `<div><p></p></div>` is valid, while `<div><p></div></p>` is not.
You are given the following code snipp... | ```rust
use std::collections::HashSet;
static ref P_CLOSING_TAG_OMISSION_RULE: ClosingTagOmissionRule = {
let mut followed_by = HashSet::<&'static [u8]>::new();
// more code here
};
fn is_valid_html(html: &str) -> bool {
let mut stack: Vec<&str> = Vec::new();
let mut i = 0;
while i < html.len() {... | magicoder | rust |
You are working on a computer vision project and need to implement a class for camera transformation. The class has several methods to retrieve different transformation components. One of the methods, `get_4x4_world_to_cam_mat`, is intended to return a 4x4 transformation matrix representing the transformation from the ... | ```python
import numpy as np
class CameraTransformation:
# Other methods and class members are assumed to be implemented
def get_4x4_world_to_cam_mat(self):
# Construct the 4x4 transformation matrix
rotation_mat = self._rotation_mat
translation_vec = self._translation_vec
camer... | magicoder | python |
You are tasked with creating a Python program to consume messages from a Kafka topic and measure the time taken to process these messages. Your program should use the `confluent_kafka` library to interact with Kafka and the `time` module to measure the processing time.
Your program should perform the following steps:
... | ```python
import time
from confluent_kafka import Consumer, KafkaException
def consume_and_measure_time(kafka_topic_name):
consumer = Consumer({
'bootstrap.servers': 'your_kafka_broker_address',
'group.id': 'my_consumer_group',
'auto.offset.reset': 'earliest'
})
consumer.subscribe(... | magicoder | python |
You are tasked with implementing a custom memory buffer class in C++. The class should support the functionality of copying data from a given source to a specified offset within the buffer. Your task is to implement the `memcpy` method within the `MemoryBuffer` class.
The `MemoryBuffer` class has the following attribu... | ```cpp
#include <iostream>
#include <cstring>
class MemoryBuffer {
private:
char* address;
size_t size;
public:
MemoryBuffer(char* addr, size_t sz) : address(addr), size(sz) {}
void memcpy(void* source, size_t offset, size_t size) {
if (offset + size > this->size) {
std::cerr << "... | magicoder | cpp |
You are tasked with implementing a class that manages a collection of `ScopeClaimsExtractor` objects. The `ScopeClaimsExtractor` interface has a method `getExtractor(String scope)` that returns a specific extractor based on the given scope. However, the existing code snippet shows that the `getExtractors()` method, whi... | ```java
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
public class ScopeClaimsManager {
private Map<String, ScopeClaimsExtractor> extractors;
public ScopeClaimsManager() {
this.extractors = new HashMap<>();
}
public void addExtractor(String scope, ScopeClaimsExt... | magicoder | java |
You are tasked with implementing a C++ program that reads a list of integers from a file, calculates the sum of all the integers, and then writes the sum to an output file. The input file will contain one integer per line, and the output file should contain only the calculated sum.
Your program should use the followin... | ```cpp
#include "stdafx.hpp"
#include <iostream>
#include <fstream>
#include <string>
int main(int argc, char* argv[]) {
if (argc != 2) {
std::cerr << "Usage: " << argv[0] << " <input_file>" << std::endl;
return 1;
}
std::ifstream inputFile(argv[1]);
if (!inputFile.is_open()) {
... | magicoder | cpp |
You are given a list of integers representing the scores of a game. The game has a special rule for scoring where the score of each player is the sum of their scores in the current and the previous round. You need to write a function to calculate the total score for each player after all the rounds.
Write a function `... | ```python
from typing import List
def calculateTotalScore(scores: List[int]) -> List[int]:
total_scores = [scores[0]] # Initialize the total scores list with the first score
for i in range(1, len(scores)):
total_scores.append(total_scores[i-1] + scores[i]) # Calculate the total score for each round
... | magicoder | python |
You are working on a data preprocessing script for organizing image datasets. The script is designed to unzip two separate image datasets, move the unzipped files into a new directory, and then merge the contents of both datasets into a single directory. However, there seems to be an issue with the script, as it is not... | The issue with the provided script is that the `mv` command is not being executed correctly. The wildcard `*` is not expanded when using the `mv` command in this manner. To resolve this issue, the script should be modified to use the `shutil` module in Python to perform the file operations. Below is the corrected scrip... | magicoder | python |
You are tasked with creating a function to determine if there is a newer news flash in an RSS feed for a specific site. The function should take in the RSS link and the site name as parameters and return `True` if there is a newer news flash, and `False` otherwise. The function should currently only work for the "ynet"... | ```python
from anyway.parsers.news_flash import parsing_utils
from anyway.parsers.news_flash_parser import get_latest_date_from_db
def is_new_flash_news(rss_link, site_name):
"""
check if there is a newer news flash in the rss link - I think it works only for ynet though
:param rss_link: rss link
:retu... | magicoder | python |
You are tasked with implementing a filtering system for a photo editing application. The application has a `FilterViewController` class that allows users to apply various filters to their photos. The `FilterViewController` class has a delegate protocol, `FilterViewControllerDelegate`, which includes a method `filterVie... | ```swift
protocol FilterViewControllerDelegate: AnyObject {
func filterViewController(filter: FilterViewController, didSelectFilter filterName: String)
}
class FilterViewController {
weak var delegate: FilterViewControllerDelegate?
func applyFilter(selectedFilter: [[Float]], toPhoto photo: [[(red: Int, gr... | magicoder | swift |
You are tasked with creating a Python package management system that can handle dependencies and package augmentation. To achieve this, you need to implement a class for managing package dependencies and a plugin system for package augmentation.
Your task is to create a Python class `PackageDependencyManager` that can... | ```python
# Define the PackageDependencyManager class
class PackageDependencyManager:
def __init__(self):
self.dependencies = {}
def add_dependency(self, package_name, version):
self.dependencies[package_name] = version
def remove_dependency(self, package_name):
if package_name in ... | magicoder | python |
You are tasked with implementing a function that constructs a schema table based on a given set of field mappings. The function takes in an array of field mappings, where each mapping consists of a field name and its corresponding data type. The function should handle nullable data types and enums, and it should also a... | ```csharp
using System;
using System.Collections.Generic;
using System.Data;
public class SchemaMappingColumn
{
public string FieldName { get; }
public Type DataType { get; }
public bool AllowDbNull { get; }
public SchemaMappingColumn(string fieldName, Type dataType, bool allowDbNull)
{
Fi... | magicoder | csharp |
You are tasked with creating a command-line tool to manage timezones on a Unix-based system. Your tool should allow users to view the current timezone, set a new timezone, and list all available timezones. To achieve this, you need to implement a Python script that interacts with the system's timezone settings.
Your s... | ```python
import subprocess
def view_timezone():
try:
result = subprocess.check_output(["sudo", "systemsetup", "-gettimezone"])
print(result.decode("utf-8").strip())
except subprocess.CalledProcessError as e:
print(f"Error: {e}")
def set_timezone(new_timezone):
try:
subproc... | magicoder | python |
You are tasked with implementing a function that takes in a string representing a JSX code snippet and checks if all the opening JSX tags have a corresponding closing tag in the correct order. JSX tags are similar to HTML tags and are enclosed in angle brackets, such as `<div>`, `<span>`, or `<CustomComponent>`.
You n... | ```javascript
function validateJSX(jsxCode) {
const stack = [];
const regex = /<\s*\/?\s*([a-zA-Z]+)\s*>/g;
let match;
while ((match = regex.exec(jsxCode)) !== null) {
const tag = match[1];
if (tag.startsWith('/')) {
const openingTag = stack.pop();
if (!openingTag || openingTag !== tag.subs... | magicoder | javascript |
You are tasked with creating a Python program to manage a simple library system using Django's ORM (Object-Relational Mapping). The library system should allow users to add, view, and delete books from the library.
Your program should have the following functionalities:
1. Create a Django model for the Book entity wit... | ```python
# Import necessary modules
from django.db import models
# Define the Book model using Django's ORM
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
publication_year = models.IntegerField()
# Function to add a new book to the library
def... | magicoder | python |
You are tasked with creating a form validation system for a student registration application. The application has fields for student ID, password, and confirmation of the password. The validation rules for each field are as follows:
- Student ID: Should start with "PB" followed by exactly 8 digits (0-9).
- Password and... | ```python
import re
class StudentRegistrationValidator:
@staticmethod
def validate_student_id(student_id):
# Validate student ID: Should start with "PB" followed by exactly 8 digits (0-9)
return bool(re.match(r'^PB[0-9]{8}$', student_id))
@staticmethod
def validate_password(password):
... | magicoder | python |
You are tasked with implementing a Python function that calculates the sum of all prime numbers within a given range. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. The function should take two integer parameters, `start` and `end`, representing the inclusive ra... | ```python
def sum_of_primes(start: int, end: int) -> int:
def is_prime(num):
if num < 2:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
prime_sum = 0
for num in range(max(2, start), end + 1):
... | magicoder | python |
You are tasked with creating a Python script to automate the generation and emailing of a daily report of blocked GeoIPs from a pfSense firewall using pfBlockerNG. The report should include the list of blocked GeoIPs and be sent via email to a specified recipient.
The script should perform the following tasks:
1. Con... | ```python
import paramiko
import smtplib
from email.message import EmailMessage
# SSH connection parameters
ssh_host = 'pfSense_IP'
ssh_port = 22
ssh_username = 'your_ssh_username'
ssh_password = 'your_ssh_password'
# Email parameters
email_sender = 'your_email@gmail.com'
email_password = 'your_email_password'
email_... | magicoder | python |
You are tasked with creating a Python module for monitoring and managing Apache web server metrics. The module should implement an interactive viewer similar to the functionality of the `top` command, using the `curses` library for terminal-based user interface. The module should be invoked from the command line using ... | ```python
import curses
import time
import psutil # Assuming psutil is used for obtaining system metrics
def display_apache_metrics(stdscr):
# Clear screen
stdscr.clear()
# Add title
stdscr.addstr(0, 0, "Apache Web Server Metrics", curses.A_BOLD)
# Add metrics display
while True:
# G... | magicoder | python |
You are tasked with implementing a simplified version of a timer using Swift. The timer should be able to schedule and execute a given closure after a specified time interval. Your task is to create a class `SimpleTimer` that adheres to the provided `TimerProtocol` and allows scheduling and executing closures after a s... | ```swift
import Foundation
class SimpleTimer: TimerProtocol {
private var timer: Timer?
private var closure: (() -> Void)?
var fireDate: Date {
didSet {
if let closure = closure {
scheduleTimer(fireDate: fireDate, closure: closure)
}
}
}
var... | magicoder | swift |
You are tasked with implementing a custom error handling mechanism for a Python application. The goal is to create a class that generates informative error messages when certain conditions are met. Your task is to create a custom error class and a function that raises instances of this error class with specific error m... | ```python
class CustomError(Exception):
def __init__(self, class_name, property_name, val, err):
self.class_name = class_name
self.property_name = property_name
self.val = val
self.err = err
super().__init__(self.create_error())
def create_error(self):
return f"{... | magicoder | python |
You are tasked with creating a program to parse and extract information from a given HTML snippet containing details about third-party cookies used by various services. Your program should extract the service name, cookie type, and the URL for more details for each third-party cookie mentioned in the HTML snippet.
The... | ```python
from bs4 import BeautifulSoup
html_snippet = """
<div id="cookie__google" class="cookie__list">
• Cookie di "terze parti" di alcuni servizi Google come ad esempio Google Maps. E’ possibile consultare i dettagli su questi cookie in <a href="http://www.google.com/intl/it_it/policies/technologies/cook... | magicoder | python |
You are tasked with implementing a function that updates the principal on a compartment to match a new document in a browser environment. The compartment is used for reusing inner windows for same-origin principals, and it is essential to update the principal to match the new document accurately.
You are given the fol... | ```javascript
function updateCompartmentPrincipal(currentInner, newDocument) {
// Check if the currentInner and newDocument are valid
if (currentInner && newDocument) {
// Get the principal of the new document
let newPrincipal = newDocument.principal;
// Update the principal on the comp... | magicoder | javascript |
You are given a Python code snippet that processes an image represented as a 3D array `temp` and performs certain operations on its elements. Your task is to understand the code and implement a function that achieves the same result using a different approach.
The code snippet iterates through the elements of the seco... | ```python
def process_image(temp, BRIGHT_CUTOFF, RED_CUTOFF, GREEN_CUTOFF, BLUE_CUTOFF):
temp_bright = []
result = []
for row in range(len(temp)):
temp_bright_row = []
for element in range(len(temp[row])):
brightness = sum(temp[row][element]) / 3
temp_bright_row.appen... | magicoder | python |
You are tasked with creating a program that reads a text file and counts the occurrences of each unique word in the file. For the purpose of this problem, a word is defined as a sequence of alphanumeric characters, excluding any punctuation or whitespace.
Your program should read the text file named "input.txt" and ou... | ```python
from collections import defaultdict
import re
# Read the input file
with open("input.txt", "r") as file:
text = file.read()
# Remove punctuation and convert text to lowercase
text = re.sub(r'[^\w\s]', '', text).lower()
# Split the text into words
words = text.split()
# Count the occurrences of each wo... | magicoder | python |
You are tasked with creating a Python function that processes a list of database migration operations and returns the final order in which these operations should be executed. Each operation can either create or alter a database model, and some operations may have dependencies on others.
You are given a list of migrat... | ```python
def process_migrations(operations):
graph = {}
indegree = {}
result = []
# Build the graph and calculate indegree for each model
for operation in operations:
model_name = operation[1]
dependencies = operation[2]
if model_name not in graph:
graph[model_n... | magicoder | python |
You are tasked with implementing a function that checks whether a given string is a palindrome or not. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). Your function should return `True` if the input stri... | ```python
def is_palindrome(s: str) -> bool:
# Remove non-alphanumeric characters and convert to lowercase
s = ''.join(char for char in s if char.isalnum()).lower()
# Check if the string is equal to its reverse
return s == s[::-1]
``` | magicoder | python |
You are given a text file containing a software license agreement. Your task is to write a program that counts the occurrences of each word in the agreement and outputs the top N most frequently occurring words.
Your program should ignore common stop words such as "the", "and", "or", "is", etc., and should not be cas... | ```python
import re
from collections import Counter
def count_top_words(file_path, N):
with open(file_path, 'r') as file:
text = file.read().lower()
words = re.findall(r'\b\w+\b', text)
stop_words = set(['the', 'and', 'or', 'is', 'of', 'in', 'to', 'for', 'a', 'be', 'shall', 'no', 'any', 'or... | magicoder | python |
You are tasked with implementing a function to approximate the value of π using the Leibniz formula for π. The Leibniz formula is given by the series:
π/4 = 1 - 1/3 + 1/5 - 1/7 + 1/9 - ...
Your task is to write a Python function that takes an integer n as input and returns the approximation of π using the first n ter... | ```python
import matplotlib.pyplot as plt
def leibniz(n):
lz = 0
ret = []
for i in range(n + 1):
lz += ((-1) ** i) * (4 / (2 * i + 1))
ret.append(lz)
return lz, ret
lz, ret = leibniz(1000)
plt.plot(ret)
plt.show()
```
The `leibniz` function calculates the approximation of π using the ... | magicoder | python |
You are tasked with creating a function to determine whether a given string can be transformed into another string by rearranging its characters. The function should return `True` if the transformation is possible and `False` otherwise.
You are given the following code snippet as a starting point:
```python
from coll... | ```python
from collections import Counter
def can_scramble(source, dest):
# Check if the lengths of the two strings are different
if len(source) != len(dest):
return False
# Count the occurrences of each character in both strings
source_counter = Counter(source)
dest_counter = Counter(... | magicoder | python |
You are tasked with implementing a Python function that manages environment paths and executes commands with a timeout. The provided code snippet includes a partial implementation of this functionality. Your task is to complete the implementation of the `run_command` function and ensure that it can execute commands wit... | ```python
import subprocess
import time
ENV_PATHS = set()
def add_path_to_env(path):
ENV_PATHS.add(path)
def run_command(command, timeout=-1):
if type(command) == str:
try:
if timeout == -1:
result = subprocess.check_output(command, shell=True, stderr=subprocess.STDOUT)
... | magicoder | python |
You are tasked with simulating a series of actions performed by an automation tool. The provided code snippet demonstrates a sequence of actions, such as key presses, mouse clicks, and cursor movements. Your goal is to write a program that can interpret and execute these actions in a simulated environment.
You are giv... | ```python
import time
import pyautogui as auto
# Define the list of actions as provided in the code snippet
actions = [
lambda: auto.press('enter'),
lambda: time.sleep(0.2),
lambda: auto.doubleClick(536, 837, button='left'),
lambda: auto.keyDown('ctrlleft'),
lambda: auto.press('c'),
lambda: aut... | magicoder | python |
You are tasked with implementing a Python class that represents a mathematical set of terms. The class should support various operations on the set, such as iterating through the terms, counting the number of terms, and determining the size of the set. Below is a skeleton of the class with some methods already defined:... | ```python
class TermSet:
def __init__(self, iter_terms):
self.terms = set(iter_terms)
def iter_terms(self):
return iter(self.terms)
def add_term(self, term):
self.terms.add(term)
def remove_term(self, term):
self.terms.discard(term)
def iter_quads(self):
t... | magicoder | python |
You are tasked with implementing a simplified version of the Eigenfaces algorithm for face recognition in Python. The Eigenfaces algorithm is a popular technique that uses eigenvalue decomposition and principal component analysis to recognize faces. In this problem, you will need to write a Python class that performs t... | ```python
import numpy as np
class Eigenfaces:
def __init__(self, num_components):
self.num_components = num_components
self.mean_face = None
self.eigenfaces = None
self.eigenvalues = None
def train(self, training_data):
num_samples, img_height, img_width = training_dat... | magicoder | python |
You are tasked with implementing a Python class that performs a specific operation on a given set of data. The class should have an `__init__` method that accepts keyword-only arguments and initializes an attribute called `logits` with the provided data. The `logits` attribute should be of type `Optional[TensorOrData]`... | ```python
from typing import Optional, Union
TensorOrData = Union[int, float, str, list, tuple]
class LogitsProcessor:
def __init__(self, *, logits: Optional[TensorOrData]):
self.logits = logits
```
The solution provides the complete implementation of the `LogitsProcessor` class with the specified `__ini... | magicoder | python |
You are tasked with implementing a command-line interface for a Game Boy emulator. The provided code snippet is part of a larger Rust program that handles user input and executes corresponding emulator commands. The `match` statement is used to match user input to emulator commands, and the `dump_bg` and `reset` comman... | ```rust
// Define the function to dump the background tile map and color palette
fn dump_bg(command: &mut Command, gameboy: &GameBoy) {
// Extract the background tile map and color palette from the gameboy emulator
let background_tile_map = gameboy.get_background_tile_map();
let color_palette = gameboy.get_... | magicoder | rust |
You are tasked with creating a class that represents a geometric shape called "Triangle." The class should have methods to calculate and retrieve various properties of the triangle. One of the methods to be implemented is `getSidewardStepLength`, which should return the length of the sideward step of the triangle.
You... | ```java
public class Triangle {
private double sideA;
private double sideB;
private double sideC;
public Triangle(double sideA, double sideB, double sideC) {
this.sideA = sideA;
this.sideB = sideB;
this.sideC = sideC;
}
public double getSidewardStepLength() {
do... | magicoder | java |
You are tasked with creating a form validation function for a web application. The function should validate the input fields based on the given HTML structure and return an object containing the validation results.
The HTML structure for a single input field is as follows:
```html
<div class="row control-group success... | ```javascript
function validateForm(inputFields) {
const validationResults = {};
inputFields.forEach(field => {
const { name, value, required } = field;
const isValid = !required || (required && value.trim() !== '');
if (isValid) {
validationResults[name] = { valid: true, message: '' };
} el... | magicoder | javascript |
You are tasked with implementing a simplified version of a Laplace solver for a 2D grid. The Laplace equation is a second-order partial differential equation named after Pierre-Simon Laplace, which describes the distribution of heat in a given region. In this problem, you will be asked to write a function to solve the ... | ```cpp
#include <iostream>
#include <vector>
class Step3 {
private:
int rows, cols;
std::vector<std::vector<double>> grid;
public:
Step3(int rows, int cols) : rows(rows), cols(cols), grid(rows, std::vector<double>(cols, 0.0)) {}
void run() {
const int max_iterations = 1000;
const doub... | magicoder | cpp |
You are tasked with implementing a command-line interface (CLI) for a simple note-taking application. The CLI should support the following subcommands: "add", "view", "delete", and "list". Each subcommand should perform a specific action as described below:
1. "add": This subcommand should allow the user to add a new ... | ```python
class NoteTakingApp:
def __init__(self):
self.notes = {}
def add_note(self, title, content):
self.notes[title] = content
def view_note(self, title):
if title in self.notes:
return self.notes[title]
else:
return "Note not found."
def de... | magicoder | python |
You are tasked with creating a program to traverse dependencies in a software project. The program should be able to handle visiting different project components and returning appropriate codes based on the success or failure of the visit.
Your task is to implement a method `TraverseDependencies` in the `DependencyVis... | ```csharp
public class DependencyVisitorAlgorithm
{
public int TraverseDependencies(IVisitor visitor, IFileSystem fileSystem, IGitDependFileFactory factory, IGit git, List<string> visitedDependencies)
{
foreach (var dependency in visitedDependencies)
{
var visitResult = visitor.Visit... | magicoder | csharp |
You are tasked with implementing a simple game where the player has to guess a randomly generated number. The game should provide the player with feedback on whether their guess is too high, too low, or correct. You are given a code snippet that includes the `random` function from the `rand` crate in Rust. Your task is... | ```rust
use std::ops::RangeInclusive;
use std::io;
fn guessing_game(range: RangeInclusive<u32>) -> u32 {
let secret_number = rand::random::<u32>() % (range.end() - range.start() + 1) + range.start();
let mut num_guesses = 0;
loop {
println!("Please guess a number between {} and {}: ", range.start(... | magicoder | rust |
You are tasked with implementing a timer class that triggers a callback function at regular intervals. Your goal is to create a Timer class template that takes a duration and a callback function as parameters. The timer should be able to trigger the callback function at regular intervals specified by the duration. Addi... | ```cpp
#include <iostream>
#include <functional>
#include <chrono>
#include <thread>
template <typename Duration>
class Timer {
public:
Timer(const Duration& interval, const std::function<void()>& callback, bool autoStart = false)
: interval_(interval), callback_(callback), autoStart_(autoStart), running_(... | magicoder | cpp |
You are tasked with creating a unit test for a Swift class that handles APDU (Application Protocol Data Unit) commands for a card reader provider API. The class being tested is `APDUCommand` and it is a part of the `CardReaderProviderApi` module. The test class is a subclass of `XCTestCase` and uses the `Nimble` framew... | ```swift
@testable import CardReaderProviderApi
import Foundation
import Nimble
import XCTest
final class APDUCommandTest: XCTestCase {
// Test case for creating an APDU command with valid parameters
func testCreateAPDUCommand() {
let apduCommand = APDUCommand(instruction: 0x00, parameter1: 0x00, param... | magicoder | swift |
You are tasked with implementing a simple benchmarking program using the Rust programming language. The code snippet provided is a part of a Rust program that utilizes the `criterion` crate for benchmarking. The `criterion_group!` macro is used to define a group of benchmarks, and the `criterion_main!` macro is used to... | ```rust
use criterion::{criterion_group, criterion_main, Criterion};
// Quick Sort implementation
fn quick_sort(arr: &mut [i32]) {
if arr.len() <= 1 {
return;
}
let pivot = arr.len() / 2;
let mut left = 0;
let mut right = arr.len() - 1;
while left <= right {
while arr[left] < ar... | magicoder | rust |
You are tasked with implementing a stock price stream aggregator that combines data from multiple providers into a single stream for further processing. The `StreamAggregator` class has been provided with the initial setup for managing multiple streams and aggregating their data. Your task is to complete the implementa... | ```csharp
using System;
using System.Reactive.Subjects;
using System.Threading;
using System.Diagnostics;
public class StreamAggregator
{
private Subject<Tick> _priceUpdateStream = new Subject<Tick>();
private Subject<long> _totalTickCountStream = new Subject<long>();
private long _totalTickCount;
priv... | magicoder | csharp |
You are given a snippet of code that is part of a larger program. The code snippet is responsible for manipulating a heap data structure and creating two vectors based on the heap's contents. Your task is to implement a function that takes an array of values and performs the same operations as the code snippet.
You ne... | ```cpp
#include <vector>
#include <queue>
#include <cmath>
std::pair<std::vector<size_t>, std::vector<int>> processHeap(const std::vector<int>& values, int k) {
std::priority_queue<int, std::vector<int>, std::greater<int>> heap;
for (int i = 0; i < k; i++) {
heap.push(values[i]);
}
for (int i... | magicoder | cpp |
You are tasked with creating a web form for a service center that offers various services with different discount rates. The form should allow users to input the original price of a service, select the service center location, and choose the type of service. Upon submission, the form should calculate the final price af... | ```javascript
function calculateFinalPrice(originalPrice, serviceCenter, serviceType) {
const discountRates = {
"serviceCenters": {
"center1": {
"discountRate": 0.1
},
"center2": {
"discountRate": 0.15
}
},
"serviceTypes": {
"type1": {
"discountRate": ... | magicoder | javascript |
You are working on a project that involves analyzing a network of bike-sharing stations in a city. The code snippet provided is a part of the data processing and visualization pipeline. The code uses the `nxviz` library to create a geographical plot of the bike-sharing station network. The network is represented as a g... | ```python
# Missing arguments for GeoPlot object
g = GeoPlot(
G_new,
node_lat="latitude",
node_lon="longitude",
node_color="blue",
node_size=20,
edge_color="gray",
bgcolor="white"
)
import networkx as nx
def average_distance_between_nodes(graph):
total_distance = 0
num_pairs = 0
... | magicoder | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.