query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with simulating a multi-threaded communication system in a software application. The system consists of several threads responsible for different communication protocols and devices. Your goal is to implement a mechanism to ensure that all threads are properly synchronized and terminated when the communi... | ```python
import threading
def terminate_communication_system(tcp_thread, udp_thread, transceiver, transform_thread, arduino_thread):
try:
# Join TCP thread
tcp_thread.join()
# Join UDP thread
udp_thread.join()
# Stop transceiver
transceiver.stop()
... | magicoder | python |
You are tasked with implementing a class for creating silhouettes of 3D objects in a CAD (Computer-Aided Design) software. The silhouette is the outline of an object when viewed from a specific direction. Your goal is to create a `Silhouette` class that can generate the silhouette of a given face of a 3D object.
The `... | ```python
from fscad.fscad import Face, Vector3D, Point3D, Plane
import adsk.core
class Silhouette:
def __init__(self, face, viewing_plane):
self.face = face
self.viewing_plane = viewing_plane
def create_occurrence(self, generate_occurrence):
# Generate the silhouette and create an occ... | magicoder | python |
You are tasked with creating a Python function that checks whether a given Spatial Reference ID (SRID) has the meter unit. In the context of geospatial data, an SRID is a unique identifier for a specific coordinate system, and the meter unit is commonly used for measuring distances in such systems.
Write a function `c... | ```python
def check_srid_has_meter_unit(srid: int) -> bool:
meter_unit_srids = {3857, 900913, 3785} # Common SRIDs using meter unit
return srid in meter_unit_srids
```
The solution defines the function `check_srid_has_meter_unit` that takes an integer `srid` as input and returns `True` if the given SRID is pr... | magicoder | python |
You are tasked with creating a reinforcement learning (RL) environment for training an agent to learn the identity function. The RL environment takes a single input and produces the same value as the output. The code snippet provided initializes various RL models and their hyperparameters for learning the identity func... | To solve this problem, you can follow these steps:
1. Define the RL environment for learning the identity function:
- Create a custom RL environment that takes a single input and produces the same value as the output. This environment should implement the necessary methods such as `step`, `reset`, and `render`.
2.... | magicoder | python |
You are tasked with implementing a memory copy function for a custom memory management system. The function `copy_address_raw` takes in a source object `source` and an address `addr` to start copying from. It also takes a `length` parameter indicating the number of bytes to copy. The function should handle potential er... | ```rust
#[derive(Debug)]
enum MemoryCopyError {
RequestTooLarge(usize),
ProcessEnded,
CustomError,
}
trait CopyAddress {
fn copy_address(&self, addr: usize, buffer: &mut [u8]) -> Result<(), std::io::Error>;
}
const MAX_COPY_LENGTH: usize = 1024;
fn copy_address_raw<T: CopyAddress>(
source: &T,
... | magicoder | rust |
You are tasked with creating a program that automates the process of checking and validating shell scripts. Your program should take a list of file paths as input and perform the following steps for each file:
1. Check if the file is a Bourne shell script.
2. If the file is a Bourne shell script, run a shellcheck to en... | ```bash
#!/bin/bash
for file in "$@"; do
if file "$file" | grep Bourne; then
shellcheck -s bash "$file"
if [ $? -eq 0 ]; then
echo "[ok] $file shellcheck pass"
else
echo "[error] $file shellcheck failed"
fi
else
echo "[error] $file is not a Bourne... | magicoder | shell |
You are tasked with implementing a data validation algorithm for a specific data format used in a communication protocol. The data is represented as an array of bytes, and certain conditions must be met for the data to be considered valid. Your task is to write a function that takes the data array as input and performs... | ```csharp
using System;
public class DataValidator
{
public static bool ValidateData(byte[] data)
{
byte[] IDm = data[1..9]; // Extract sub-array containing elements at indices 1 to 8
byte StatusFlag1 = data[9];
byte StatusFlag2 = data[10];
if (StatusFlag1 == 0x00 && data.Lengt... | magicoder | csharp |
You are tasked with creating a program that simulates a simple command-line interface for managing a list of tasks. The program should allow users to add, remove, and list tasks, as well as mark tasks as completed.
Your task is to implement the `TaskManager` class, which should provide the following functionality:
- `... | ```python
class TaskManager:
def __init__(self):
self.tasks = []
def add_task(self, task_description):
self.tasks.append({"description": task_description, "completed": False})
def remove_task(self, task_id):
if 1 <= task_id <= len(self.tasks):
del self.tasks[task_id - 1... | magicoder | python |
You are tasked with implementing a function that manages the exports of a module in a programming language. The function should add a new export to the module, but if there is a conflicting export with the same name, it should return an error.
You are given the following code snippet as a reference:
```rust
if let So... | ```rust
impl Exports {
fn add(&mut self, new_export: &Export, c: Export) -> Option<Export> {
if let Some(existing_export) = self.get_export_by_name(new_export.name) {
Some(existing_export)
} else {
self.add_export(new_export, c);
None
}
}
fn get_e... | magicoder | rust |
You are tasked with creating a Python program to read and display sensor data from the "SparkFun Atmospheric Sensor Breakout - BME280 (Qwiic)" connected to an "Adafruit Feather STM32F405 Express" microcontroller using STEMMAQT. The sensor provides temperature, humidity, and pressure data, which should be displayed in a... | ```python
import time
import board
import busio
import adafruit_bme280
# Initialize I2C connection
i2c = busio.I2C(board.SCL, board.SDA)
# Initialize BME280 sensor
bme280 = adafruit_bme280.Adafruit_BME280_I2C(i2c)
# Optional settings:
bme280.sea_level_pressure = 1013.25 # Set this to the current sea level pressure ... | magicoder | python |
You are tasked with implementing a communication protocol for a microcontroller-based system. The system consists of a central controller and multiple peripheral devices, each equipped with encoders to measure rotational movement. The central controller needs to read the encoder values from the peripheral devices using... | ```python
# Message structure for requesting encoder values
class RequestMessage:
def __init__(self, message_type, device_address):
self.message_type = message_type
self.device_address = device_address
self.payload_length = 0
def to_bytes(self):
return bytes([self.message_type, ... | magicoder | python |
You are tasked with creating a class that interacts with a RESTful API to manage exchange settings for different asset pairs. The API provides two endpoints for interacting with exchange settings: `Get` and `Add`. The `Get` endpoint retrieves the exchange settings for a given asset pair and exchange name, while the `Ad... | ```csharp
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
public class ExchangeSettingsManager
{
private readonly HttpClient _httpClient;
private readonly string _apiBaseUrl;
public ExchangeSettingsManager(string apiBaseUrl)
{
_apiBaseUrl = apiBaseUrl;... | magicoder | csharp |
You are tasked with implementing a role-based access control system for a user management application. The application uses a PHP framework called Crudvel, which provides a base User model named `UserModel`. Your task is to create a custom `User` class that extends the `UserModel` and adds the ability to modify user ro... | ```php
use Crudvel\Models\User as UserModel;
class User extends UserModel {
// Add a method to modify the role of a user
public function modifyRole($userId, $newRole) {
// Logic to modify the role of the user
// Example: Update the role in the database
$user = $this->find($userId);
... | magicoder | php |
You are tasked with creating a Python function that interacts with the USGS Earthquake API to retrieve earthquake data. The function should take in parameters for the target path, file basename, file extension, method, and additional query parameters. The function should construct a URL based on the provided parameters... | ```python
import os
import io
import requests
def retrieve_earthquake_data(tgt_path, tgt_file_basename, tgt_file_extension, method, query_params):
tgt_path = os.path.expanduser(tgt_path)
tgt_file_name = os.path.join(tgt_path, tgt_file_basename + tgt_file_extension)
base_url = 'https://earthquake.usgs.gov/... | magicoder | python |
You are tasked with implementing a class that represents a bounding box in an image. The class should support two different formats for representing the bounding box: XYWH (X-coordinate, Y-coordinate, Width, Height) and XYX2Y2 (X-coordinate, Y-coordinate, X2-coordinate, Y2-coordinate). The class should also calculate t... | ```python
from enum import Enum
class BBFormat(Enum):
XYWH = 1
XYX2Y2 = 2
class BoundingBox:
def __init__(self, format, x, y, w, h, imgSize=None):
self._format = format
self._x = x
self._y = y
self._w = w
self._h = h
self._x2 = None
self._y2 = None
... | magicoder | python |
You are tasked with implementing a custom R-squared (coefficient of determination) function in Python. The R-squared value is a statistical measure that represents the proportion of the variance for a dependent variable that's explained by an independent variable. It is often used to evaluate the performance of regress... | ```python
from sklearn.metrics import r2_score
def custom_r2_score(y_true, y_pred):
n = len(y_true)
mean_y_true = sum(y_true) / n
sum_squared_residuals = sum((y_true[i] - y_pred[i])**2 for i in range(n))
sum_squared_total = sum((y_true[i] - mean_y_true)**2 for i in range(n))
r_squared = 1 - (sum_sq... | magicoder | python |
You are tasked with creating a simple game using the PyGame library. The game will involve a player-controlled character navigating through a maze to reach a goal while avoiding obstacles. The player's character will be controlled using the arrow keys on the keyboard. The maze will be represented by a grid of cells, wi... | ```python
import pygame
import sys
# Initialize PyGame library
pygame.init()
# Define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
# Set up the game window
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Maze Game')
# D... | magicoder | python |
You are tasked with creating a script to automate the generation of SSL/TLS certificates for a web server. The script should use OpenSSL commands to generate a root certificate authority (CA) key and certificate, as well as a server key and certificate signing request (CSR).
Your script should perform the following st... | ```bash
#!/bin/bash
# Generate a 4096-bit RSA private key for the root CA with triple DES encryption
openssl genrsa -des3 -out rootca.key 4096
# Create a self-signed root certificate with a validity period of 1024 days and SHA-256 hashing
openssl req -x509 -new -nodes -key rootca.key -sha256 -days 1024 -out rootca.cr... | magicoder | shell |
You are tasked with creating a message processing system using the given code snippet as a starting point. The system should be able to handle different types of messages and process them using a message processor. Your task is to implement the necessary classes and methods to achieve this functionality.
You are provi... | ```csharp
public class MessageProcessor : IMessageProcessor
{
public void ProcessMessage(IMessage message)
{
// Implementation of message processing logic
}
}
public class MessageAdapter : IMessageAdapterWithSubscribing
{
public void Subscribe()
{
// Implementation of message subscr... | magicoder | csharp |
You are tasked with creating a function that simulates a division operation without using the division operator. The function `spam(divideBy)` takes an integer `divideBy` as input and should return a list of integers that are the result of dividing 42 by the input integer. The division should be performed using subtrac... | ```python
def spam(divideBy):
if divideBy == 0:
return "Error: Division by zero is not allowed"
result = []
dividend = 42
while dividend >= 0:
result.append(dividend)
dividend -= divideBy
return result
```
The `spam` function first checks if the input `divideBy` is 0, in whic... | magicoder | python |
You are tasked with implementing a unit conversion library in Rust. The provided code snippet initializes a module named `units`, which will contain the necessary functionality for converting between different units of measurement.
Your task is to create a Rust module that includes functions for converting between var... | ```rust
// units.rs
pub mod units {
pub mod length {
pub fn meters_to_feet(meters: f64) -> f64 {
meters * 3.28084
}
pub fn meters_to_inches(meters: f64) -> f64 {
meters * 39.3701
}
// Add more length conversion functions as needed
}
pub mod... | magicoder | rust |
You are tasked with implementing a blockchain data structure in Rust. A blockchain is a distributed ledger that stores a growing list of records, called blocks, which are linked and secured using cryptography. Each block contains a cryptographic hash of the previous block, a timestamp, and transaction data. In this pro... | ```rust
use std::time::{SystemTime, UNIX_EPOCH};
// Define the Block struct to represent a block in the blockchain
struct Block<T> {
timestamp: u64,
data: T,
previous_hash: Vec<u8>,
hash: Vec<u8>,
}
// Define the Hasher trait to specify the behavior of a hashing algorithm
trait Hasher {
fn hash(&m... | magicoder | rust |
You are tasked with implementing a 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. Your function should take two integers, `start` and `end`, as input and return the sum of all prime numb... | ```javascript
function sumOfPrimes(start, end) {
function isPrime(num) {
if (num <= 1) return false;
if (num <= 3) return true;
if (num % 2 === 0 || num % 3 === 0) return false;
let i = 5;
while (i * i <= num) {
if (num % i === 0 || num % (i + 2) === 0) return false;
i += 6;
}
... | magicoder | javascript |
You are tasked with implementing a simple Java class that manages a network connection using JavaFX. The class, named `NetworkManager`, should provide methods for setting up and tearing down the connection, as well as managing the user interface components related to the connection.
Your task is to complete the implem... | ```java
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class NetworkManager {
private TextField consoleIP;
private Button connect;
private Object ... | magicoder | java |
You are tasked with implementing a Python 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 be named `max_subarray_sum` and should adhere to the following signature:
```python
def max_subarray_sum(nums: List[int]) -> int:
... | ```python
from typing import List
def max_subarray_sum(nums: List[int]) -> int:
max_sum = float('-inf') # Initialize max_sum to negative infinity
current_sum = 0 # Initialize current_sum to 0
for num in nums:
current_sum = max(num, current_sum + num) # Update current_sum to be the maximum of th... | magicoder | python |
You are given a code snippet that appears to be part of a program analyzing access patterns in a loop nest. The snippet contains a loop and several conditional statements. Your task is to write a program that simulates the behavior of the given code snippet and determines the final value of a specific variable.
You ar... | To simulate the behavior of the given code snippet and determine the final value of the variable `loop_coeff`, we can analyze the conditional statements and loops in the code.
1. We first obtain the loop depth by calling the function `Do_Depth(wn_loop)`.
2. We then iterate over the vectors in `aa` using a for loop:
... | magicoder | python |
You are tasked with implementing a program to analyze the contours of a given image. The contours are represented as a list of arrays, where each array contains the coordinates of the contour points. The program should plot each contour and display the plot for 20 seconds before closing it.
Write a function `plot_cont... | ```python
import numpy as np
import matplotlib.pyplot as plt
def plot_contours(poly):
assert len(poly) == 4 # Ensure there are four contours
# Plot each contour
for i in range(4):
plt.plot(poly[i][:, 0], poly[i][:, 1])
plt.show(block=False) # Display the plot without blocking
plt.pause(... | magicoder | python |
You are tasked with implementing a function that processes a collection of metal lines data and returns a specific output based on the input. Each metal line is represented as an object with properties for metal type, length, and width. The function should calculate the total area of all metal lines and return the aver... | ```javascript
function calculateAverageArea(metalinesData) {
const totalArea = metalinesData.reduce((acc, metalLine) => {
return acc + (metalLine.length * metalLine.width);
}, 0);
return totalArea / metalinesData.length;
}
``` | magicoder | javascript |
You are tasked with implementing a function to process vertex input descriptions for a Vulkan graphics application. The function should take in vertex input data and return the corresponding attribute descriptions.
You are given the following code snippet as a starting point:
```cpp
static std::array<VkVertexInputAtt... | ```cpp
#include <array>
#include <vulkan/vulkan.h>
struct Vertex {
glm::vec3 position;
glm::vec3 color;
glm::vec2 textureCoord;
};
static std::array<VkVertexInputAttributeDescription, 3>
getAttributeDescriptions() {
std::array<VkVertexInputAttributeDescription, 3> attributeDescriptions = {};
// P... | magicoder | cpp |
You are tasked with creating a Python class that simulates a simple robot controller for a mobile robot. The robot controller class should be able to publish velocity commands to the robot's navigation system using the ROS (Robot Operating System) framework. Your task is to complete the implementation of the `RobotCont... | ```python
import rospy
from geometry_msgs.msg import Twist
class RobotController:
def __init__(self):
self.cmd_vel = rospy.Publisher('cmd_vel_mux/input/navi', Twist, queue_size=10)
def publish_velocity(self, linear, angular):
vel_msg = Twist()
vel_msg.linear.x = linear
vel_msg.... | magicoder | python |
You are tasked with implementing a function that manages memory allocation for a simulated assembly language program. The function should allocate memory for a specified number of data words and then place an ASCIIZ string constant at a specific memory location. The function should return the address of the ASCIIZ stri... | ```python
def allocate_memory_and_string(count: int, string_constant: str) -> int:
memory_addr = 0x123450 # Initial memory address
data_words = []
for _ in range(count):
data_words.append(memory_addr)
print("${0:06x} : dw 0".format(memory_addr))
memory_addr += 2
str... | magicoder | python |
You are tasked with implementing a simple game mechanic for a 2D grid-based game. The game involves a grid of cells, each of which can be in one of two states: filled with fluid or empty. The game starts with a certain amount of fluid distributed across the grid. The player can interact with the grid by clicking on cel... | ```csharp
public void OnCellClick(Cell clickedCell)
{
if (!_simStarted)
{
_simStarted = true;
digbutton.gameObject.SetActive(false);
}
if (clickedCell.IsFilledWithFluid())
{
clickedCell.RemoveFluid();
_remainingFluid--;
SpreadFluidToNeighbours(clickedCell);
... | magicoder | csharp |
You are tasked with creating a program that parses and analyzes a simplified version of the Bicep language, a domain-specific language for deploying Azure resources. The Bicep language is represented using a custom parser and semantic model. Your goal is to implement a function that serializes the semantic model of a B... | ```csharp
using Bicep.Core.Parser;
using Bicep.Core.SemanticModel;
using Newtonsoft.Json;
public string SerializeBicepSemanticModel(BicepProgram program)
{
JsonSerializerSettings settings = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Auto,
Formatting = Formatting.Indented /... | magicoder | csharp |
You are given a string `S` consisting of lowercase English letters. Your task is to find the number of distinct non-empty subsequences of `S`.
A subsequence of a string is a new string that is formed from the original string by deleting some (or none) of the characters without changing the relative order of the remain... | ```python
def distinctSubseqII(S: str) -> int:
res, end = 0, collections.Counter()
for c in S:
res, end[c] = res * 2 + 1 - end[c], res + 1
return res % (10**9 + 7)
```
The solution defines a function `distinctSubseqII` that takes a string `S` as input and returns the number of distinct non-empty sub... | magicoder | python |
You are tasked with implementing a media object serialization and deserialization functionality in Java. The media object represents different types of media, such as still images, videos, or audio files. Your task is to create a class that can serialize a media object into a JSON string and deserialize it back into a ... | ```java
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.net.URI;
public class MediaSerialization {
private static final ObjectMapper objectMapper = new ObjectMapper();
public static String serializeMediaObje... | magicoder | java |
You are tasked with implementing a Python function to calculate the modularity of a network using the Louvain method. Modularity is a measure of the structure of networks or graphs. It quantifies the strength of division of a network into modules (also called groups, clusters, or communities). The modularity of a parti... | ```python
from typing import List, Tuple
import networkx as nx
import community
def calculate_modularity(network_structure: List[Tuple[int, int]]) -> float:
# Create an undirected graph from the network structure
G = nx.Graph()
G.add_edges_from(network_structure)
# Detect the communities using the Lou... | magicoder | python |
You are tasked with creating a Python script to automate the download of satellite imagery using the NASA Worldview API. The provided code snippet is a bash script that iterates through a range of numbers and calls a Python script `worldview_modis_wget.py` with different parameters for each iteration. The Python script... | ```python
import argparse
import requests
import os
def download_satellite_image(index, sensor_type, image_format, image_size, bbox_coordinates):
base_url = "https://gibs.earthdata.nasa.gov/wmts/epsg4326/best"
layer = f"{sensor_type}_{image_format}_{image_size}"
tile_matrix_set = "250m"
tile_matrix = "... | magicoder | python |
You are tasked with implementing a simple factory pattern for creating server-side render services in TypeScript. The provided code snippet is a part of a class that includes a factory method and a getter method for the server-side render service. Your task is to complete the implementation by creating the necessary cl... | ```typescript
// Define an interface for the factory that creates server-side render services asynchronously
interface IFactoryAsync<T> {
(params: any[], config: any): Promise<T>;
}
// Define an interface for the server-side render service
interface IServerSideRenderService {
// Define the methods and properties o... | magicoder | typescript |
You are tasked with implementing a Pomodoro timer in Python. The Pomodoro Technique is a time management method developed by Francesco Cirillo in the late 1980s. It uses a timer to break work into intervals, traditionally 25 minutes in length, separated by short breaks. The following code snippet is a part of a Python ... | ```python
def start_timer(self):
def count_down():
if self.__mins == 0 and self.__secs == 0:
self.__clock.config(text="Pomodoro interval ended")
return
if self.__secs == 0:
self.__mins -= 1
self.__secs = 59
else:
self.__secs -= 1
... | magicoder | python |
You are tasked with implementing a Python function that simulates a simplified version of a database migration system. The function will take a list of migration operations and execute them in the specified order. Each migration operation is represented as a dictionary with 'code' and 'reverse_code' keys, where the val... | ```python
from typing import List, Dict, Callable
def execute_migrations(operations: List[Dict[str, Callable]]) -> bool:
executed_operations = []
try:
for operation in operations:
operation['code']()
executed_operations.append(operation)
except Exception as e:
for op... | magicoder | python |
You are tasked with implementing a data validation function that checks and updates a dictionary based on custom attributes and limits. The function takes in a custom attributes dictionary, a section, and a value to be validated. The custom attributes dictionary contains sections, each with keys and their corresponding... | ```python
import logging
def validate_and_update(custom_attributes_dict, section, value):
section_dict = custom_attributes_dict.get(section, {})
if section_dict:
for key, attr in custom_attributes_dict[section].items():
type_attr = attr['type']
limits = attr['limits']
... | magicoder | python |
You are working on a project to develop a cloud storage management system. As part of this project, you need to implement a class hierarchy for account information and storage management. The code snippet provided includes two methods from different classes: `get_minimum_part_size` and `get_s3_api_url`.
Your task is t... | ```python
class OldAccountInfoMethods:
def get_recommended_part_size(self):
# Implement the logic to calculate and return the recommended part size for storage management
pass # Placeholder for implementation
class MissingAccountData(Exception):
pass # Placeholder for custom exception defini... | magicoder | python |
You are tasked with implementing a data service class in TypeScript for handling HTTP requests and errors. The class should include methods for making HTTP requests and handling errors using Observables and Promises.
Your task is to complete the implementation of the DataService class by adding the missing methods and... | ```typescript
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
import { Http, Response } from '@angular/http';
export class DataService {
constructor(private http: Http) {}
getData(url: string): Observable<any> {
... | magicoder | typescript |
You are tasked with creating a Swift function that retrieves and processes images from the Photos library using the PhotoKit framework. Your function should take an asset, a target size, and a completion handler as input parameters. The function should use the PHImageManager to request the image for the given asset, wi... | ```swift
import Photos
func retrieveAndProcessImage(asset: PHAsset, size: CGSize, completion: @escaping (UIImage?) -> Void) {
let imageManager = PHImageManager.default()
let requestOptions = PHImageRequestOptions()
requestOptions.deliveryMode = .highQualityFormat
requestOptions.isNetworkAccessAllowed =... | magicoder | swift |
You are tasked with implementing a custom data structure in Swift that mimics the functionality of a stack, but with an added feature. The stack should support the usual push and pop operations, but it should also have a method that returns the minimum element in the stack at any given time. Your task is to design and ... | ```swift
class MinStack {
private var stack: [(value: Int, min: Int)] = []
func push(_ x: Int) {
if stack.isEmpty {
stack.append((x, x))
} else {
let currentMin = min(x, getMin())
stack.append((x, currentMin))
}
}
func pop() {
stack.... | magicoder | swift |
You are tasked with implementing a module dependency resolution algorithm for a simple programming language. The language consists of modules, each defined in a separate file. Modules can depend on other modules, and the dependencies are specified using `mod` statements at the beginning of each file. For example, the f... | ```rust
fn resolve_module_dependencies(modules: &[(String, Vec<String>)]) -> Result<Vec<String>, String> {
let mut graph: HashMap<String, Vec<String>> = HashMap::new();
let mut in_degree: HashMap<String, usize> = HashMap::new();
// Build the graph and calculate in-degrees
for (module, dependencies) in ... | magicoder | rust |
You are working on a software system that manages the importation of agents from external files. The system provides two methods for this purpose:
1. `boolean areImported()`: This method checks whether the agents have been successfully imported from the external files. It returns `true` if the agents are imported, and... | ```java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class AgentImporter {
private boolean agentsImported;
private String agentsContent;
public AgentImporter() {
agentsImported = false;
agentsContent = "";
}
... | magicoder | java |
You are tasked with implementing a Python class decorator that adds functionality to track the number of times a specific method is called within a class. The decorator should be able to track the number of calls for each instance of the class separately. You are provided with a code snippet that demonstrates the usage... | ```python
def track_calls(method):
def wrapper(self, *args, **kwargs):
if self not in method.__self__.call_counts:
method.__self__.call_counts[self] = {}
if method.__name__ not in method.__self__.call_counts[self]:
method.__self__.call_counts[self][method.__name__] = 0
... | magicoder | python |
You are tasked with implementing a filtering system for a product inventory. The system should support various filter clauses, including terms filters and boolean filters. A sample code snippet is provided below to illustrate the usage of the filtering system:
```java
booleanFilter.add(new FilterClause(getTermsFilter(... | ```java
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanFilter;
import org.apache.lucene.search.FilterClause;
import org.apache.lucene.search.TermFilter;
public class InventoryFilterSystem {
public static TermFilter getTermsFilter(String fieldName, String value) {
retu... | magicoder | java |
You are working on a project that involves optimizing a scheduling problem using a combination of heuristics and integer linear programming (ILP). The project involves the use of various modules and utilities to generate and solve the scheduling problem.
Your task is to create a Python function that takes in a set of ... | ```python
import numpy as np
import heuristics
import ilp
import utils
import generator
def generate_optimized_schedule(constraints):
# Generate initial schedule using the generator module
initial_schedule = generator.generate_initial_schedule(constraints)
# Apply heuristics to improve the initial schedul... | magicoder | python |
You are tasked with implementing a key-value list data structure in Rust. The data structure should support adding key-value pairs, removing key-value pairs, and retrieving the value associated with a given key. Additionally, the data structure should allow for iterating over the key-value pairs in the list.
You need ... | ```rust
pub struct KeyList {
data: Vec<(String, i32)>,
}
impl KeyList {
pub fn new() -> KeyList {
KeyList { data: Vec::new() }
}
pub fn insert(&mut self, key: String, value: i32) {
if let Some((_, v)) = self.data.iter_mut().find(|(k, _)| k == &key) {
*v = value;
} e... | magicoder | rust |
You are tasked with implementing a simple text editor class in Python. The class should support the following operations:
1. `insert(text)`: Insert the given text at the current cursor position.
2. `delete(n)`: Delete the last n characters from the current cursor position.
3. `move_cursor(steps)`: Move the cursor forw... | ```python
class TextEditor:
def __init__(self):
self.text = ""
self.cursor_position = 0
def insert(self, text):
self.text = self.text[:self.cursor_position] + text + self.text[self.cursor_position:]
self.cursor_position += len(text)
def delete(self, n):
if self.curs... | magicoder | python |
You are tasked with creating a Python program to monitor the state of two input pins connected to a Raspberry Pi GPIO. The program should detect button presses on these pins and perform specific actions based on the detected input. Additionally, the program should capture images using the PiCamera module and display a ... | ```python
import RPi.GPIO as GPIO
from time import sleep
from picamera import PiCamera
import datetime
# Set up GPIO mode and pins
GPIO.setmode(GPIO.BOARD)
GPIO.setup(16, GPIO.IN, pull_up_down=GPIO.PUD_UP) # "Sign in" button
GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP) # "Sign out" button
camera = PiCamera()
... | magicoder | python |
You are tasked with implementing a priority queue data structure in Python using a class called `PriorityQueue`. The `PriorityQueue` class should support the following operations:
1. `insert(value, priority)`: Insert a new value with a given priority into the priority queue.
2. `pop()`: Remove and return the value with... | ```python
class PriorityQueue:
def __init__(self):
self.queue = []
def insert(self, value, priority):
self.queue.append((value, priority))
self.queue.sort(key=lambda x: x[1], reverse=True)
def pop(self):
if not self.queue:
return None
return self.queue.p... | magicoder | python |
You are working on a project where you need to organize various PHP packages and their associated directories. The project uses a configuration file that maps each package to its corresponding directories. The configuration file follows a specific format where each line consists of the package name followed by its asso... | ```python
import re
def parse_package_directories(config_file: str) -> dict:
package_directories = {}
lines = config_file.split('\n')
for line in lines:
if line.strip(): # Check if the line is not empty
package, directories = line.split('=>')
package_name = package.strip().... | magicoder | python |
You are tasked with implementing a simple blockchain smart contract in Rust for managing the prices of different alloys. The smart contract will allow updating the price of an alloy identified by its unique ID. The code snippet provided includes Rust structs for the smart contract and the arguments required to update t... | ```rust
use borsh::{BorshSerialize, BorshDeserialize};
#[derive(Debug, BorshSerialize, BorshDeserialize, Clone, PartialEq)]
pub struct Alloy {
pub id: u8,
pub price: u64,
}
#[derive(Debug, BorshSerialize, BorshDeserialize, Clone, PartialEq)]
pub struct UpdateAlloyPriceArgs {
pub id: u8,
pub price: u64... | magicoder | rust |
You are tasked with implementing a simple arithmetic expression parser and evaluator in Python. Your goal is to create a program that can take a mathematical expression as a string, build a parse tree from it, and then evaluate the expression by traversing the parse tree.
Your task is to implement the `parse_string_to... | ```python
# Import the necessary library for parsing
import pyauparser
# Define the parse_string_to_tree function
def parse_string_to_tree(grammar, expr):
try:
tree = pyauparser.parse_string_to_tree(grammar, expr)
return tree
except pyauparser.ParseError as e:
raise e
# Define the eval... | magicoder | python |
You are tasked with implementing a class that manages grades for students. The class should allow for the storage and retrieval of grades for different subjects. You are provided with a partial code snippet for a `Grade` class in PHP, which includes the `fillable` attribute for mass assignment and a comment indicating ... | ```php
class Grade extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'user_id', 'subject', 'grade',
];
/**
* Relations
*/
public function user()
{
return $this->belongsTo(User::class);
}
... | magicoder | php |
You are tasked with implementing a simple scanner for a programming language. The scanner should be able to identify and classify different tokens such as identifiers and numbers. Your task is to complete the implementation of the `Scanner` struct by adding the necessary methods to handle identifiers and numbers.
The ... | ```rust
struct Scanner {
// Other fields and methods are not shown for brevity
fn identifier(&mut self) {
while Scanner::is_alphanumeric(self.peek()) {
self.advance();
}
self.add_token(TokenType::Identifier);
}
fn number(&mut self) -> Result<(), CfgError> {
... | magicoder | rust |
You are tasked with creating a Python function that processes a list of integers and returns the maximum sum that can be obtained by selecting a contiguous subarray from the input list. The function should be named `max_subarray_sum` and should take a single parameter: `arr`, a list of integers. The function should ret... | ```python
def max_subarray_sum(arr):
max_sum = arr[0]
current_sum = arr[0]
for num in arr[1:]:
current_sum = max(num, current_sum + num)
max_sum = max(max_sum, current_sum)
return max_sum
```
The `max_subarray_sum` function initializes `max_sum` and `current_sum` with the first element... | magicoder | python |
You are working on a system that manages network connections using NetworkManager. The given code snippet is a part of a script that sets up a persistent storage for NetworkManager keyfile configurations. The script ensures that the persistent storage is mounted and accessible to NetworkManager for reading and writing ... | ```bash
setup_network_manager_storage() {
mkdir -p /etc/NetworkManager/system-connections
if ! mountpoint /etc/NetworkManager/system-connections ; then
mkdir -p $PERSIST_ROOT/skiff/connections
echo "# Place NetworkManager keyfile configs here." > $PERSIST_ROOT/skiff/connections/readme
c... | magicoder | shell |
You are tasked with implementing a simple 3D camera movement system in a game engine. The given code snippet is a part of the camera movement logic. The camera is controlled by the arrow keys, and the movement is based on the state of these keys. The camera's position and target are updated based on the key states, and... | ```cpp
if (GetAsyncKeyState(VK_UP) & 0x8000f)
{
d3d_cube.v_Translate += D3DXVECTOR3(0.0f, 1.0f * timeDelta, 0.0f);
d3d_cube.SetTranslation(d3d_cube.v_Translate);
this->position += D3DXVECTOR3(0.0f, 1.0f * timeDelta, 0.0f);
this->target += D3DXVECTOR3(0.0f, 1.0f * timeDelta, 0.0f);
this->UpdateCamera();
}
... | magicoder | cpp |
You are working on a data visualization project and need to create a Python program that generates a scatter plot with a line connecting the points. The data is stored in a pandas DataFrame `df` with two columns: 'x' and 'y'. You want to use the ggplot library to achieve this visualization.
Write a Python function `ge... | ```python
import pandas as pd
from ggplot import *
def generate_scatter_with_line(df):
gg = ggplot(df, aes(x='x', y='y')) + geom_point() + geom_line()
print(gg)
```
In this solution, we import the necessary libraries and define the function `generate_scatter_with_line(df)`. Inside the function, we use the ggp... | magicoder | python |
You are tasked with implementing a benchmarking function for a `ChunkPosition` struct in a game development context. The `ChunkPosition` struct represents a position within a game world, and the benchmarking function aims to measure the performance of the `surrounding_chunks` method for different chunk sizes.
The `chu... | ```rust
extern crate criterion;
use criterion::{black_box, Criterion};
// Define the ChunkPosition struct representing a position within the game world
struct ChunkPosition {
// Define the fields representing the position within the game world
x: i32,
y: i32,
z: i32,
}
impl ChunkPosition {
// Imp... | magicoder | rust |
You are tasked with implementing a logging system similar to the NLogger class. The NLogger class is responsible for logging messages with different levels of severity. Your task is to create a class that can handle logging messages with various severity levels and provide a method to retrieve the logged messages.
You... | ```csharp
using System;
using System.Collections.Generic;
public enum LogLevel
{
Debug,
Info,
Warning,
Error,
Fatal
}
public class LogMessage
{
public LogLevel Level { get; set; }
public DateTime Timestamp { get; set; }
public string Message { get; set; }
}
public class Logger
{
p... | magicoder | csharp |
You are tasked with creating a program that automates the process of fetching and verifying the binary target for a specific library in an iOS project. The binary target is hosted at a URL that includes the release tag, and it requires a checksum for verification. Your program should be able to dynamically construct th... | ```swift
import Foundation
import CryptoKit
// Define the release tag
let releaseTAG = "v1.2.3" // Example release tag
// Construct the URL for the binary target using the release tag
let baseURL = "https://github.com/approov/approov-ios-sdk-bitcode/releases/download/"
let binaryTargetURL = URL(string: baseURL + rele... | magicoder | swift |
You are tasked with creating a Python function that processes a list of dates and returns the count of unique years present in the list. Each date in the list is represented as a string in the format "MM/DD/YYYY". The function should ignore duplicate years and only consider unique years present in the list.
The functi... | ```python
from typing import List
def count_unique_years(dateList: List[str]) -> int:
unique_years = set() # Using a set to store unique years
for date in dateList:
year = date.split("/")[-1] # Extracting the year part from the date
unique_years.add(year) # Adding the year to the set (ignore... | magicoder | python |
You are tasked with implementing a generative model class in Python. The class should have methods for training the model and generating new data based on the learned patterns. The provided code snippet is a part of the generative model class, and you need to complete the implementation by adding the missing parts.
Yo... | ```python
def generate(self, x_data, count, reset_increment=-1, warmup_timesteps=0):
"""
Given a single datapoint, the model will feed this back into itself
to produce generative output data.
x_data : data to generate from (the first data point will be used unless reset_inc... | magicoder | python |
You are tasked with creating a migration operation for a Django application. The application has a model named `CommitteeMember` in an app called `history`. The migration operation involves altering a field in the `CommitteeMember` model.
Your task is to write a migration operation that alters the field named `member`... | ```python
def generate_migration_operation(app_name, model_name, field_name):
# Construct the migration operation code
migration_operation = f"migrations.AlterField(" \
f"model_name='{model_name}', " \
f"name='{field_name}', " \
f"fie... | magicoder | python |
You are tasked with implementing a function that calculates the sum of all even Fibonacci numbers up to a given limit. The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. For example, the first few numbers in the Fibonacci sequence are ... | ```rust
fn even_fibonacci_sum(limit: u64) -> u64 {
let (mut a, mut b) = (1, 2);
let mut sum = 0;
while b <= limit {
if b % 2 == 0 {
sum += b;
}
let next = a + b;
a = b;
b = next;
}
sum
}
fn main() {
let limit = 10;
println!("Sum of even ... | magicoder | rust |
You are working on a web application that utilizes serverless architecture on AWS Lambda. The application involves rendering images and tracking the progress of the rendering process. You have been provided with a code snippet from a TypeScript file that exports some types and functions related to this application. You... | ```typescript
function calculateRemainingTime(progress: RenderProgress): string {
if (progress < 0 || progress > 100) {
throw new Error('Invalid progress value. Progress should be between 0 and 100.');
}
// Assuming linear progress and constant time per percentage
const timePerPercentage = 10; ... | magicoder | typescript |
You are tasked with implementing a Python program to perform steganography, a technique of hiding secret data within an ordinary, non-secret file or message. In this problem, you will be working with the `enStego` function, which takes three arguments: the source file, the stego file, and the message to be hidden. The ... | ```python
import sys
def enStego(source_file, stego_file, message):
with open(source_file, 'rb') as source:
source_data = bytearray(source.read())
with open(stego_file, 'wb') as stego:
stego.write(source_data)
# Embed the message into the stego file
message_bits = ''.join(form... | magicoder | python |
You are tasked with implementing a custom caching mechanism for a mapping function in Python. The goal is to optimize the performance of the mapping function by storing previously computed mappings in a cache.
You are given a class `MappingCache` with the following attributes and methods:
- `base`: A sequence of value... | ```python
class MappingCache:
def __init__(self, base, map_func):
self.base = base
self.map = map_func
self._mapping_cache = {}
self._cache_iterator = iter(self.base)
def get_original_value(self, mapped_value):
if mapped_value in self._mapping_cache:
return s... | magicoder | python |
You are tasked with implementing a simple presentation system in Swift using protocols and delegates. You are given a protocol `Presentable` and a protocol `PresentationDelegate` as follows:
```swift
import UIKit
protocol Presentable: class {
var presentationDelegate: PresentationDelegate? { get set }
}
protocol... | ```swift
class PresentationManager: Presentable, PresentationDelegate {
var presentationDelegate: PresentationDelegate?
func present() {
print("Presentation is starting")
}
func startPresentation() {
presentationDelegate?.present()
}
}
``` | magicoder | swift |
You are tasked with creating a Python program to automate the process of web scraping multiple pages of a website. The website contains a series of pages, and the goal is to extract specific information from each page. The code snippet provided gives a glimpse of the process, including writing the page content to a fil... | ```python
from selenium import webdriver
import time
# Set up the web driver (e.g., Chrome driver)
driver = webdriver.Chrome()
# Navigate to the initial page of the website
driver.get("https://www.example.com")
# Write the content of the initial page to a file named "page.htm"
with open("page.htm", "wb+") as file:
... | magicoder | python |
You are tasked with creating a Python decorator that logs the execution time of a function and prints the result to the console. The decorator should be able to handle functions with any number of arguments and keyword arguments. Additionally, the decorator should be able to handle functions that return a value or func... | ```python
import time
import functools
def log_execution_time(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
execution_time = round(end_time - start_time, 4)
if result is not None... | magicoder | python |
You are tasked with implementing a file persistence module in a Node.js application. The file persistence module should provide a way to save and retrieve data from files. You are provided with a partial code snippet that exports the `FilesFilePersistence` class from the `FilesFilePersistence.js` file. Your task is to ... | ```javascript
// FilesFilePersistence.js
import fs from 'fs';
export class FilesFilePersistence {
saveData(fileName, data) {
try {
fs.writeFileSync(fileName, data);
console.log(`Data saved to ${fileName} synchronously.`);
} catch (error) {
throw new Error(`Error saving data to ${fileName}:... | magicoder | javascript |
You are given a dataset containing the results of a classification model. The dataset consists of true positive (TP), false positive (FP), true negative (TN), and false negative (FN) values for each class in the classification. Your task is to calculate the F1 score for each class and then compute the macro F1 score.
... | ```python
def calculate_f1_score(dataset):
f1_scores = []
precision = []
recall = []
for values in dataset:
tp, fp, tn, fn = values
precision.append(0 if (tp + fp) == 0 else tp / (tp + fp))
recall.append(0 if (tp + fn) == 0 else tp / (tp + fn))
for p, r in zip(preci... | magicoder | python |
You are given a positive integer `n`. Your task is to write a function that takes `n` as input and returns the result of reversing the sign of `n` and then reversing the digits of the resulting number.
For example, if `n` is 123, the function should return -321. If `n` is -456, the function should return 654.
Write a... | ```python
def reverse_sign_and_digits(n: int) -> int:
# Reverse the sign of n
n = n * (-1)
# Convert n to string to reverse its digits
n = str(n)
# Reverse the digits of n
n = n[::-1]
# Convert n back to integer
n = int(n)
return n
``` | magicoder | python |
You are given a string containing only parentheses, square brackets, curly braces, and angle brackets. Your task is to write a function to determine if the input string is valid based on the arrangement of the brackets. A string is considered valid if all the brackets are properly closed in the correct order. The openi... | ```rust
fn is_valid(input: &str) -> bool {
let mut stack: Vec<char> = Vec::new();
for c in input.chars() {
match c {
'(' | '[' | '{' | '<' => stack.push(c),
')' => {
if stack.pop() != Some('(') {
return false;
}
}
... | magicoder | rust |
You are tasked with implementing a function that generates an indented representation of a hierarchical structure. The function takes an object `obj` and returns a string representing the object's position within the hierarchy. The indentation is based on the level of the object within the hierarchy, and special charac... | ```python
def generate_indented_representation(obj):
level = getattr(obj, obj._mptt_meta.level_attr)
indent = max(0, level - 1) * '│'
if obj.parent:
last = ((obj.parent.rght - obj.rght == 1) and
(obj.rght - obj.lft == 1))
if last:
indent += '└ '
else:
... | magicoder | python |
You are tasked with creating a Python function that measures the time taken to execute a given function and prints the duration in seconds. Your function should take another function as an argument and return the duration of its execution. You should use the `time` module to achieve this.
Your task is to implement the... | ```python
import time
def measure_execution_time(func):
start = time.time()
func()
end = time.time()
duration = end - start
print('Operation done in {} seconds'.format(duration))
return duration
# Example usage
def example_function():
time.sleep(2)
duration = measure_execution_time(exampl... | magicoder | python |
You are tasked with implementing a simple message loop system for a plugin framework. The provided code snippet is a part of the framework and is responsible for waiting for a request from a plugin. If a specific cookie is found, the function returns immediately. Otherwise, it creates a new `MessageLoopRunner` object a... | ```cpp
#include <queue>
#include <functional>
class MessageLoopRunner {
public:
void Run() {
running_ = true;
while (running_) {
if (!message_queue_.empty()) {
std::function<void()> message = message_queue_.front();
message_queue_.pop();
message();
}
}
}
void Stop... | magicoder | cpp |
You are tasked with creating a Python function that processes a list of Django migration files and extracts information about the fields being added to a specific model. Each migration file is represented as a string containing Python code. The function should extract the model name, field name, and field type for each... | ```python
from typing import List, Tuple
import re
def extract_migration_fields(migration_files: List[str], model_name: str) -> List[Tuple[str, str, str]]:
fields = []
for migration_file in migration_files:
model_pattern = r"model_name='{}'".format(model_name)
matches = re.findall(model_pattern... | magicoder | python |
You are tasked with implementing a Python class for a Blinn-Phong light source, which calculates the lighting effects on a surface based on its material properties and the incoming light direction. The Blinn-Phong lighting model is a popular shading model in computer graphics, combining diffuse and specular lighting co... | ```python
class BlinnPhongLight(Light):
def __init__(self, direction: "Vector", intensity: float, diffuse: Color, specular: Color):
super().__init__(intensity, diffuse, specular)
self.direction = direction.normalize() # Just to be sure it's a unit vector
def light(self, ray: "Ray", distance: f... | magicoder | python |
You are tasked with creating a Python function that formats and prints a set of tips for running specific commands. The function should take in the purpose of the command and the command itself, and then print the formatted tips with indentation and color.
Create a function called `print_command_tips` that takes two p... | ```python
class Layout:
INDENT = " "
class Colors:
BOLD = "\033[1m"
ENDC = "\033[0m"
def print_command_tips(purpose, cmd):
print(Layout.INDENT * 3 + "Tips:")
print(Layout.INDENT * 3 + "please run the following command to {}".format(purpose))
print(Layout.INDENT * 4 + Colors.BOLD + cmd + Col... | magicoder | python |
You are tasked with creating a Python function that interacts with Google Drive and rclone to upload a file and generate a shareable link. Your function should take the file's absolute path and the destination directory on Google Drive as input and return the shareable link.
You are provided with the following code sn... | ```python
import os
import subprocess
def upload_and_get_drive_url(absolute_file_path: str, destination_directory: str) -> str:
if "RCLONE_CONFIG_COLAB_TOKEN" not in os.environ:
raise EnvironmentError("Missing rclone environment variables")
# Upload the file to Google Drive using rclone
upload_com... | magicoder | python |
You are tasked with implementing a simple number manipulation class in Rust. The class, `Number`, should have the following functionalities:
1. `new`: A function that takes an integer as input and creates a new `Number` instance.
2. `add`: A method that takes another `Number` instance as input and returns a new `Numbe... | ```rust
struct Number {
value: i32,
}
impl Number {
fn new(value: i32) -> Number {
Number { value }
}
fn add(&self, other: &Number) -> Number {
Number::new(self.value + other.value)
}
fn subtract(&self, other: &Number) -> Number {
Number::new(self.value - other.value)
... | magicoder | rust |
You are tasked with implementing a live search feature for a forum website. The provided code snippet contains a form input element and a container for displaying search results. The live search functionality is triggered by the `oninput` event of the input element, which calls the `liveSearch` function with the parame... | ```javascript
function liveSearch(url, userId, resultContainer, key) {
// Create a new XMLHttpRequest object
var xhr = new XMLHttpRequest();
// Set up the request
xhr.open('GET', url + '?userId=' + userId + '&key=' + key, true);
// Define the callback function
xhr.onload = function () {
... | magicoder | javascript |
You are tasked with creating a Python function that processes a given sentence to extract and count the occurrences of words matching a specific pattern. The pattern is defined as a sequence of one or more word characters (alphanumeric or underscore) possibly followed by hyphens or apostrophes, and enclosed in triple q... | ```python
import re
def count_matched_words(sentence: str, pattern: str) -> dict:
# Compile the provided pattern into a regular expression
compiled_pattern = re.compile(pattern)
# Find all matches of the pattern in the given sentence
matched_words = compiled_pattern.findall(sentence)
# Create a d... | magicoder | python |
You are given a binary tree represented as a list of lists, where each inner list contains the value of a node and the indices of its left and right children. The tree is constructed such that the root is at index 0, and for any node at index i, its left child is at index 2*i+1 and its right child is at index 2*i+2. Th... | ```python
class TreeNode:
def __init__(self, value=0, left=None, right=None):
self.value = value
self.left = left
self.right = right
def zigzagLevelOrder(root):
if not root:
return []
result = []
queue = [root]
level = 0
while queue:
level_nodes = []
... | magicoder | python |
You are given a Python code snippet that processes a matrix `cmat` and performs some operations on it. Your task is to understand the code and implement a function that achieves the same result using NumPy and Pandas.
Write a Python function `process_matrix(cmat)` that takes a 2D NumPy array `cmat` as input and perfor... | ```python
import numpy as np
import pandas as pd
import seaborn as sns
def process_matrix(cmat):
ymax = cmat.max(axis=0) # Find the maximum value along each column
res = list(zip(range(cmat.shape[0]), np.argmax(cmat, axis=1), ymax)) # Create a list of tuples
if len(res) == 2: # If the shape of the res... | magicoder | python |
You are tasked with implementing a Python function that processes a list of integers and returns the sum of all the even numbers in the list. However, there is a catch - you are not allowed to use any conditional statements (if, else) or loops (for, while) in your solution. You must achieve this using only Python's bui... | ```python
def sum_even_numbers(numbers: list) -> int:
# Filter out the odd numbers from the list using the filter function
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
# Use the reduce function from the functools module to sum the even numbers
from functools import reduce
return r... | magicoder | python |
You are tasked with creating a program that processes an image to identify and count the number of distinct colors present in the image. You will need to implement a function that takes the file path of an image as input and returns the count of unique colors present in the image.
Your task is to implement the functio... | ```python
from PIL import Image
import numpy as np
def count_unique_colors(image_path):
# Open the image using PIL
img = Image.open(image_path)
# Convert the image to a NumPy array
img_array = np.array(img)
# Reshape the array to a 2D array of pixels
reshaped_array = img_array.reshape(-1, img... | magicoder | python |
You are tasked with creating a Java class that utilizes annotations and imports from external libraries. Your class should implement a caching strategy using Hibernate annotations and Google Guava library. Additionally, the class should include a method that compares two objects using the `Objects` class from Google Gu... | ```java
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import com.google.common.base.Objects;
import com.jeefw.model.sys.param.TzzShizhanDetailsParameter;
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class CacheManager {
public boolean compareObjec... | magicoder | java |
You are tasked with implementing a function to generate a statistics report for a memcached server cluster. The function should take a cluster specification and server statistics as input and produce a formatted report as output.
You are given the following code snippet as a reference for the desired output format:
``... | ```cpp
#include <string>
#include <sstream>
struct ClusterSpec {
std::vector<std::string> servers;
// Other cluster information
};
struct ServerStats {
std::string version;
int pid;
int uptime;
int64_t bytes;
int64_t bytes_read;
int64_t bytes_written;
// Other server statistics
};
... | magicoder | cpp |
You are tasked with implementing a custom table view component in Swift, called `GLBaseTableView`, that supports both horizontal and vertical scrolling. The table view should display a grid of cells, and each cell should be able to contain any type of content, such as text, images, or custom views. Your task is to impl... | ```swift
import UIKit
protocol GLBaseTableViewDelegate: AnyObject {
func didSelectCell(at indexPath: IndexPath)
// Add any other required delegate methods here
}
class GLBaseTableView: UIScrollView {
weak var glDelegate: GLBaseTableViewDelegate?
var numberOfRows: Int = 0
var numberOfColumns: ... | magicoder | swift |
You are tasked with creating a program that analyzes a given CSS file and identifies the properties and values associated with each CSS class. Your program should be able to extract and display this information in a structured format.
Write a function `extractCSSInfo(css)` that takes a string `css` representing the co... | ```python
import re
def extractCSSInfo(css):
css_info = {}
class_pattern = r'\.(\w+)\s*{([^}]*)}'
property_pattern = r'(\w+)\s*:\s*([^;]+);'
class_matches = re.finditer(class_pattern, css)
for match in class_matches:
class_name = match.group(1)
properties = match.group(2)
p... | magicoder | python |
You are tasked with implementing a program that merges two sorted arrays into a single sorted array. The input arrays are already sorted in non-decreasing order. Your task is to write a function that takes in two arrays and returns a new array containing all the elements from the input arrays in non-decreasing order.
... | ```java
public static int[] mergeSortedArrays(int[] arr1, int[] arr2) {
int[] mergedArray = new int[arr1.length + arr2.length];
int i = 0, j = 0, k = 0;
while (i < arr1.length && j < arr2.length) {
if (arr1[i] < arr2[j]) {
mergedArray[k++] = arr1[i++];
} else {
merge... | magicoder | java |
You are given a DataFrame `df` with 6 rows and 4 columns, filled with the value 1 in each cell. Your task is to write a function that takes this DataFrame as input and returns a new DataFrame where each value is replaced by the cumulative sum of the values in the same column up to that row.
For example, if the origina... | ```python
import pandas as pd
def cumulative_sum(df):
cumulative_df = df.cumsum()
return cumulative_df
``` | magicoder | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.