query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with implementing a custom integer type `MyInt` in Rust. The `MyInt` type should support the following operations: addition, subtraction, multiplication, division, equality comparison, and inequality comparison.
You need to implement the `MyInt` type and its associated methods to support the specified o... | ```rust
struct MyInt {
val: i32,
}
impl MyInt {
fn new(val: i32) -> MyInt {
MyInt { val }
}
fn add(&self, other: &MyInt) -> MyInt {
MyInt { val: self.val + other.val }
}
fn sub(&self, other: &MyInt) -> MyInt {
MyInt { val: self.val - other.val }
}
fn mul(&self... | magicoder | rust |
You are tasked with implementing a custom logging system in Python. The system should include a custom filter and a handler to manage the log messages.
Your task is to create a Python class that represents a custom filter called `KmIOFilter`. This filter should be designed to filter log records based on specific crite... | ```python
import logging
class KmIOFilter(logging.Filter):
def filter(self, record):
# Implement the filtering logic based on specific criteria
# For example, filter log records based on log level or message content
if record.levelno >= logging.WARNING:
return True
retur... | magicoder | python |
You are tasked with implementing a function to calculate the Elliott Wave Oscillator (EWO) for a given financial time series dataset. The EWO is a technical analysis tool used by traders to identify potential market cycles and turning points. The EWO is calculated using two exponential moving averages (EMAs) of the pri... | ```python
import numpy as np
from typing import Union
def ewo(candles: np.ndarray, short_period: int = 5, long_period: int = 35, source_type="close", sequential=False) -> \
Union[float, np.ndarray]:
"""
Elliott Wave Oscillator
:param candles: np.ndarray
:param short_period: int - the period for the sho... | magicoder | python |
You are tasked with implementing a custom email transport class in PHP. Your task is to create a class that extends the `Swift_Transport_EsmtpTransport` class from the Swift Mailer library. The custom class, named `DummyTransport`, should include a property to store an array of `Swift_Events_EventListener` objects.
Yo... | ```php
namespace Yiisoft\Mailer\SwiftMailer\Tests\TestAsset;
use Swift_Events_EventListener;
use Swift_RfcComplianceException;
use Swift_Transport_EsmtpTransport;
final class DummyTransport extends Swift_Transport_EsmtpTransport
{
/**
* @var Swift_Events_EventListener[]
*/
private $eventListeners;
... | magicoder | php |
You are tasked with implementing a user authentication system using Swift. The `User` struct represents a user in the system and has a static property `current` to store the currently logged-in user. The `login` function is used to authenticate a user with a given username and password. Upon successful authentication, ... | ```swift
struct User {
static var current: User?
static func login(username: String, password: String, completion: (Result<User, Error>) -> Void) {
// Simulating authentication process
if username == "hello" && password == "world" {
let authenticatedUser = User(username: username) /... | magicoder | swift |
You are tasked with implementing a snapshot update function for a graph data structure. The function should take a graph scope and a callback object as input and update the callback's snapshot with any modifications made to the graph since the last snapshot.
The provided code snippet is a template function for the sna... | ```cpp
template <typename Graph, typename CallbackType>
void snapshot_update(iscope<Graph>& scope,
icallback<Graph>& _callback) {
CallbackType& callback = *dynamic_cast<CallbackType*>(&_callback);
if (callback.get_snapshot_token(scope.vertex())) return;
if (callback.vertex_modified_sin... | magicoder | cpp |
You are tasked with creating a program that simulates a simple inventory management system for a warehouse. The program should allow users to add, remove, and display items in the inventory. Additionally, it should provide the functionality to export the inventory to a CSV file.
Your task is to implement the `Inventor... | ```python
import csv
class Inventory:
def __init__(self):
self.inventory = {}
def add_item(self, item_name, quantity):
if item_name in self.inventory:
self.inventory[item_name] += quantity
else:
self.inventory[item_name] = quantity
def remove_item(self, ite... | magicoder | python |
You are tasked with implementing a TypeScript function that validates a given abstract syntax tree (AST) for a specific syntax pattern. The AST represents a SQL query, and the function should check if the query contains a `WHERE` clause with a specific expression.
You are provided with the following TypeScript interfa... | ```typescript
function hasSpecificWhereExpression(ast: Node, specificExpression: Expression): boolean {
if (ast.syntaxKind === SyntaxKind.WhereClause) {
const whereClause = ast as WhereClause;
return areExpressionsEqual(whereClause.expr, specificExpression);
} else {
for (const key in as... | magicoder | typescript |
You are tasked with implementing a function to compute the radiation pressure acceleration on a cannonball due to the Poynting-Robertson drag effect in a given orbital scenario. The function takes in various parameters related to the cannonball and the radiation source and returns the computed radiation pressure accele... | ```cpp
#include <cmath>
template< typename Real, typename Vector3 >
Vector3 computeCannonballPoyntingRobertsonDragAcceleration(
const Real radiationPressureCoefficient,
const Vector3& unitVectorToSource,
const Real radius,
const Real bulkDensity,
const Real velocity
) {
const Re... | magicoder | cpp |
You are tasked with implementing a class to manage a product inventory system. The class should support adding products, removing products, and updating product quantities. Additionally, it should provide a method to retrieve the total number of products in the inventory.
You are given a partially completed Python cla... | ```python
class ProductInventory:
def __init__(self):
self.products = {}
self.PRODUCT_NUMBER = 1000
def add_product(self, name, quantity):
if name in self.products:
if self.total_products() + quantity - self.products[name] > self.PRODUCT_NUMBER:
print("Cannot... | magicoder | python |
You are tasked with implementing a Python class that simulates a space generator. The space generator is responsible for producing unique space objects, and the test cases provided ensure that the generator functions correctly. Your task is to complete the implementation of the `SpaceGenerator` class by adding the nece... | ```python
class Space:
pass # Placeholder for the Space class definition
class SpaceGenerator:
def __init__(self):
self.generated_spaces = set()
def next(self) -> Space:
new_space = Space()
while new_space in self.generated_spaces:
new_space = Space()
self.gen... | magicoder | python |
You are tasked with creating a script to automate the setup of a new user and install necessary packages on a Raspberry Pi system. The script should perform the following tasks:
1. Check if the script is being executed from the home directory of the 'pi' user. If not, it should display an error message and exit.
2. Gr... | ```bash
#!/bin/bash
# Check if the script is being executed from the home directory of the 'pi' user
if [ ! `pwd` = "/home/pi" ]; then
echo "This script should be called from the home directory of the 'pi' user"
exit 1
fi
# Grant sudo privileges to the 'pi' user without password prompt
echo "pi ALL=(ALL) NOPA... | magicoder | shell |
You are working on a Python library that provides a decorator-based approach for binding SQL queries and commands to Python functions. The library uses decorators to associate SQL statements with Python functions, allowing for easy execution and querying of a database. However, there seems to be an issue with the bindi... | ```python
import re
class FunctionAlreadyBoundError(Exception):
pass
class MalformedQueryError(Exception):
pass
def validate_binding(decorators):
bound_functions = {}
sql_pattern = r'^\s*(SELECT|UPDATE|INSERT|DELETE)\s+.+'
for decorator, sql_statement in decorators:
if decorator in bound... | magicoder | python |
You are tasked with implementing a sorting algorithm for a list of objects based on specific fields within each object. Each object represents a vulnerability in a software system and contains various fields such as "identifierField", "displayText", "sortable", "fieldOrder", "selected", "sortOrder", and "sortType". The... | ```python
def sort_vulnerabilities(vulnerabilities, sort_field, sort_order):
sorted_vulnerabilities = sorted(vulnerabilities, key=lambda x: x[sort_field], reverse=(sort_order == "DESC"))
return sorted_vulnerabilities
```
The `sort_vulnerabilities` function takes in the list of vulnerabilities, a `sort_field`, ... | magicoder | python |
You are tasked with creating a version control system for a software project. The version control system should automatically generate a short unique identifier for each commit made to the project. The identifier should be stored in a file named "version". The identifier should be a short hash of the commit, generated ... | ```python
import subprocess
def generate_commit_identifier():
try:
# Execute the git command to obtain the short commit identifier
commit_hash = subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD']).decode('utf-8').strip()
# Write the commit identifier to the version fil... | magicoder | python |
You are tasked with implementing a function that generates a NetCDF source layer for a Geographic Data Abstraction Library (GDAL) in a TypeScript environment. The function should take into account the dataset path, NetCDF subdataset, and time points to create the layer with mapping raster symbology.
You are provided w... | ```typescript
private generateGdalSourceNetCdfLayer(): Layer<MappingRasterSymbology> {
const path = this.ebvDataset.dataset_path;
const netCdfSubdataset = '/' + this.ebvSubgroupValues.map(value => value.name).join('/');
const timePoints = this.ebvDataLoadingInfo.time_points;
// Assuming the existence o... | magicoder | typescript |
You are tasked with creating a simple game using Python's Pygame library. The game involves drawing a grassy background and placing two cow objects on the screen. The provided code snippet is a part of the game's rendering logic. Your task is to complete the game by implementing the missing parts.
You are given the fo... | ```python
# 1 - clear the screen before drawing it again
screen.fill((0, 0, 0)) # Fills the screen with black color
# 2 - draw the grassy background on the screen
for x in range(int(width / grass.get_width()) + 1):
for y in range(int(height / grass.get_height()) + 1):
screen.blit(grass, (x * grass.get_wid... | magicoder | python |
You are tasked with creating a custom Android view that displays a colored circle with a number in the center. The view should be able to dynamically change the color and number displayed. You are provided with a starter code snippet that includes the necessary Android classes and imports.
Your task is to implement a ... | ```java
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class NumberCircleView extends RelativeLayout {
priva... | magicoder | java |
You are working on a project that involves setting up symbolic links to various files and directories. Your task is to write a program that simulates the creation of symbolic links based on a given set of input instructions.
You are given a list of symbolic link creation commands in the following format:
```
ln -s <so... | ```python
def create_symbolic_links(commands):
symbolic_links = {}
current_directory = "./"
for command in commands:
if command.startswith("ln -s"):
_, source, destination = command.split()
symbolic_links[destination] = source
elif command.startswith("cd"):
... | magicoder | python |
You are tasked with implementing a Python class that represents a file system namespace. The namespace consists of directories and files, and you need to create methods to traverse the namespace in both breadth-first and depth-first orders.
Your task is to implement the `Namespace` class with the following methods:
1.... | ```python
class Namespace:
def __init__(self, name):
self.name = name
self.children = []
def ls(self):
return self.children
def iterBreadthFirst(self):
queue = [self]
while queue:
node = queue.pop(0)
yield node
queue.extend(node.c... | magicoder | python |
You are tasked with implementing a custom service provider framework in Java. The code snippet provided includes an abstract `Service` class and a concrete `ServiceImpl` class, along with annotations and static initializers. Your goal is to create a custom service provider framework that allows registering and invoking... | ```java
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface ProjectServiceProvider {
Class<?> service();
String projectType();
}
public abstract static class Service {
static {
System.err.println("===> loading Service");
}
public abstract... | magicoder | java |
You are tasked with simulating the behavior of a robot in a game environment. The robot has the ability to shake trees to collect resources. The robot can sense the nearest neutral tree and attempt to shake it to collect resources. However, the shaking action may fail due to various reasons. Your task is to implement a... | ```java
boolean shakeTree() {
TreeInfo nearestTree = sensor.findNearestTree(Team.NEUTRAL);
if(nearestTree == null){
return false; // No neutral tree found
}
if(rc.canShake(nearestTree.ID)) {
try{
rc.shake(nearestTree.ID); // Attempt to shake the tree
return t... | magicoder | java |
You are tasked with implementing a dynamic counter provider in C#. The dynamic counter provider should allow for the creation and management of dynamic counters, which can be incremented, decremented, and accessed by name. The dynamic counter provider should be implemented as a class with the following specifications:
... | ```csharp
using System;
using System.Collections.Generic;
using System.Dynamic;
public class DynamicCounterProvider : DynamicObject
{
private Dictionary<string, int> counters = new Dictionary<string, int>();
public void CreateCounter(string name, int initialValue)
{
if (!counters.ContainsKey(name)... | magicoder | csharp |
You are tasked with creating a Python function that processes a video file and returns the average frame rate of the video. You are given a code snippet that retrieves the total number of frames in the video using the OpenCV library. Your task is to utilize this information to calculate the average frame rate of the vi... | ```python
import cv2
def calculate_average_frame_rate(video_capture, video_length):
total_frames = int(video_capture.get(cv2.CAP_PROP_FRAME_COUNT))
total_time_ms = video_length * 1000 # Convert video length to milliseconds
average_frame_rate = total_frames / (total_time_ms / 1000) # Calculate average fra... | magicoder | python |
You are tasked with implementing a Python class that represents a geometric concept. The class should handle operations related to lines in a 2D plane. The class should be able to calculate the distance between a point and the line, as well as determine whether a given point lies to the left or right of the line.
You... | ```python
import math
class Line:
def __init__(self, a, b, c, k):
self.a = a
self.b = b
self.c = c
self.k = k
def distance_from_point(self, x, y):
numerator = abs(self.a * x + self.b * y + self.c)
denominator = math.sqrt(self.a ** 2 + self.b ** 2)
return... | magicoder | python |
You are tasked with creating a program that analyzes the license information of a given source code file. The license information is typically found at the beginning of the file as a comment block, similar to the provided code snippet. Your program should extract and parse the license details to determine the license t... | ```python
import re
def extractLicenseInfo(source_code):
license_info = {}
match = re.search(r'Licensed under the (.+?) License', source_code)
if match:
license_info["license_type"] = match.group(1)
url_match = re.search(r'You may obtain a copy of the License at\n\n\s+(http://\S+)', source_code... | magicoder | python |
You are tasked with implementing a neural network architecture using PyTorch for image classification. The given code snippet is a part of the neural network definition and shows the initialization of some layers. Your task is to complete the neural network definition by implementing the forward pass function and ensur... | ```python
import torch
import torch.nn as nn
class ConvTriple(nn.Module):
def __init__(self, in_channels, out_channels):
super(ConvTriple, self).__init__()
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1)
self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_s... | magicoder | python |
You are tasked with creating a script to automate the validation of npm scripts in a given project. The script should check if all npm scripts are in a working state. An npm script is considered to be in a working state if it can be executed without errors.
You are provided with a sample project structure and a list o... | ```javascript
const { execSync } = require('child_process');
const path = require('path');
const fs = require('fs');
// Define the paths for the temporary app and test module
const tempAppPath = '/path/to/temp_app';
const tempModulePath = '/path/to/temp_module';
// Read the package.json file of the temporary app
cons... | magicoder | javascript |
You are given a code snippet that defines a data structure for representing triangles and a function for calculating the projected area of a set of triangles onto a plane. Your task is to implement the `projected_area` function to calculate the total projected area of the triangles onto the specified plane.
The `Trian... | ```cpp
#include <cmath>
// Function to calculate the area of a triangle given its vertices
double triangle_area(const Vector3d &p1, const Vector3d &p2, const Vector3d &p3) {
double a = sqrt(pow(p2.x - p1.x, 2) + pow(p2.y - p1.y, 2) + pow(p2.z - p1.z, 2));
double b = sqrt(pow(p3.x - p2.x, 2) + pow(p3.y - p2.y, ... | magicoder | cpp |
You are given a snippet of Java code that is part of a breadth-first search algorithm. The code snippet is responsible for generating the next set of nodes to be explored in the search. The `next` queue contains the nodes to be explored, and the snippet processes the current node `b` to determine the next nodes to be a... | ```java
import java.util.*;
public class Solution {
public int[][] generateNextNodes(int[] b) {
Queue<int[]> next = new LinkedList<>();
int[][] result;
if (b[0] > 0) {
next.offer(new int[]{b[0]-1, b[1]});
}
if (b[1] > 0) {
if (b[0] == 0) {
... | magicoder | java |
You are tasked with implementing a local ID generator function in Python. The local ID generator should produce unique IDs within a specified range. To ensure the correctness of the generator, you need to write a test case using the `unittest` framework to verify that the generated IDs are unique and of the correct typ... | ```python
import unittest
import random
def local_id_generator(start, end):
used_ids = set()
while True:
new_id = random.randint(start, end)
if new_id not in used_ids:
used_ids.add(new_id)
yield new_id
class IdGeneratorTest(unittest.TestCase):
def testuuid_generato... | magicoder | python |
You are tasked with implementing a function to standardize a given vector by centering and scaling it. The function should allow the user to choose between centering the vector using the mean or median, and scaling it using the standard deviation or interquartile range. Additionally, the function should handle cases wh... | ```python
import numpy as np
def standardize_vec(v, center='mean', scale='std'):
""""
Standardizes a vector by centering and scaling it
This function will ignore scaling if the scale value is zero and will
instead set the scale value to 1
"""
# choose the center value
if center == 'mean':
... | magicoder | python |
You are tasked with analyzing a dataset containing information about students' grades in various subjects. The dataset is represented as a pandas DataFrame and contains the following columns:
- 'Name': The name of the student (string)
- 'Age': The age of the student (integer)
- 'Grade': The grade obtained by the stude... | ```python
import pandas as pd
from typing import Dict
def average_grades(data: pd.DataFrame) -> Dict[str, float]:
# Group the data by 'Subject' and find the maximum grade for each subject
max_grades = data.groupby('Subject')['Grade'].max()
# Convert the grouped data to a dictionary
average_grades_... | magicoder | python |
You are tasked with creating a Swift function that processes an array of integers and returns the sum of all the even numbers in the array. Additionally, you need to handle the possibility of an empty array and ensure that the function can be easily integrated into existing code.
Write a Swift function `sumOfEvenNumbe... | ```swift
func sumOfEvenNumbers(_ numbers: [Int]) -> Int {
return numbers.filter { $0 % 2 == 0 }.reduce(0, +)
}
```
The `sumOfEvenNumbers` function filters the input array to keep only the even numbers using the `filter` method. Then, it uses the `reduce` method to sum up all the filtered even numbers. If the input... | magicoder | swift |
You are tasked with implementing a simple text editor class in Python. The class should support the following operations: clearing the text, moving the cursor position, appending a message, writing to a file, and disabling further edits.
You are given a code snippet that partially implements the text editor class. You... | ```python
import threading
class TextEditor:
def __init__(self):
self.text = ""
self.cursor_pos = 0
self._lock = threading.Lock()
self.fp = None
self.disable = False
def clear(self):
with self._lock:
self.text = ""
def moveto(self, pos):
... | magicoder | python |
You are tasked with implementing a Python class to convert dates from the Gregorian calendar to the French Republican calendar. The French Republican calendar was used in France from 1793 to 1805 and had 12 months, each consisting of 30 days, with 5 or 6 additional days at the end of the year. The Republican calendar a... | ```python
import math
class RepublicanDate:
months = [
"Vendémiaire", "Brumaire", "Frimaire", "Nivôse", "Pluviôse", "Ventôse",
"Germinal", "Floréal", "Prairial", "Messidor", "Thermidor", "Fructidor"
]
days = [
"Primidi", "Duodi", "Tridi", "Quartidi", "Quintidi", "Sextidi",
"... | magicoder | python |
You are tasked with implementing a method to locate a specific element within a given type. You are provided with the following method signature:
```csharp
MethodInfo Locate(TypeInfo type, TypeInfo elementType);
```
Your task is to implement the `Locate` method, which takes two parameters:
1. `type`: A `TypeInfo` obj... | ```csharp
public class Solution
{
public MethodInfo Locate(TypeInfo type, TypeInfo elementType)
{
// Get all methods of the type
MethodInfo[] methods = type.GetMethods();
// Iterate through the methods to find the one that can locate the elementType
foreach (MethodInfo method in... | magicoder | csharp |
You are tasked with creating a C# program that reads data from a SQL Server database using the System.Data namespace. Your program should connect to the database, retrieve specific information, and display it to the user.
Your program should perform the following steps:
1. Connect to a SQL Server database using the S... | ```csharp
using System;
using System.Data;
using System.Data.SqlClient;
namespace DatabaseReader
{
class Program
{
static void Main(string[] args)
{
string connectionString = "Data Source=YourServer;Initial Catalog=YourDatabase;Integrated Security=True";
string query = "... | magicoder | csharp |
You are working on a software library that provides a fluent interface for configuring custom resource definitions in a Kubernetes environment. The code snippet provided is a part of the fluent API for configuring custom resource conversions. The `V1CustomResourceDefinitionSpecFluent` class provides methods for configu... | ```java
public io.kubernetes.client.openapi.models.V1CustomResourceDefinitionSpecFluent.ConversionNested<A> withNewConversionLike(io.kubernetes.client.openapi.models.V1CustomResourceConversion item) {
// Implement the method to configure a new conversion and return a ConversionNested interface
// Example implem... | magicoder | java |
You are given a 2D grid representing a game board with cells labeled with either "W" or "B". The grid is of size N x N, where N is a positive integer. Each cell is associated with a pair of coordinates (i, j), where 1 ≤ i, j ≤ N. The goal is to count the number of "good" rectangles in the grid. A "good" rectangle is de... | ```python
from typing import List
def count_good_rectangles(grid: List[List[str]]) -> int:
n = len(grid)
prefix_sums = [[0] * (n + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
for j in range(1, n + 1):
prefix_sums[i][j] = prefix_sums[i-1][j] + prefix_sums[i][j-1] - prefix_sums[i... | magicoder | python |
You are tasked with implementing a radio button group manager in a GUI framework. The radio button group manager should allow for the creation and management of radio button groups. Each radio button group should consist of a list of radio buttons, and each radio button should be associated with a handler that manages ... | ```csharp
public class RadioButtonHandler
{
public List<RadioButtonHandler> group;
}
public class RadioButton
{
public object Handler { get; set; }
}
public class RadioButtonGroupManager
{
public void Create(RadioButton controller)
{
var controllerHandler = controller?.Handler as RadioButtonHa... | magicoder | csharp |
You are tasked with creating a Python program that can download images from a given Instagram profile. Your program should utilize the `requests` library to fetch the HTML content of the profile page and the `selenium` library to interact with the dynamic elements of the page. Additionally, you need to use PyQt5 to cre... | ```python
import os
import requests
from bs4 import BeautifulSoup
from selenium import webdriver
from PyQt5.QtWidgets import QApplication, QDialog
from PyQt5.uic import loadUi
import urllib.request
import time
class INSTADOWNLOAD(QDialog):
def __init__(self):
super(INSTADOWNLOAD, self).__init__()
l... | magicoder | python |
You are given a function `chainResult(num)` that takes a positive integer `num` as input and returns another positive integer. The goal is to find the count of numbers from 1 to 10,000,000 (inclusive) for which the result of `chainResult(num)` is 89.
The `chainResult(num)` function follows the following rules:
- Start... | ```python
def chainResult(num):
while num != 1 and num != 89:
num = sum(int(digit)**2 for digit in str(num))
return num
count = 0
for num in range(1, 10000001):
if chainResult(num) == 89:
count += 1
print(count)
```
The solution defines the `chainResult` function to calculate the result of ... | magicoder | python |
You are tasked with creating a Python function that takes a list of NumPy arrays as input and returns the maximum shape across all arrays in each dimension. The function should handle arrays of different dimensions and shapes and return a list representing the maximum shape in each dimension.
The function signature sh... | ```python
import numpy as np
from typing import List
def max_array_shape(arrays: List[np.ndarray]) -> List[int]:
shapes = list(map(lambda x: list(x.shape), arrays)) # Get the shapes of all arrays
ndim = len(arrays[0].shape) # Get the number of dimensions of the first array
max_shape = []
for dim in ... | magicoder | python |
You are tasked with creating a script to automate the management of Docker containers and instances of Elasticsearch. Your script should perform the following tasks in sequence:
1. Stop all running instances of Elasticsearch using the script `stop_all.sc`.
2. Remove all existing instances of Elasticsearch using the sc... | ```bash
#!/bin/bash
# Step 1: Stop all running instances of Elasticsearch
if ./stop_all.sc; then
echo "All instances of Elasticsearch stopped successfully"
else
echo "Failed to stop instances of Elasticsearch"
exit 1
fi
# Step 2: Remove all existing instances of Elasticsearch
if ./remove_all_instances.sc; then
... | magicoder | shell |
You are tasked with implementing a function that calculates the distance of a specified character from the start of a run within a given source string. The function takes an index representing the UTF-16 code unit in the source string and returns the distance of the specified character from the assumed start of the run... | ```swift
public func distance(forCodeUnitAt index: Int) -> CGFloat {
// Check if the index is within the valid range
guard index >= codeUnitRange.lowerBound && index <= codeUnitRange.upperBound else {
fatalError(String.indexOutOfRange)
}
// Call the helper function to calculate the distance
... | magicoder | swift |
You are tasked with implementing a class hierarchy for a simple game involving monsters. The base class `ObjMonster` is provided, and you need to create two derived classes: `ObjGoblin` and `ObjDragon`. Each derived class should have specific behavior and attributes, while also inheriting from the base class.
The `Obj... | ```cpp
#include <iostream>
class ObjMonster {
public:
virtual void attack() = 0;
virtual void defend() = 0;
virtual void displayType() const = 0;
};
class ObjGoblin : public ObjMonster {
public:
void attack() override {
std::cout << "Goblin attacks!" << std::endl;
}
void defend() over... | magicoder | cpp |
You are tasked with designing a data structure for a robotic hand system. The system consists of a palm, fingers, and various parameters to control the movement and gestures of the hand. Your task is to create a Python class that represents the data structure for this robotic hand system.
The class should be named `Ro... | ```python
import math
class RoboticHandSystem:
def __init__(self):
self.homing_offset = 0
self.travel = math.pi/2
self.home = 0
self.initialized = False
self.gesture = None
self.angle = 0
self.sensors = []
class RobotDataStructure:
def __init__(self, nam... | magicoder | python |
You are tasked with creating a Python function that processes a list of image paths and returns the average brightness of the images. The brightness of an image is determined by the numerical value found in the file name. The file names follow a specific format: "image_xxx.jpg", where "xxx" represents a three-digit num... | ```python
def average_brightness(image_paths):
total_brightness = 0
for path in image_paths:
brightness = float(path[-7:-4]) # Extract the brightness level from the file name
total_brightness += brightness
return total_brightness / len(image_paths) # Calculate the average brightness
``` | magicoder | python |
You are working as a system administrator for a web hosting company. Your task is to automate the process of adding and managing user accounts for different websites on the server. You need to create a script that adds a new user to the crontab and enables the user for monitoring using the Open Monitoring Distribution ... | ```bash
# Add the new user to crontab, to avoid error merging crontabs
adduser "${SITE}" crontab || true
adduser "${SITE}" omd || true
omd enable "${SITE}"
if [ "${SITE}" != "sp" ]
then
omd disable "sp"
fi
```
The solution completes the script by adding the necessary commands to achieve the specified functionality... | magicoder | shell |
You are tasked with creating a Python function that retrieves a file from a remote server and saves it to a specified local directory. The function should handle HTTP basic authentication and proxy settings. You are provided with a code snippet that partially accomplishes this task, and your goal is to complete the fun... | ```python
import os
import urllib.request
def retrieve_file(remote_url, local_dir, proxy_settings, username, password):
proxy_handler = urllib.request.ProxyHandler(proxy_settings)
auth_handler = urllib.request.HTTPBasicAuthHandler()
auth_handler.add_password(realm=None, uri=remote_url, user=username, passw... | magicoder | python |
You are tasked with creating a program that processes a given software license text to extract specific permissions granted within the license. The license text is provided as a string, and the permissions are defined by the lines starting with "///" followed by the permission description. Each permission is separated ... | ```python
from typing import List
def extractPermissions(license_text: str) -> List[str]:
permissions = []
lines = license_text.split("\n")
for line in lines:
if line.startswith("///"):
permission = line[3:].strip()
permissions.append(permission)
return permissions
```
... | magicoder | python |
You are tasked with creating a Python class for managing projects in a business intelligence application. The class should include methods for listing cubes, listing models, creating a project, and deleting a project. Your task is to implement the `delete_project` method, which should delete a project after ensuring th... | ```python
import logging
class ProjectManager:
def __init__(self):
# Initialize project manager with necessary configurations
pass
def list_cubes(self, project_name):
# Implementation for listing cubes in the specified project
pass
def list_models(self, project_name):
... | magicoder | python |
You are tasked with creating a Python program to process and analyze incoming serial data from an Arduino. The Arduino is continuously sending sensor data over the serial port, and your program needs to read this data and perform specific operations based on the received information.
Your program should read the incom... | ```python
from collections import defaultdict
def process_serial_data(serial_data):
sensor_readings = defaultdict(list)
for line in serial_data.split('\n'):
if line:
sensor, value = line.split(':')
sensor_readings[sensor].append(int(value))
if len(sensor_reading... | magicoder | python |
You are tasked with implementing a function to clean a search term by removing stop words from it. Stop words are common words (e.g., "the", "is", "in") that are often filtered out from search queries because they do not significantly contribute to the meaning of the query. The function should take a search term and a ... | ```python
from typing import List
import re
def clean_search_term(search_term: str, stop_words: List[str]) -> str:
stop_word_list = re.compile(r'\b(?:' + '|'.join(stop_words) + r')\b', re.IGNORECASE)
cleaned_search_term = stop_word_list.sub('', search_term)
return cleaned_search_term
``` | magicoder | python |
You are tasked with creating a C++ class that utilizes gRPC to implement a simple client-server communication system. The class should be able to send a request to the server and receive a response using synchronous streaming.
Your task is to complete the implementation of the `GrpcClient` class, which includes the fo... | ```cpp
#include <grpcpp/impl/codegen/service_type.h>
#include <grpcpp/impl/codegen/sync_stream.h>
#include <grpcpp/channel.h>
#include <grpcpp/client_context.h>
#include <grpcpp/create_channel.h>
#include <grpcpp/generic/generic_stub.h>
#include <grpcpp/support/status.h>
#include <grpcpp/support/status_code_enum.h>
#in... | magicoder | cpp |
You are given a code snippet that involves a geometric computation. The snippet appears to be testing a function that calculates the intersection point between a plane and a line in 3D space. The variables `p`, `s`, `v`, `result`, `t`, and `exp` are used in this context. The function `Geometry.planeIntersection` seems ... | ```java
public class Geometry {
public static final double PRECISION = 1e-6;
// Function to calculate the intersection point between a plane and a line
public static double planeIntersection(double[] p, double[] s, double[] v, double[] result) {
double d = -(p[0] * s[0] + p[1] * s[1] + p[2] * s[2] ... | magicoder | java |
You are tasked with creating a skill system for a video game using C#. The skill system should be able to handle various types of skills and their interactions. The system should allow for the creation of different types of skills, such as passive, active, and ultimate skills, and should support the execution and manag... | ```csharp
// Skill class representing an individual skill
public class Skill
{
public enum SkillType
{
Passive,
Active,
Ultimate
}
public string Name { get; set; }
public SkillType Type { get; set; }
public float Cooldown { get; set; }
public Skill(string name, Skil... | magicoder | csharp |
You are tasked with implementing a Python class that manages the creation and manipulation of database tables. The class should provide methods for adding and removing attributes, as well as for building the tables with various options. Your task is to complete the implementation of the `build_tables` method in the giv... | ```python
class TableManager:
def __init__(self):
self.tables = {}
def add_attribute(self, table_name, attribute):
if table_name in self.tables:
self.tables[table_name].append(attribute)
else:
self.tables[table_name] = [attribute]
def remove_attribute(self, ... | magicoder | python |
You are tasked with creating a Python program that simulates a simple asynchronous task management system using the `asyncio` library. The system will manage a set of tasks, each with its own priority level, and execute them in an asynchronous manner. The tasks will be represented as coroutines, and the system should b... | ```python
import asyncio
class TaskManager:
def __init__(self):
self.tasks = []
def add_task(self, coroutine, priority):
self.tasks.append((coroutine, priority))
async def execute_tasks(self):
self.tasks.sort(key=lambda x: x[1], reverse=True)
for task, _ in self.tasks:
... | magicoder | python |
You are given an array of integers `nums`. Write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
For example, given the input array `nums = [0,1,0,3,12]`, after calling your function, the `nums` array should be modified to `[1,3,12,0,0]`.
You must solve this ... | ```python
def moveZeroes(nums: List[int]) -> None:
"""
Moves all 0's to the end of the array while maintaining the relative order of non-zero elements.
:param nums: List[int] - Input array of integers
:return: None (modifies the input array in-place)
"""
# Initialize a pointer to keep track... | magicoder | python |
You are tasked with creating a Python function that simulates a simplified version of a token-based authentication system. The function should take a token as input and return an object of type `Manager`. Additionally, you need to write a unit test for this function using the `unittest.mock` library to ensure that the ... | ```python
from unittest.mock import patch
import unittest
class Manager:
pass
def get_token(token: str) -> str:
# Simulated function to retrieve token
return "actual-token"
def create_manager(token: str) -> Manager:
# Simulated function to create Manager object using token
if get_token(token) == ... | magicoder | python |
You are tasked with implementing a custom filtering functionality for a web application that displays information about diseases and their prevention measures. The provided code snippet is a part of the configuration for displaying and filtering data in a grid or table view. The 'attribute' key represents the attribute... | ```php
function applyFilters(array $data, array $config, array $filters): array {
$filteredData = $data;
foreach ($config as $entry) {
if (is_array($entry)) {
$attribute = $entry['attribute'];
$filterOptions = $entry['filter'];
if (isset($filters[$attribute]) && in_a... | magicoder | php |
You are tasked with creating a Python function that processes a given directory and calculates the total size of all files within it. Additionally, the function should exclude any files with a ".torrent" extension from the total size calculation. You are provided with a code snippet that demonstrates the use of the `os... | ```python
import os
def calculate_directory_size(directory_path):
total_size = 0
for dirpath, _, filenames in os.walk(directory_path):
for filename in filenames:
if not filename.endswith('.torrent'):
file_path = os.path.join(dirpath, filename)
total_size += o... | magicoder | python |
You are given a Python program that contains a function `main()` and an `if` statement checking if the number 777 is in a variable `gen`. Your task is to complete the program by defining the `gen` variable and implementing the `main()` function. The `main()` function should generate a list of random numbers and then ch... | ```python
import random
def main():
gen = [random.randint(1, 1000) for _ in range(100)] # Generate a list of 100 random numbers between 1 and 1000
if 777 in gen:
print("Yes!")
if __name__ == '__main__':
main()
``` | magicoder | python |
You are tasked with implementing a Python class that interacts with a key-value store using asynchronous methods. The provided code snippet includes a base class `BaseConnector` and a subclass `NetConnector`. The `BaseConnector` class contains two asynchronous methods: `dump_text` and `dump_prepro_text`. The `NetConnec... | ```python
import ujson
from typing import Any, Dict
class NetConnector(BaseConnector):
def __init__(self, *args: Any, **kwargs: Any):
super().__init__(*args, **kwargs)
async def fetch_text(self, title: str) -> str:
try:
return await self._master.get(title + self._SUF_TEXT)
... | magicoder | python |
You are tasked with implementing a Python class that processes a file and provides functionality to retrieve specific information from it. The class should be able to read the file, store its contents, and offer methods to manipulate and retrieve data from it.
You are provided with a partial code snippet for a Python ... | ```python
class FileProcessor(BaseObject):
def __init__(self, is_debug, file_path):
super().__init__(self, __name__)
self._is_debug = is_debug
self._file_path = file_path
self._file_contents = []
def read_file(self):
try:
with open(self._file_path, 'r') as fi... | magicoder | python |
You are tasked with creating a Rust library for handling date and time operations. The library should provide functionalities to format timestamps and handle module paths. Your task is to implement the `Naday` struct and its associated methods to achieve this functionality.
You need to implement the following:
1. Imp... | ```rust
use std::time::{SystemTime, UNIX_EPOCH};
struct Naday {
include_module_path: bool,
}
impl Naday {
fn format_timestamp(&self, timestamp: Option<SystemTime>) -> String {
match timestamp {
Some(ts) => {
let formatted_time = ts.duration_since(UNIX_EPOCH)
... | magicoder | rust |
You are tasked with implementing a simplified version of an Intcode machine, which is a computer program used in the Advent of Code programming competition. The Intcode machine operates on a list of integers and provides various operations to manipulate the data. In this problem, you will focus on implementing the inpu... | ```python
from collections import deque
class Intmachine:
def __init__(self, name, program, input_queue, output_queue):
self.name = name
self.program = program
self.input_queue = input_queue
self.output_queue = output_queue
self.pc = 0 # Program counter
def read_input(... | magicoder | python |
You are given a code snippet that reads in three integers `n`, `m`, and `k`, and then initializes a graph `g` with `n` vertices. The code snippet also contains a loop that iterates `m` times. Your task is to complete the implementation of the graph by adding edges to it based on the input provided. Each iteration of th... | ```cpp
#include <iostream>
#include <vector>
using namespace std;
class Graph {
int V;
vector<vector<int>> adj;
public:
Graph(int V) {
this->V = V;
adj.resize(V + 1);
}
void addEdge(int u, int v) {
adj[u].push_back(v);
adj[v].push_back(u); // Assuming undirected g... | magicoder | cpp |
You are tasked with creating a custom implementation for a data access object (DAO) in a Java Spring application. The application uses MyBatis as the persistence framework. Your goal is to extend the functionality of the existing RoleDAO interface to include a method for retrieving all roles associated with a specific ... | ```java
@Repository
public interface RoleDAO extends MyBatisBaseDao<Role, Integer> {
@Select("SELECT * FROM roles WHERE user_id = #{userId}")
List<Role> getRolesByUserId(@Param("userId") int userId);
}
```
In the solution, the RoleDAO interface is extended with a new method signature `getRolesByUserId` that ac... | magicoder | java |
You are tasked with implementing a video processing module that can handle both video files and image sequences. The provided code snippet is a part of the module's initialization process. The snippet shows a switch-case block where case 1 handles video files and case 2 handles image sequences. The code snippet also at... | ```cpp
void processFrames(VideoCapture vc, double rate, int delay) {
Mat frame;
while (true) {
if (vc.isOpened()) {
if (vc.get(CV_CAP_PROP_FRAME_COUNT) > 0) { // Video file
bool success = vc.read(frame);
if (!success) {
break; // End of v... | magicoder | cpp |
You are tasked with implementing a comment field component in a React application. The component should display a text area for users to input comments. The comment field should be pre-populated with a comment retrieved from a server, and the user should be able to edit and save their changes. Additionally, the user's ... | ```javascript
import React, { useState, useEffect } from 'react';
import { useKvalitetsvurdering, useUpdateKvalitetsvurderingMutation, useCanEdit } from './customHooks';
import { StyledCommentField } from './styled-components';
interface CommentFieldProps {
textareaId: string;
}
export const CommentField = ({ texta... | magicoder | javascript |
You are tasked with implementing a class that manages a set of unique binary hashes generated from descriptions and API calls. The class should have a method `add_hash(description: str, api_calls: List[str]) -> bool` that takes a description string and a list of API calls, generates a binary hash from the combination o... | ```python
from hashlib import sha256
from typing import List
class HashManager:
def __init__(self):
self.hashes = set()
def get_hash_binary(self, description: str, api_calls: List[str]) -> str:
combined_string = description + ''.join(api_calls)
return bin(int(sha256(combined_string.enc... | magicoder | python |
You are tasked with creating a custom Airflow operator that performs a specific data processing task. The operator needs to fetch data from an external API, process it, and then store the results in a specified location. Your task is to implement the custom operator and integrate it into an Airflow DAG.
You are provid... | ```python
import airflow
from airflow import DAG
from airflow.operators.python_operator import PythonOperator
import requests
from datetime import datetime
default_args = {
'owner': 'airflow',
'depends_on_past': False,
'start_date': datetime(2022, 1, 1),
'retries': 1,
}
def fetch_process_and_store_dat... | magicoder | python |
You are tasked with creating a Python program to control a Tello drone using the `djitellopy` module. The Tello drone is a lightweight, programmable drone that can be controlled via Python code. The `djitellopy` module provides a simple interface to interact with the Tello drone.
Your program should perform the follow... | ```python
# Import the necessary modules
from djitellopy import Tello
from time import sleep
def main():
# Create a Tello object
drone = Tello()
# Connect to the Tello drone
drone.connect()
# Take off and hover at a specified height for a given duration
drone.takeoff()
drone.send_rc_contr... | magicoder | python |
You are working on a database management system that uses a revision control system to manage schema and data upgrades and downgrades. Your task is to implement a function that handles the upgrade process by adding new roles for specific objects and propagating these roles to related objects. The upgrade function shoul... | ```python
def upgrade():
"""Upgrade database schema and/or data, creating a new revision."""
_add_roles_for_objects(SCOPING_OBJECTS, NEW_ROLES)
acr_propagation.propagate_roles(
acr_constants.GGRC_NEW_ROLES_PROPAGATION,
with_update=True
)
create_new_revision()
def downgrade():
"... | magicoder | python |
You are tasked with implementing a custom HTTP client configuration in a C# application. The application uses the `AddHttpClient` method to register an HTTP client for a specific interface and implementation. Additionally, a `senderPolicy` function is applied to the HTTP client configuration. Your task is to write a me... | ```csharp
using System;
using Microsoft.Extensions.DependencyInjection;
using System.Net.Http;
public class CustomHttpClientConfiguration
{
public static IServiceCollection ConfigureHttpClient(IServiceCollection services)
{
services.AddHttpClient<IQueuedProcessor<IWebHookWorkItem>, DefaultWebHookSender... | magicoder | csharp |
You are tasked with implementing a method to perform a specific operation on a list of integers. The method should take a list of integers as input and return a modified list based on the following rules:
- If the list contains any negative numbers, all negative numbers should be replaced with their absolute values.
- ... | ```java
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class NumberOperations {
public List<Integer> modifyList(List<Integer> numbers) {
List<Integer> modifiedList = new ArrayList<>();
// Replace negative numbers with their absolute values... | magicoder | java |
You are tasked with creating a Python function that processes a CSV file containing student grades and returns the average grade for each student. The CSV file contains the following columns: "Student ID" and "Grade". Your function should read the CSV file, calculate the average grade for each student, and return a dic... | ```python
import csv
def calculate_average_grades(csv_file_path):
student_grades = {}
with open(csv_file_path, 'r') as file:
reader = csv.DictReader(file)
for row in reader:
student_id = int(row['Student ID'])
grade = float(row['Grade'])
if student_id in stud... | magicoder | python |
You are tasked with creating a function to validate a one-time password (OTP) for user authentication. The function should take the OTP as input and return a boolean value indicating whether the OTP is valid or not. Additionally, the function should handle the scenario where the OTP is already used.
You are provided w... | ```javascript
function validateOTP(otp) {
// Assume otpList is an array containing all valid OTPs
let otpList = ["123456", "654321", "987654"];
if (otpList.includes(otp)) {
// OTP is valid
return true;
} else {
// OTP is invalid or already used
this.invalidLogin = true;
alert("OTP is invali... | magicoder | javascript |
You are tasked with creating a program to manage a restaurant's reservation system. The program should allow the user to input and manage reservation details, including the reservation time, customer information, and table allocation. To achieve this, you need to implement a class to represent a reservation and its ass... | ```java
public class Reservation {
private String reservationTime;
private String customerName;
private int tableNumber;
public Reservation(String reservationTime, String customerName, int tableNumber) {
this.reservationTime = reservationTime;
this.customerName = customerName;
t... | magicoder | java |
You are tasked with implementing a utility method to split edges in a layered graph. The graph consists of nodes and edges, where the nodes are arranged in layers. The utility method should split a long edge into multiple shorter edges, ensuring that the resulting edges maintain the layering structure of the graph. The... | ```java
public void splitEdges(Edge longEdge, int segments, LayeredGraph graph) {
Node sourceNode = longEdge.getSourceNode();
Node targetNode = longEdge.getTargetNode();
// Calculate the vertical distance between the source and target nodes
int verticalDistance = targetNode.getLayer() - sourceNode.getL... | magicoder | java |
You are tasked with implementing a CRC-16 (Cyclic Redundancy Check) algorithm to calculate the checksum of a given byte sequence. The CRC-16 algorithm is a widely used error-detecting code that is capable of detecting multiple types of errors in data transmission. The algorithm operates by treating the input data as a ... | ```python
def crc16_from_bytes(data: bytes) -> int:
crc = 0xFFFF # Initial value for CRC-16 calculation
for byte in data:
crc = crc ^ (byte << 8) # XOR the next byte with the current CRC value
for _ in range(8):
if crc & 0x8000: # Check if the most significant bit is set
... | magicoder | python |
You are tasked with creating a TypeScript class that extends a generic Svelte component and enforces specific prop types. Your task is to define a new Svelte component class called `PrinterIcon` that extends the `SvelteComponentTyped` class and enforces prop types for HTML or SVG elements.
Your `PrinterIcon` class sho... | ```typescript
import { SvelteComponentTyped } from 'svelte';
interface PrinterIconProps extends svelte.JSX.HTMLAttributes<HTMLOrSVGElement> {}
export default class PrinterIcon extends SvelteComponentTyped<PrinterIconProps> {}
```
In the solution, we define an interface `PrinterIconProps` that extends `svelte.JSX.HTM... | magicoder | typescript |
You are working for a data analysis company that uses Python for processing and analyzing large datasets. Your task is to create a program that reads data from a CSV file, performs some data manipulation using the pandas library, and then saves the processed data to a new CSV file. Additionally, the program should load... | ```python
import pandas as pd
from dotenv import load_dotenv
import os
# Step 1: Load environment variables from .env file
load_dotenv()
# Step 2: Read data from input_data.csv into a pandas DataFrame
input_data = pd.read_csv("input_data.csv")
# Step 3: Perform data manipulation (example: adding a new column)
input_... | magicoder | python |
You are tasked with creating a program to measure the execution time of a given piece of code. Your program should take a code block as input and return the time taken to execute that code block in milliseconds. You are not allowed to use any built-in timing functions or libraries for this task.
Write a function `meas... | ```swift
func measureExecutionTime(codeBlock: () -> Void) -> Double {
let startTime = CFAbsoluteTimeGetCurrent()
codeBlock()
let endTime = CFAbsoluteTimeGetCurrent()
let timeTaken = (endTime - startTime) * 1000 // Convert to milliseconds
return timeTaken
}
``` | magicoder | swift |
You are given a lambda function `inv2` and an array `t_bids` generated using NumPy's `linspace` function. The lambda function `inv2` takes a parameter `x` and uses variables `c1`, `c2`, and `d2` to perform a series of mathematical operations. The array `t_bids` contains 10000 evenly spaced values between `b[0]` and `b[... | ```python
import numpy as np
from scipy.optimize import minimize
def find_min_bid(inv2, t_bids) -> float:
# Define a function to minimize based on the inv2 lambda function
def min_func(x):
return inv2(x)
# Find the minimum value of the inv2 function using scipy's minimize function
result =... | magicoder | python |
You are tasked with creating a script to process a list of dependencies and generate a JSON representation of the dependencies for a specific programming language. The script should take a list of dependencies in the format "library-version" and produce a JSON object representing the dependencies for a given programmin... | ```bash
#!/bin/bash
# Read input language and version
read -p "Enter programming language: " language
read -p "Enter language version: " version
dependencies=""
# Read dependencies in the format "library-version" from standard input
while IFS= read -r str; do
library=$(echo $str | sed "s/-${version}//")
dependen... | magicoder | shell |
You are working on a version control system and need to implement a function to determine the number of characters that need to be changed in order to transform one string into another. The transformation is case-insensitive, and you can only perform one operation at a time: either insert a character, delete a characte... | ```python
def minEditDistance(source: str, target: str) -> int:
m, n = len(source), len(target)
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] = i
... | magicoder | python |
You are tasked with implementing a function that derives a master key, generates a public key, and then converts the public key into an address for a specific blockchain network. The provided code snippet gives a high-level overview of the process, but you need to write the complete function to achieve this functionali... | ```python
def generate_address(masterKey, derivation_path, networkID, chainId):
key = derive_master_key(masterKey, derivation_path) # Derive the master key
public_key = BipPublicKey(key, Bip44AVAXMainNet) # Generate public key
pk = public_key.RawCompressed() # Get raw compressed public key
addr = add... | magicoder | python |
You are tasked with implementing a method to convert a given object to a string representation. The method should handle various data types and return a string representation of the object. If the object is a string, it should be returned as is. If the object is an array, the method should return a string representatio... | ```java
public class ObjectToStringConverter {
public static String convertToString(Object o) {
if (o instanceof String) {
return (String) o;
} else if (o.getClass().isArray()) {
StringBuilder sb = new StringBuilder("[");
int length = java.lang.reflect.Array.getLe... | magicoder | java |
You are tasked with developing a mobile application for a university's course management system. The application uses Firebase for user authentication and data storage. The provided code snippet is a part of the application's main activity, where a user can select a course or add students to a course.
Your task is to ... | ```java
addstudents.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), AddStudents.class);
intent.putExtra("selectedCourse", selectedCourse); // Pass the selected course to the AddStudents activity
s... | magicoder | java |
You are given a list of integers representing the heights of people standing in a line. The people are standing in a row, and their heights are represented by the integers in the list. You need to find the height of the person who is neither the tallest nor the shortest in the line.
Write a function `find_middle_heigh... | ```python
from typing import List
def find_middle_height(heights: List[int]) -> int:
sorted_heights = sorted(heights)
return sorted_heights[1] # Return the second smallest height, which is the middle height
``` | magicoder | python |
You are tasked with creating a custom dataset class for a computer vision project using PyTorch. The dataset is based on the VOC2012 dataset, which contains images and corresponding segmentation masks for 21 different classes. Your goal is to implement the `VOCDataset` class that inherits from `BaseDataSet` and is resp... | ```python
from PIL import Image
import os
from torch.utils.data import Dataset
from torchvision import transforms
import json
class VOCDataset(Dataset):
def __init__(self, root, transform=None):
self.root = os.path.join(root, 'VOCdevkit/VOC2012')
self.num_classes = 21
self.palette = pallete... | magicoder | python |
You are tasked with creating a Python program that simulates a simple drawing application using the pico2d library. The program should allow the user to draw basic shapes on a canvas and then close the canvas when the drawing is complete.
Your task is to implement a function called `draw_shapes` that takes a list of s... | ```python
import pico2d
def draw_shapes(shapes):
pico2d.open_canvas()
for shape in shapes:
if shape["type"] == "circle":
pico2d.draw_circle(shape["position"][0], shape["position"][1], shape["size"][0] // 2, shape["color"])
elif shape["type"] == "rectangle":
pico2d.d... | magicoder | python |
You are tasked with creating a program to generate a customized audio file from a series of audio segments and comments. The program should take into account various parameters such as fade duration, speech gain, comment fade duration, language, and output file name. You need to implement the `generate_mp3` function, w... | ```python
from pydub import AudioSegment
import os
def generate_mp3(segments, fade_ms, speech_gain, comment_fade_ms, language="en", output_file_name="generated_program_sound"):
output_audio = AudioSegment.silent(duration=0)
for segment in segments:
segment_audio = segment["audio"]
comments = s... | magicoder | python |
You are tasked with creating a Python program that parses an XML file containing information about chemical compounds. The XML file follows the format of the PDBeChem XML file for the wwPDB ligand dictionary, which can be found at ftp://ftp.ebi.ac.uk/pub/databases/msd/pdbechem/readme.htm. The program should extract spe... | ```python
import xml.etree.ElementTree as ET
# Function to parse the XML file and extract compound information
def parse_xml(xml_file):
tree = ET.parse(xml_file)
root = tree.getroot()
compounds = []
for compound in root.findall('compound'):
compound_id = compound.find('id').text
... | magicoder | python |
You are tasked with implementing a logging system that supports different verbosity levels. The code snippet provided includes a variable `verbosityLevel` and a catch block for handling logic errors. Your task is to create a class `Logger` that allows for logging messages at different verbosity levels and to implement ... | ```java
public class Logger {
private int verbosityLevel;
public Logger(int verbosity) {
this.verbosityLevel = verbosity;
}
public void logMessage(String message, int messageVerbosity) {
if (messageVerbosity >= verbosityLevel) {
System.out.println(message);
}
}
... | magicoder | java |
You are tasked with creating a Python script that extracts relevant information from the given code snippet. Specifically, you need to parse the version number, package name, contact email, homepage URL, and repository URL from the provided code and display them in a structured format.
Write a Python function `extract... | ```python
import re
def extract_info_from_code(code: str) -> dict:
info_dict = {}
version_match = re.search(r'VERSION = \((.*?)\)', code)
if version_match:
info_dict["version"] = tuple(map(int, version_match.group(1).split(', ')))
info_dict["package_name"] = re.search(r'__package_name__ = \'(.... | magicoder | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.