query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with creating a command-line tool that processes an Xcode asset catalog and generates a Swift file containing an enum representing the asset names. The tool should take the following command-line arguments:
- `-path <path_to_asset_catalog>`: The path to the Xcode asset catalog directory.
- `-exportPath <... | ```swift
import Foundation
// Define the command-line argument structure
struct CommandLineArguments {
var assetCatalogPath: String?
var exportPath: String?
var enumName: String?
}
// Parse the command-line arguments
func parseCommandLineArguments() -> CommandLineArguments? {
let arguments = CommandLi... | magicoder | swift |
You are tasked with creating a Python script to fetch and process court calendar data from the Vermont Judiciary website. The script should be able to write the fetched data to a Git repository if the corresponding environment variable is set to true. The script should also be able to handle cases where the environment... | ```python
import os
from dotenv import load_dotenv
import requests
import git
def fetch_and_process_calendar_data():
load_dotenv()
WRITE_TO_GIT_REPO = os.getenv('WRITE_TO_GIT_REPO', 'false').lower() == 'true'
WRITE_DIR = os.getenv('WRITE_DIR', './data')
CALENDAR_ROOT_URL = os.getenv("CALENDAR_ROOT_URL... | magicoder | python |
You are tasked with implementing a module resolution system for a JavaScript project. The system should be able to resolve and import modules based on the provided import statements. The import statements follow the ES6 module syntax, where modules are imported using the `import` keyword and exported using the `export`... | ```javascript
function resolveModuleImport(importStatement) {
const importRegex = /from\s+['"](.*)['"]/;
const match = importStatement.match(importRegex);
if (match) {
return match[1];
}
return '';
}
// Test
console.log(resolveModuleImport("export {NoticeView} from './notice'")); // Output: './notice'
``... | magicoder | javascript |
You are given a list of intervals, where each interval is represented by a pair of integers [start, end]. The intervals may overlap, and you need to merge overlapping intervals to produce a list that contains only mutually exclusive intervals.
Write a function `mergeIntervals` that takes a vector of pairs of integers ... | ```cpp
#include <vector>
#include <algorithm>
std::vector<std::pair<int, int>> mergeIntervals(std::vector<std::pair<int, int>> &intervals) {
if (intervals.empty()) {
return {};
}
std::sort(intervals.begin(), intervals.end());
std::vector<std::pair<int, int>> merged;
merged.push_back(inter... | magicoder | cpp |
You are tasked with implementing a method to validate a chat room's configuration based on certain criteria. The chat room configuration is represented by a DataForm object, which contains various fields with their corresponding values. Your task is to write a method that checks if the chat room configuration satisfies... | ```java
public Result validateChatRoomConfiguration(DataForm roomConfiguration) {
try {
final DataForm.Field mam = roomConfiguration.getConfigurationForm().get().findField("mam");
if (mam != null) {
// Assuming the condition for the "mam" field is to check if its value is "enabled"
... | magicoder | java |
You are tasked with implementing a clustering algorithm to analyze an SMS spam dataset using SciPy. The dataset contains a collection of SMS messages labeled as spam or non-spam. Your goal is to use the SciPy library to perform clustering on the dataset and identify patterns that can distinguish between spam and non-sp... | To solve this problem, you can use the following Python code as a starting point:
```python
import numpy as np
from scipy.cluster.vq import kmeans, vq
from scipy.spatial.distance import cdist
import pandas as pd
# Load the SMS spam dataset
# Replace '<reponame>' with the actual repository name
dataset_path = '<repona... | magicoder | python |
You are tasked with implementing a function to create and update statistics in an ordered dictionary. The function `create_stats_ordered_dict` takes in the statistic name, value, and optional parameters such as `stat_prefix` and `always_show_all_stats`. The statistics are then updated in an ordered dictionary called `s... | ```python
from collections import OrderedDict
def create_stats_ordered_dict(stat_name, stat_value, stat_prefix=None, always_show_all_stats=False):
if stat_prefix:
stat_name = f"{stat_prefix} {stat_name}"
return OrderedDict({stat_name: stat_value})
def update_statistics(stat_names, stat_values, stat_pr... | magicoder | python |
You are tasked with creating a program that simulates a simple file loading system. The program should be able to load files and modules based on specific commands provided in a script file.
Your program should read a script file containing a series of commands, each of which can be one of the following types:
1. `Loa... | ```python
class FileLoader:
def __init__(self):
self.loaded_files = set()
self.loaded_modules = set()
def load_file(self, file_path):
if file_path in self.loaded_files:
print(f"File {file_path} is already loaded")
else:
# Perform actual file loading opera... | magicoder | python |
You are tasked with implementing a Python class that provides a wrapper around a service catalog client and offers convenience methods for operations that would otherwise need to be chained together. Your task is to create a class `ServiceCatalogClientCompositeOperations` with the following requirements:
1. The class ... | ```python
import oci
class ServiceCatalogClientCompositeOperations(object):
def __init__(self, service_catalog_client):
"""
Constructor for ServiceCatalogClientCompositeOperations.
:param service_catalog_client: The service catalog client instance.
:type service_catalog_client: oci... | magicoder | python |
You are tasked with implementing a function that creates a new work item in a project management system. The function takes in a list of child work item IDs, an ID for the new work item, and a title for the new work item. The function should create the new work item with the given ID and title, and then associate it wi... | ```python
def create_work_item(child_work_item_ids, id, title):
# Create the new work item with the given ID and title
new_work_item = {
"id": id,
"title": title,
"child_work_items": child_work_item_ids
}
# Associate the new work item with the child work items
for child_... | magicoder | python |
You are tasked with implementing a rocket launch control system. The system is responsible for determining whether a rocket launch should proceed based on various criteria. One of the key components of the system is a function that evaluates the readiness of the rocket for launch. The function takes into account multip... | ```java
public class RocketLaunchControl {
// ... other methods and properties
public boolean positiveLaunch() {
// Assess various parameters to determine readiness for launch
boolean fuelReady = checkFuelLevels();
boolean weatherReady = checkWeatherConditions();
boolean technic... | magicoder | java |
You are tasked with implementing a serialization and deserialization mechanism for a custom form object. The form object represents a user input form with various fields such as text, checkboxes, and radio buttons. Your goal is to create a serialization method that converts the form object into a dictionary, and a dese... | ```python
class FormSerializer:
def serialize(self, form):
serialized_form = {}
# Assuming the form object has a method to retrieve all fields and their values
fields = form.get_fields()
for field in fields:
field_name = field.get_name()
field_value = field.ge... | magicoder | python |
You are tasked with implementing a Python function that generates a module for a given namespace. The function should take a class name and a string representing the namespace as input and return a string representing the generated module.
The function should follow the following format:
```python
def gen_module_for_n... | ```python
def gen_module_for_namespace(classname, input_str):
# Split the input_str into individual function strings
funcs = input_str.split('\n')
# Generate the autogen_str using the provided format
autogen_str = '''
class {classname}:
def __init__(self, *args, **kargs):
self.org = triton.... | magicoder | python |
You are tasked with implementing a Python function that simulates a simple text-based game. The game involves navigating through a grid-based map, avoiding obstacles, and reaching the goal. To enhance the user experience, the game should utilize ANSI escape codes to display colorful text in the terminal.
You are provi... | ```python
def navigate_game(grid_map, start_position, movements):
def printColored(colorA, msg):
print(colorA + msg + reset, end='')
x, y = start_position
for move in movements:
if move == 'U' and x > 0 and grid_map[x - 1][y] != 'X':
x -= 1
elif move == 'D' and x < len(g... | magicoder | python |
You are tasked with creating a Python class that utilizes SQLAlchemy and Pandemic to define a data model for a library management system. The system should have two entities: `Book` and `Author`. Each book can have multiple authors, and each author can have multiple books. The `Book` entity should have the following at... | ```python
from sqlalchemy import Column, Integer, String, ForeignKey, Table
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base
from pandemic import SignatureBuilder, field
from pandemic.normalizers import ModelFieldEx, Normalizers
Base = declarative_base()
# Define associa... | magicoder | python |
You are tasked with implementing a RESTful API for a simple todo list application using Python and Flask. The application has a database with two models: `TodoList` and `TodoItem`. The `TodoList` model represents a collection of todo items, and the `TodoItem` model represents individual todo items. The code snippet pro... | ```python
from flask import Blueprint, request, jsonify
from app.models import TodoList, TodoItem
from app import db
todoList = Blueprint('todoList', __name__, template_folder='templates')
# Create a new todo list
@todoList.route('/todo-list', methods=['POST'])
def create_todo_list():
data = request.json
new_... | magicoder | python |
You are tasked with creating a Rust function that calculates the total size of all files within a given directory using the Tokio asynchronous runtime. You will need to utilize the `tokio::fs::metadata` function to retrieve the metadata of each file and sum up their sizes.
Your task is to implement the `calculate_dire... | ```rust
use tokio::fs;
async fn calculate_directory_size(dir_path: &str) -> Result<usize, std::io::Error> {
let mut size: usize = 0;
let mut entries = fs::read_dir(dir_path).await?; // Read the directory entries asynchronously
while let Some(entry) = entries.next_entry().await? { // Iterate through each ... | magicoder | rust |
You are tasked with implementing a Python class that calculates the BLEU (Bilingual Evaluation Understudy) score for a given input file containing reference and candidate sentences. The BLEU score is a metric used to evaluate the quality of machine-translated text by comparing it to one or more reference translations. ... | ```python
import json
import pandas as pd
from nltk.translate.bleu_score import sentence_bleu
class BleuScore:
def __init__(self, infile):
self._infile = infile
def get_df(self):
try:
with open(self._infile, 'r') as fp:
data = json.load(fp)
reference... | magicoder | python |
You are tasked with creating a function that processes and organizes language locale messages for a Vue.js application. The function should load locale messages from JSON files in a specific directory and format them into a structured object.
Write a function `loadLocaleMessages` that takes no parameters and returns a... | ```javascript
const Vue = require('vue');
const VueI18n = require('vue-i18n');
Vue.use(VueI18n);
function loadLocaleMessages() {
const locales = require.context('./lang', true, /[A-Za-z0-9-_,\s]+\.json$/i);
const messages = {};
for (const key of locales.keys()) {
const matched = key.match(/([A-Za-z0-9-_]+)\... | magicoder | javascript |
You are tasked with creating a Python package for a company's internal use. The package should implement a simple command-line tool for performing basic arithmetic operations. The tool should be able to add, subtract, multiply, and divide two numbers provided as command-line arguments.
Your task is to write the necess... | ```python
from setuptools import setup, find_packages
setup(
name="arithmetic_tool",
version="1.0",
description="A simple command-line arithmetic tool",
url="https://github.com/yourusername/arithmetic_tool",
packages=find_packages(),
entry_points={"console_scripts": ["arithmetic=arithmetic_tool... | magicoder | python |
You are tasked with implementing a class to manage a collection of items and track changes to the collection. The class should provide methods to add new items, update existing items, and retrieve the new and updated items.
You are given a code snippet that asserts the behavior of the class. The `step_result` object r... | ```python
class ItemManager:
def __init__(self):
self.new_items = []
self.updated_items = []
def add_item(self, item):
self.new_items.append(item)
def update_item(self, item):
self.updated_items.append(item)
def get_new_items(self):
return self.new_items
d... | magicoder | python |
You are tasked with implementing a visitor pattern for processing expressions in a programming language. The provided code snippet outlines the signature of the visit methods that need to be implemented. The `SubExpression` type represents a sub-expression within a larger expression, and the `Step` type represents a st... | ```rust
// Define the SubExpression and Step types for demonstration purposes
struct SubExpression;
struct Step;
// Define the Visitor trait
trait Visitor {
fn visit_negation(&mut self, _expression: &SubExpression);
fn visit_not_equal(&mut self, _left: &SubExpression, _right: &SubExpression);
fn visit_or(&... | magicoder | rust |
You are tasked with implementing a program to tokenize sentences extracted from a PDF document. The program should make an API call to retrieve all the paragraphs from the PDF and then tokenize the sentences from each paragraph. The tokenized sentences should be written to an output file.
Your task is to write a Pytho... | ```python
import requests
import argparse
import re
import nltk
from PyPDF2 import PdfReader
def extract_paragraphs_from_pdf(pdf_path):
paragraphs = []
with open(pdf_path, 'rb') as file:
reader = PdfReader(file)
for page in reader.pages:
paragraphs.extend(page.extract_text().split('... | magicoder | python |
You are tasked with implementing a Python class that manages dependencies for a project. The class should utilize caching to improve performance when accessing certain properties.
You are provided with a partial code snippet for the class, which includes a method and two cached properties. The `Pip` class is used to m... | ```python
from functools import cached_property
class Pip:
def __init__(self, ctx, project_root):
self.ctx = ctx
self.project_root = project_root
class DependencyManager:
def __init__(self, ctx, project_root):
self.ctx = ctx
self.project_root = project_root
@cached_propert... | magicoder | python |
You are tasked with implementing a Python class that can execute SQL statements. The class should support executing SELECT, INSERT, UPDATE, and DELETE SQL statements on a given database.
Your task is to complete the implementation of the `ExecuteSQL` class by adding methods for executing different types of SQL stateme... | ```python
import sqlite3
class ExecuteSQL:
def __init__(self, db_connection):
self.db_connection = db_connection
def execute_select(self, sql_statement):
cursor = self.db_connection.cursor()
cursor.execute(sql_statement)
result_set = cursor.fetchall()
return result_set
... | magicoder | python |
You are tasked with creating a Python script that processes command-line arguments to generate statistics from the differences between two XML files. The script should take in the following command-line arguments:
- `-d`: A flag indicating that detailed statistics should be generated.
- `prog0:p0:<file_path_0>`: A key-... | ```python
import argparse
import difflib
import xml.etree.ElementTree as ET
def generate_diff_stats(prog0_path, prog1_path, detailed_stats):
with open(prog0_path, 'r') as prog0_file, open(prog1_path, 'r') as prog1_file:
prog0_data = prog0_file.read()
prog1_data = prog1_file.read()
diff = d... | magicoder | python |
You are tasked with creating a Python function that processes and inserts person data into a database. The function should handle potential exceptions and print error messages when necessary. The function will receive several parameters representing person and travel information, and it should insert this data into a d... | ```python
def process_and_insert_person_data(db, name, surname, province, ship, destination, leave_date, arrive_date, link_family, family_id_register):
try:
print(f"Ship: {ship} - leave_date: {leave_date} - arrive_date: {arrive_date} - province: {province} - destination: {destination} - surname: {surname} -... | magicoder | python |
You are given a list of strings, each representing a pair of coordinates in the format "x1,y1 -> x2,y2". Your task is to calculate the Euclidean distance between each pair of coordinates and return the distances as a list of floating-point numbers rounded to two decimal places.
Write a function `calculate_distances(li... | ```python
from typing import List
import math
def calculate_distances(lines: List[str]) -> List[float]:
distances = []
for line in lines:
coordinates = line.split(' -> ')
x1, y1 = map(int, coordinates[0].split(','))
x2, y2 = map(int, coordinates[1].split(','))
distance = math.sq... | magicoder | python |
You are tasked with creating a Python function that processes a list of student records and returns a filtered list based on specific criteria. Each student record is represented as a dictionary with the following keys: "name", "age", "grade", and "school".
Your task is to implement the function `filter_students` that... | ```python
from typing import List, Dict, Union
def filter_students(students: List[Dict[str, Union[str, int]]], filter_condition: str) -> List[str]:
filtered_students = []
if filter_condition == "high_grade":
filtered_students = [student["name"] for student in students if student["grade"] in ["11",... | magicoder | python |
You are tasked with implementing a custom adapter class in Android for displaying ticket information in a list view. The provided code snippet is the beginning of the `TicketAdapterEx` class, which extends `BaseAdapter` and is intended to work with a `TicketInfo` class. Your task is to complete the implementation of th... | ```java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.justwen.trip.bean.TicketInfo;
import java.util.List;
public class TicketAdapterEx extends BaseAdapter<Tick... | magicoder | java |
You are tasked with implementing a function that handles the deletion of items based on their archetype reference IDs. The function takes an array of archetype reference IDs as an argument and should remove the corresponding items from the system. However, there is a catch - if an archetype reference ID does not exist ... | ```javascript
function handleDeletionByArchetypeReferenceIds(idsToDelete) {
// Assume model is an object with a method to delete items by archetype reference IDs
// For example, model.deleteByArchetypeReferenceId(id) can be used to delete an item
idsToDelete.forEach(id => {
// Check if the item with the give... | magicoder | javascript |
You are tasked with implementing a method to add resource dictionaries to a collection in a C# WPF application. Resource dictionaries are used to define and manage resources such as styles, templates, and other resources that can be shared and reused throughout the application.
You need to create a method `AddResource... | ```csharp
using System;
using System.IO;
using System.Windows;
public class ResourceDictionaryManager
{
private ResourceDictionary Resources { get; }
public ResourceDictionaryManager(ResourceDictionary resources)
{
Resources = resources ?? throw new ArgumentNullException(nameof(resources));
}
... | magicoder | csharp |
You are tasked with creating a dynamic dropdown menu for a web form that allows users to select a category for a quotation. The code snippet provided is a part of the HTML and PHP code for generating the dropdown menu. The PHP code is used to dynamically select the option that matches the category stored in the `$resul... | ```php
function generateDynamicDropdown($options, $selectedCategory) {
$html = '<select name="quotation_category">';
$html .= '<option value="" disabled="">-- Pilih Kategori --</option>';
foreach ($options as $option) {
$html .= '<option value="' . $option . '"';
if ($option === $selectedCat... | magicoder | php |
You are given a string `S` and a character `C`. Your task is to write a function to return an array of integers representing the shortest distance from the character `C` in the string `S`.
The distance between two indices `i` and `j` is calculated as `abs(i - j)`.
You need to implement the following function:
```pyt... | ```python
from typing import List
def shortestToChar(S: str, C: str) -> List[int]:
n = len(S)
res = [0 if S[i] == C else n for i in range(n)]
for i in range(1, n):
res[i] = min(res[i], res[i-1] + 1)
for i in range(n-2, -1, -1):
res[i] = min(res[i], res[i+1] + 1)
retur... | magicoder | python |
You are tasked with implementing a Python function that recursively merges the contents of a source directory into a destination directory. The provided code snippet offers a starting point for the implementation. Your task is to complete the function `merge(src, dst)` so that it correctly merges the contents of the so... | ```python
import os
import os.path as op
import shutil
def merge(src: str, dst: str) -> None:
for file in os.listdir(src):
f_path = op.join(src, file)
if op.isfile(f_path):
shutil.copy(f_path, dst)
elif op.isdir(f_path):
if file.startswith('.'):
conti... | magicoder | python |
You are tasked with creating a Bash script that securely transfers a file to a remote server using SFTP (Secure File Transfer Protocol). The script will take in several parameters and perform the file transfer using the provided credentials and software information.
The script should accept the following parameters in... | ```bash
#!/bin/bash
# Validate the number of input parameters
if [ "$#" -ne 6 ]; then
echo "Usage: $0 <server_address> <transfer_id> <transfer_key> <software_name> <software_version> <filepath>"
exit 1
fi
# Assign input parameters to variables
readonly SERVER_ADDRESS=$1
readonly TRANSFER_ID=$2
readonly TRANSF... | magicoder | shell |
You are tasked with implementing a class that simulates a proportional-integral-derivative (PID) controller for a system. The PID controller is a control loop feedback mechanism widely used in industrial control systems. It continuously calculates an error value as the difference between a desired setpoint (SP) and a m... | ```python
class PIDController:
def __init__(self, kp, ki, kd):
self.kp = kp
self.ki = ki
self.kd = kd
self.integral = 0
self.prev_error = 0
def calculate(self, pv, sp):
error = sp - pv
self.integral += error
derivative = error - self.prev_error
... | magicoder | python |
You are tasked with implementing a function to calculate the derivative of the arctan2 function for complex numbers. The arctan2 function returns the angle in radians between the positive x-axis of a plane and the point given by the coordinates (x, y). The derivative of the arctan2 function with respect to the input co... | ```python
import cmath
def calculate_arctan2_derivative(x, y):
# Calculate the arctan2 value for the given input
arctan2_val = cmath.atan2(y, x)
# Calculate the derivative of arctan2 with respect to x and y
derivative_x = -y / (x**2 + y**2)
derivative_y = x / (x**2 + y**2)
return deri... | magicoder | python |
You are given a code snippet that appears to be part of a larger algorithm. Your task is to understand the code and implement a function that performs the same computation as the given code.
The code snippet is as follows:
```python
is quite costly though.
"""
stype = type(a)
e = (stype.bit_length - 1... | ```python
def compute_h_and_h2(a):
stype = type(a)
e = (stype.bit_length() - 1) // 2
r, r2 = stype(0), stype(0) # r2 = r**2
j = 1 << e
for _ in range(e+1):
h, h2 = r + j, r2 + (2*r + j) * j
r, r2 = h, h2
return h, h2
```
The solution defines the function `compute_h_and_h2(a)` w... | magicoder | python |
You are tasked with creating a React component for a technology level selector. The component should display a set of technology level images, allowing the user to select a specific level. The selected level should be highlighted, and clicking on an image should update the current selection.
The code snippet provided ... | ```jsx
import React from 'react';
import clsx from 'clsx';
import techLevelImages from '@shared/assets/images'; // Assuming the images are stored in a module
const TechnologyLevelSelector = ({ techLevels, currentTier, setCurrentTier }) => {
return (
<div>
{techLevels.map((techLevel) => (
<img
... | magicoder | jsx |
You are tasked with implementing a Python class that handles HTTP requests using the `pycurl` library. Your class should have methods for performing HTTP requests, building request bodies, and extracting response headers and body.
Your task is to complete the implementation of the `HttpClient` class by adding the miss... | ```python
import pycurl
import io
import json
class HttpClient:
def __init__(self):
self.ch = pycurl.Curl()
self.buffer = io.BytesIO()
def perform(self):
self.ch.setopt(self.ch.WRITEFUNCTION, self.buffer.write)
self.ch.perform()
resp = self.buffer.getvalue().decode("utf... | magicoder | python |
You are tasked with creating a validation system for a project worker information management application. The application uses a PHP-based framework and the provided code snippet is a part of the validation process for adding project worker information. The `validate` function is used to create a validation instance, a... | ```php
class ProjectWokerValidate
{
protected $data;
protected $errors = [];
public function scene($scene)
{
// Implement scene-specific validation rules
switch ($scene) {
case 'addInfo':
$this->addInfoRules();
break;
// Add more c... | magicoder | php |
You are tasked with implementing a simple task scheduler using Rust's `ispc` module. The task scheduler will be responsible for executing a set of tasks in parallel. Each task is represented by a function that takes no arguments and returns no value. Your goal is to implement the `TaskScheduler` struct with the followi... | ```rust
fn main() {
unsafe {
let mut scheduler = TaskScheduler::new(4);
scheduler.add_task(|| {
// Task 1: Perform some computation
});
scheduler.add_task(|| {
// Task 2: Perform some computation
});
scheduler.add_task(|| {
// Ta... | magicoder | rust |
You are tasked with implementing a function that processes the output of a Unity process and returns a specific result based on the process's exit status. The function takes in a Unity process and an aggregator for the standard output as input. The Unity process emits a 'close' event, and based on the exit status of th... | ```typescript
function processUnityOutput(unityProcess: UnityProcess, stdoutAggregator: string): Promise<string> {
return new Promise<string>((resolve, reject) => {
unityProcess.once('close', (exitStatus) => {
if (exitStatus === 0) {
resolve(stdoutAggregator);
} else ... | magicoder | typescript |
You are tasked with implementing a simplified version of a keyboard input handling system. The provided code snippet is a part of a larger system and contains a function `IsKeyDown` that takes a `GT::Script` object as a parameter. The `IsKeyDown` function is responsible for checking if a specific key is currently press... | ```cpp
bool IsKeyDown(GT::Script &script, Key key) {
script.Push(GetContext(script).IsKeyDown(static_cast<Key>(key)));
return script.ToBool(-1);
}
``` | magicoder | cpp |
You are tasked with creating a program that analyzes the frequency of words in a given text. Your program should take a string of text as input and output a list of unique words along with their frequencies in descending order.
For example, given the input string:
```
"Hello world, this is a beautiful world."
```
The ... | ```python
from collections import Counter
import re
def word_frequency(text: str) -> List[Tuple[str, int]]:
# Remove punctuation and convert to lowercase
clean_text = re.sub(r'[^\w\s]', '', text.lower())
# Split the text into words and count their frequencies
word_counts = Counter(clean_text.split())
... | magicoder | python |
You are tasked with implementing a function that processes a given JavaScript code snippet and extracts specific information from it. The code snippet will contain a class definition and an export statement. Your task is to extract the name of the class and the type of export (default or named).
Write a function `extr... | ```javascript
function extractClassInfo(codeSnippet) {
const classRegex = /class\s+(\w+)\s+{/;
const exportDefaultRegex = /export\s+default\s+(\w+);/;
const exportNamedRegex = /export\s+{\s+(\w+)\s+};/;
const classNameMatch = codeSnippet.match(classRegex);
const exportDefaultMatch = codeSnippet.mat... | magicoder | javascript |
You are tasked with creating a Bash script to automate the setup of a node for a blockchain network. The script should prompt the user for certain configurations and set corresponding variables based on the user input. Your task is to complete the script by adding the necessary code to handle user input and set the var... | ```bash
#!/bin/bash
# Prompt the user to specify whether the mainnet node should be an archival node
read -r -p "Do you want this mainnet node to be an archival node? (Default $ARCHIVALDEFAULT): " ARCHIVALMAIN
# Set the variable ARCHIVALMAIN based on the user input, defaulting to the value of ARCHIVALDEFAULT if no in... | magicoder | shell |
You are tasked with creating a signal handling mechanism for a multi-platform application. The application needs to handle cleanup operations when receiving termination signals on both Unix-like and Windows systems. The provided code snippet is a part of the signal handling functionality for Unix-like systems. Your tas... | ```rust
#[cfg(windows)]
pub(crate) fn cleanup_tempfiles_windows() {
// Emulate sig-term unconditionally on Windows
// Implement the necessary code to handle cleanup operations for Windows systems
// For example:
// cleanup_tempfiles();
// Perform additional cleanup operations specific to Windows
... | magicoder | rust |
You are tasked with creating a Python class that monitors changes in a directory's files and sends notifications for added, removed, or modified files. Your class should have the following functionalities:
1. Initialize with a target directory and an identifier name.
2. Continuously monitor the target directory for fi... | ```python
import os
import glob
import berrymq
class FileMonitor:
def __init__(self, target_dir, id_name):
self.target_dir = target_dir
self.id_name = id_name
self.fileinfo = self._get_fileinfo()
def _get_fileinfo(self):
result = {}
for filename in glob.glob(self.target... | magicoder | python |
You are tasked with implementing a Python class for a 3D Cartesian coordinate system with elastoplastic material properties. The provided code snippet imports a module `_GMatElastoPlasticQPot3d` and its `Cartesian3d` class, which is used to define the 3D Cartesian coordinate system with elastoplastic material propertie... | ```python
from ._GMatElastoPlasticQPot3d.Cartesian3d import *
class CustomCartesian3d(Cartesian3d):
def calculate_stress(self, strain):
# Utilize the elastoplastic material properties and stress-strain relationship
# defined in the Cartesian3d class to calculate stress values based on the provided ... | magicoder | python |
You are tasked with creating a program to generate a word cloud from a given text file. A word cloud is a visual representation of the frequency of words in a given text, where the size of each word indicates its frequency. The program should read the text from a file, process it, and generate a word cloud image using ... | ```python
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
import os
# Read text from input file
input_file = "input.txt"
with open(input_file, 'r', encoding='utf-8') as file:
text = file.read()
# Preprocess the text
text = te... | magicoder | python |
You are working on a project that involves interfacing with a Java Virtual Machine (JVM) from Rust code. The Rust code needs to interact with various types of Java objects and arrays. To facilitate this interaction, you have been provided with a set of Rust traits and structs that represent different Java types. Your t... | ```rust
fn convert_to_jvalue<T: Jvm>(value: T, jvm: &Jvm) -> jvalue {
if let Some(float_val) = value.downcast_ref::<f32>() {
jvm.jvalue_from_jfloat(*float_val)
} else if let Some(int_val) = value.downcast_ref::<i32>() {
jvm.jvalue_from_jint(*int_val)
} else if let Some(long_val) = value.down... | magicoder | rust |
You are tasked with creating a custom collection view in an iOS app. The collection view should display a list of pinned items, and each item should have a specific layout and behavior. Your task is to implement the necessary code to achieve this functionality.
You are provided with a code snippet that initializes and... | ```swift
import UIKit
class PinnedCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var itemImageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
// Additional UI elements and configurations as needed
// Method to populate the cell with data
func configureCell(with item: PinnedI... | magicoder | swift |
You are tasked with creating a custom hook for managing the selected channel in a messaging application. The provided code snippet is a starting point for the custom hook using the Zustand library, which is a small, fast, and scaleable state management library. Your goal is to complete the custom hook by adding the nec... | ```typescript
import { combine } from 'zustand/middleware';
import create from 'zustand';
import { ChannelAttributes } from '@tidify/common';
export type Selection = 'overview' | 'members' | 'calendar' | 'kanban' | ChannelAttributes;
export const useSelectedChannel = create(
combine(
{
selectedChannel: nu... | magicoder | typescript |
You are tasked with creating a Python program that utilizes TensorFlow Lite to perform image classification on a given set of images. TensorFlow Lite is a lightweight machine learning framework designed for mobile and embedded devices. In this problem, you will need to load a pre-trained model using TensorFlow Lite and... | ```python
from tflite_runtime.interpreter import Interpreter
import numpy as np
from PIL import Image
from typing import List
def load_labels(label_path: str) -> List[str]:
with open(label_path, 'r') as f:
return [line.strip() for line in f.readlines()]
def classify_images(image_paths: List[str]) -> List[... | magicoder | python |
You are tasked with implementing a function to clone a data structure that contains import and type declarations. The given code snippet provides a partial implementation of the cloning process for import and type declarations. Your task is to complete the implementation of the cloning function based on the provided co... | ```cpp
// Clones the data structure with import and type declarations
DataStructure* CloneDataStructure(DataStructure* original) {
DataStructure* clone = new DataStructure(); // Create a new instance for cloning
// Clone import declarations
clone->AllocateImportDeclarations(original->NumImportDeclarations(... | magicoder | cpp |
You are tasked with creating a unit test for a report updating functionality in a software system. The code snippet provided is a part of the unit test setup using the Moq framework for mocking dependencies. Your task is to complete the unit test setup and verify the behavior of the report updating functionality.
The ... | ```csharp
// Import necessary namespaces
using Moq;
using Xunit;
public class ReportServiceTests
{
[Fact]
public void UpdateReport_ShouldUpdateReportAndSaveAuditRecord()
{
// Arrange
var reportId = 1;
var updateUser = new User { Id = 123, Name = "John Doe" };
var oldVersion ... | magicoder | csharp |
You are tasked with implementing a Python function that processes a list of strings and returns the count of unique strings that contain a specific substring. The function should ignore case sensitivity when comparing the strings and the substring. If a string contains the substring multiple times, it should only be co... | ```python
from typing import List
def count_unique_substring_strings(substring: str, strings: List[str]) -> int:
# Convert the substring to lowercase for case-insensitive comparison
substring_lower = substring.lower()
# Initialize a set to store unique strings containing the substring
unique_strin... | magicoder | python |
You are tasked with implementing a subscription management system for a website. The provided code snippet is a part of a React component that handles the subscription button functionality. The button is initially enabled, and when clicked, it triggers a subscription status update through an API call. Upon successful s... | ```javascript
// Implementation of apiSetSubscribeStatus function
const apiSetSubscribeStatus = (code, status) => {
// Simulate API call with a Promise
return new Promise((resolve, reject) => {
// Assuming a successful API call
setTimeout(() => {
// Simulate API response
console.log(`Subscriptio... | magicoder | javascript |
You are tasked with creating a Swift function that processes a given array of tuples representing software products and their corresponding supported operating systems. The function should filter the products based on the specified minimum macOS version and return the names of the products that support the given versio... | ```swift
enum macOS {
case v10_9, v10_10, v10_11, v10_12, v10_13, v10_14, v10_15, v11_0, v12_0
}
func filterProducts(products: [(name: String, supportedOS: [macOS])], minVersion: macOS) -> [String] {
var supportedProducts: [String] = []
for product in products {
if let maxSupportedOS = product... | magicoder | swift |
You are tasked with implementing a function that processes embeddings using layer normalization, dropout, and masking. The function takes as input a 3D tensor representing embeddings, the length of the input sequence, and the stride value. The function performs the following operations:
1. Apply layer normalization to ... | ```python
import tensorflow as tf
def process_embeddings(emb, inp_len, idx, dropout_prob, stride):
# Apply layer normalization
emb_normalized = tf.math.maximum(emb[:, :, :idx], emb[:, :, idx:])
# Apply dropout
emb_dropout = tf.nn.dropout(emb_normalized, rate=dropout_prob)
# Apply masking
... | magicoder | python |
You are tasked with creating a custom viewset in a Django REST framework application. Your custom viewset should handle both read and write operations for a specific model. The model represents a library of books, and you need to implement the necessary viewset to perform CRUD (Create, Read, Update, Delete) operations ... | ```python
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin, CreateModelMixin, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin
from rest_framework.permissions import IsAuthenticated
from rest_framework.authentication import TokenAuthentication
from .models impor... | magicoder | python |
You are tasked with creating a program that can parse and extract the date and time information from a given code snippet. The code snippet is written in Java and contains a comment with a date and time stamp in the Chinese language. Your program should be able to extract this information and convert it into a standard... | ```java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DateTimeExtractor {
public static String extractDateTime(String codeSnippet) {
String pattern = ".*@date (\\d{4})年(\\d{1,2})月(\\d{1,2})日 下午(\\d{1,2}):(\\d{1,2}):(\\d{1,2}).*";
Pattern r = Pattern.compile(pattern);
... | magicoder | java |
You are working on a data processing pipeline for a geospatial analysis application. The pipeline involves merging a Dask DataFrame with another DataFrame derived from a Dask array. The code snippet provided is a part of a method in the pipeline that performs this merging process. The `meta.M` is a matrix, and `xyz_arr... | ```python
import dask.dataframe as dd
import dask.array as da
def merge_dask_dataframes(df, meta_M, xyz_array):
# Step 1: Apply transformation to xyz_array
answer = (meta_M @ xyz_array.T).T
# Step 2: Create answer_df with column names from get_column_names('xyz')
answer_df = dd.from_dask_array(ans... | magicoder | python |
You are tasked with implementing a progress tracking system for a software application. The system should include a class `ProgressWindowController` that manages a window displaying the progress of a task. The window should have the ability to update and display the progress in real-time.
Your task is to design and im... | ```swift
import Cocoa
final class ProgressWindowController: NSWindowController {
private let progressViewController = ProgressViewController()
override init(window: NSWindow?) {
super.init(window: window)
self.contentViewController = progressViewController
}
required init?(coder: NSCo... | magicoder | swift |
You are tasked with implementing a Python class for managing a dataset. The class should have the ability to calculate the number of batches required to process the dataset, handle any remaining data that does not fit into a complete batch, and provide a method to reset the dataset to its initial state.
Your task is t... | ```python
import numpy as np
class DatasetManager:
def __init__(self, image_ids, batch_size):
""" Setup the dataset. """
self.image_ids = image_ids
self.batch_size = batch_size
self.count = len(self.image_ids)
self.num_batches = int(np.ceil(self.count * 1.0 / self.batch_size... | magicoder | python |
You are tasked with implementing a complex number class in C++ to perform arithmetic operations on complex numbers. The complex number class should support addition, subtraction, multiplication, and division operations, as well as the ability to raise a complex number to a power.
Your task is to implement the missing ... | ```cpp
#include <cmath>
class ZComplex {
private:
double real;
double imag;
public:
ZComplex(double real, double imag) : real(real), imag(imag) {}
ZComplex operator+(const ZComplex& other) const {
return ZComplex(real + other.real, imag + other.imag);
}
ZComplex operator-(const ZComp... | magicoder | cpp |
You are tasked with implementing a token revocation system for a web application that uses JSON Web Tokens (JWT) for authentication. Your goal is to create a function that handles revoked tokens and returns a specific response when a revoked token is encountered.
You are provided with a code snippet that includes a re... | ```python
from flask import jsonify
MSG_INVALID_CREDENTIALS = "Invalid credentials"
def my_revoked_token_callback(e):
resp = jsonify({
'status': 401,
'sub_status': 5,
'description': e,
'message': MSG_INVALID_CREDENTIALS
})
resp.status_code = 401
return resp
```
In the ... | magicoder | python |
You are tasked with creating a Python function that calculates the angle between two lines and plots the angle on a graph. The function `get_angle_plot` takes in two lines, a radius, color, origin, and the lengths of the x and y axes. It then calculates the angle between `line1` and the x-axis and plots the angle on a ... | ```python
import numpy as np
import matplotlib.pyplot as plt
def get_angle_plot(line1, line2, radius=1, color=None, origin=(0, 0), len_x_axis=1, len_y_axis=1):
l1xy = line1.get_xydata()
l2xy = line2.get_xydata()
# Calculate the angle between line1 and line2
l1_xs = l1xy[:, 0]
l1_ys = l1xy[:, 1]
... | magicoder | python |
You are given a snippet of code that appears to be incomplete. Your task is to complete the code by implementing a function that checks whether a given string is a palindrome. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward, ignoring spaces, punctuation, ... | ```java
public class PalindromeChecker {
public static void main(String[] args) {
String input = "A man, a plan, a canal, Panama";
System.out.println(isPalindrome(input)); // Output: true
}
public static boolean isPalindrome(String str) {
str = str.replaceAll("[^a-zA-Z0-9]", "").toL... | magicoder | java |
You are tasked with implementing a simplified version of a migration script for a database schema. The script is responsible for applying a series of operations to modify the structure of a database table. Each operation is represented as a migration step, and the script must execute these steps in the correct order to... | ```python
from typing import Dict, List
class Migration:
def apply(self, state: Dict[str, str]) -> Dict[str, str]:
pass
class RemoveField(Migration):
def __init__(self, model_name: str, field_name: str):
self.model_name = model_name
self.field_name = field_name
def apply(self, sta... | magicoder | python |
You are tasked with implementing a function that compresses a given list of values into a string representation based on the number of consecutive repetitions of each value. For example, given the input list [1, 1, 2, 3, 3, 3, 4], the function should return the compressed string "1x2, 2, 3x3, 4", where "1x2" indicates ... | ```javascript
function compressList(inputList) {
if (inputList.length === 0) return "";
let groupList = [];
let currentVal = inputList[0];
let notRepeatIndex = 0;
for (let i = 1; i <= inputList.length; i++) {
const checkVal = inputList[i];
const repeatCount = i - notRepeatIndex;
if (checkVal !=... | magicoder | javascript |
You are tasked with implementing a function to calculate the factorial of a given number. The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. For example, the factorial of 5 (denoted as 5!) is calculated as 5 x 4 x 3 x 2 x 1 = 120.
Write a Python function `factori... | ```python
import math
def factorial(n):
return math.factorial(n)
```
The provided code snippet simply prints the factorial of 80 using the `factorial` function. To solve this problem, you can use Python's built-in `math.factorial` function, which efficiently calculates the factorial of a given number. This functi... | magicoder | python |
You are tasked with implementing a Python class that utilizes the ELMo (Embeddings from Language Models) library to process text data and extract contextual word embeddings. ELMo is a deep contextualized word representation model that takes into account the context of each word in a sentence. Your task is to create a c... | ```python
import tensorflow as tf
import numpy as np
import h5py
from allennlp.modules.elmo import Elmo, batch_to_ids
class ElmoEmbedder:
def __init__(self, options_file, weight_file, vocab_file):
self.elmo = Elmo(options_file, weight_file, 1, dropout=0)
self.vocab_file = vocab_file
def embed_... | magicoder | python |
You are tasked with implementing a network packet fragmentation algorithm. In networking, when a packet exceeds the Maximum Transmission Unit (MTU) of a network, it needs to be fragmented into smaller packets that fit within the MTU. The given code snippet defines the MTU value as 1600 bytes.
Your task is to write a f... | ```rust
fn fragment_packet(packet: &[u8], mtu: usize) -> Vec<Vec<u8>> {
let mut fragmented_packets = Vec::new();
let mut remaining_data = packet;
while !remaining_data.is_empty() {
let chunk_size = if remaining_data.len() > mtu {
mtu
} else {
remaining_data.len()
... | magicoder | rust |
You are tasked with creating a Python class to manage network configurations. Your class should have methods to add, remove, and display network configurations. Each configuration should consist of a setting and a value, such as "speed auto" or "duplex auto". Additionally, the class should have a method to generate a c... | ```python
class NetworkConfigManager:
def __init__(self):
self.configurations = []
def add_config(self, setting: str, value: str):
self.configurations.append((setting, value))
def remove_config(self, setting: str):
self.configurations = [(s, v) for s, v in self.configurations if s ... | magicoder | python |
You are tasked with implementing a function to calculate the sum of all the 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. The first few numbers in this sequence are 0, 1, 1, 2, 3, 5, 8, ... | ```python
def evenFibonacciSum(limit):
# Initialize the first two Fibonacci numbers
fib1, fib2 = 0, 1
evenSum = 0
# Calculate the Fibonacci sequence and sum the even numbers
while fib2 <= limit:
if fib2 % 2 == 0:
evenSum += fib2
fib1, fib2 = fib2, fib1 + fib2
return... | magicoder | python |
You are working on a data analysis project and need to create a program to model the joint probability density function of two random variables, X and Y. The given code snippet is part of a larger program and includes the calculation of marginal probabilities and fitting of normal distribution curves for X and Y.
Your... | ```python
import numpy as np
def joint_pdf(marg_value_x, marg_value_y, x_mu, x_sigma, y_mu, y_sigma, correlation_coefficient):
joint_pdf_values = []
for x in marg_value_x:
row = []
for y in marg_value_y:
exponent = -1 / (2 * (1 - correlation_coefficient**2)) * (
((x ... | magicoder | python |
You are tasked with implementing a function to summarize numerical variables in a given dataframe. The function should calculate various statistical measures for each numerical variable in the dataframe and return a summary table.
You are given the following code snippet as a starting point:
```python
def summarize(v... | ```python
import pandas as pd
def summarize(vars, df):
summary_stats = df[vars].describe().T
summary_stats = summary_stats[['count', 'mean', 'std', 'min', '25%', '50%', '75%', 'max']]
summary_stats.columns = ['Count', 'Mean', 'Standard Deviation', 'Minimum', '25th Percentile', 'Median', '75th Percentile', ... | magicoder | python |
You are given a 2D grid represented as a list of binary numbers. Each binary number represents a row in the grid, and each bit in the binary number represents a cell in the row. A '1' bit represents an obstacle, and a '0' bit represents an empty space. Your task is to write a function that determines the number of conn... | ```python
def count_connected_components(grid):
def dfs(row, col):
if row < 0 or row >= len(grid) or col < 0 or col >= len(grid[0]) or grid[row][col] != '0':
return
grid[row] = grid[row][:col] + '1' + grid[row][col+1:]
dfs(row+1, col)
dfs(row-1, col)
dfs(row, col+... | magicoder | python |
You are tasked with implementing a PHP interface for a recovered entities functionality of a database repository. The interface, named `RecoverableRepository`, contains a single method `recover` that takes a `DomainEntity` as a parameter.
Your task is to create a PHP class that implements the `RecoverableRepository` i... | ```php
<?php
namespace PHPKitchen\Domain\Contracts;
/**
* Represents a domain entity.
*/
class DomainEntity {
private $id;
public function getId(): int {
return $this->id;
}
public function setId(int $id): void {
$this->id = $id;
}
}
/**
* Implements the RecoverableRepository ... | magicoder | php |
You are tasked with implementing a class that simulates a bagging system for a retail store. The bagging system should keep track of the items being added to the bag and provide functionality to dump the bag's contents. Additionally, the system should maintain a flag to indicate whether an item has been added to the ba... | ```python
class BaggingSystem:
def __init__(self):
self.first = True
self.bag_contents = []
def add_item(self, item):
self.bag_contents.append(item)
if self.first:
self.first = False
def bagger_dump(self):
self.bag_contents = []
self.first = True... | magicoder | python |
You are tasked with creating a command-line build tool that simulates the behavior of the given Gradle command. Your tool should support cleaning the project, building the project, skipping tests, and publishing artifacts to a local Maven repository.
Your command-line tool should accept the following options:
- `clean... | ```python
import argparse
def clean_project():
print("Cleaning the project...")
def build_project():
print("Building the project...")
def skip_tests():
print("Skipping tests...")
def publish_to_maven_local():
print("Publishing artifacts to local Maven repository...")
print("Artifacts published l... | magicoder | python |
You are given a code snippet from a shell script that includes comments describing the expected output and some diagnostic checks. Your task is to write a program that processes the output of the given shell script and performs the diagnostic checks mentioned in the comments.
Write a program that reads the output of t... | ```python
import re
def parse_output(output):
numbers = re.findall(r'[-+]?\d*\.\d+e[-+]?\d+|[-+]?\d+', output)
return float(numbers[0]), float(numbers[1])
def is_close_to_zero(number, tolerance=1e-5):
return abs(number) < tolerance
def has_cycles_with_empty_words(input_data):
# Perform the diagnostic... | magicoder | python |
You are tasked with implementing a simplified version of a composite component system in a hypothetical UI framework. The framework provides a `Component` protocol and a `CompositeComponent` class, which can contain other components. Your goal is to create a function that generates a composite component based on a give... | ```swift
static func csComponent(forModel model: Any, context: Any?) -> Component? {
// Assume the model is an integer for simplicity
if let modelValue = model as? Int {
// Create a view configuration with a white background color
let viewConfig = ViewConfiguration(attributes: A.backgroundColor(... | magicoder | swift |
You are tasked with implementing a Python class for a financial modeling application. The class is responsible for processing financial data and generating forward returns. Your task is to complete the implementation of the `generate_forward_return` method in the given class. The method takes in the `scaler`, `sigma`, ... | ```python
import numpy as np
from scipy.stats import spearmanr
class FinancialModel:
def __init__(self, exposure):
self.lastvalue = None
self.logger = None # Assume logger is initialized elsewhere
self.exposure = exposure
def generate_forward_return(self, scaler, sigma, shrinkage):
... | magicoder | python |
You are tasked with implementing a SQL query parser that can handle a specific set of SQL queries. The SQL queries are represented as strings, and your parser should be able to parse these strings into a structured query representation and then convert the structured representation back into the original string form. Y... | ```rust
// Define a struct to represent the structured query representation
struct Query {
// Define fields to represent different parts of the SQL query
// For example: select, from, where, etc.
// You may use appropriate data structures to represent these fields
// For simplicity, let's assume a singl... | magicoder | rust |
You are tasked with implementing a custom error handling mechanism for the `spawn` function in an asynchronous Rust framework. The `spawn` function is used to execute a given asynchronous task, represented by a `Future`, within the context of an Actix system. However, the current implementation lacks proper error handl... | ```rust
use actix::System;
use std::error::Error;
use std::fmt;
// Custom error type for spawn function
#[derive(Debug, Clone)]
pub struct SpawnError {
message: String,
}
impl SpawnError {
pub fn new(message: &str) -> Self {
SpawnError {
message: message.to_string(),
}
}
}
imp... | magicoder | rust |
You are tasked with creating a script to automate the installation and setup of the JAGS (Just Another Gibbs Sampler) software on a Linux system. JAGS is a program for analysis of Bayesian hierarchical models using Markov Chain Monte Carlo (MCMC) simulation. The installation process involves downloading the JAGS source... | ```bash
#!/bin/bash
# Install LAPACK library and development files
sudo yum install lapack-3.4.2-5.el7.ppc64le -y
sudo yum install lapack-static.ppc64le -y
sudo yum install lapack-devel.ppc64le -y
# Download and unpack JAGS source code
wget https://sourceforge.net/projects/mcmc-jags/files/JAGS/4.x/Source/JAGS-4.2.0.t... | magicoder | shell |
You are tasked with implementing a depth-first search algorithm to traverse a tree-like data structure. The data structure is represented as a collection of objects, each containing a set of fields and their corresponding values. The goal is to visit each object in the data structure and perform a specific operation on... | ```python
class DataObject:
def __init__(self, fields, values):
self.fields = fields
self.values = values
def depth_first_search(root, operation):
worklist = [(root, [], None)]
while len(worklist) > 0:
workItem = worklist.pop()
obj = workItem[0]
keyPath = workItem[1]... | magicoder | python |
You are tasked with creating a script that starts the Visor console for Apache Ignite, a distributed database, caching, and processing platform. The script should be able to handle different operating systems and set various Java Virtual Machine (JVM) options.
Write a shell script that starts the Visor console based o... | ```bash
#!/bin/bash
osname=$(uname)
JAVA="java"
IGNITE_HOME="/path/to/ignite/home"
IGNITE_PROG_NAME="VisorConsole"
JVM_OPTS="-Xms512m -Xmx1024m"
QUIET="-DIGNITE_QUIET=true"
DOCK_OPTS=""
JVM_XOPTS="-XX:+UseG1GC -XX:+DisableExplicitGC"
CP="/path/to/ignite/libs/*"
ARGS=""
case $osname in
Darwin*)
"$JAVA" ${J... | magicoder | shell |
You are tasked with implementing a stack data structure using a linked list. The stack should support the standard push and pop operations, along with a method to retrieve the minimum element in constant time. You need to design the stack to have O(1) time complexity for all operations.
You are given the following Nod... | ```python
class MinStack:
def __init__(self):
self.head = None
self.min_stack = []
def push(self, value):
new_node = Node(value)
new_node.next = self.head
self.head = new_node
if not self.min_stack or value <= self.min_stack[-1]:
self.min_stack.append... | magicoder | python |
You are working on a simulation program for a residential area (RA) management system. The program simulates the behavior of resident assistants (RAs) in response to neighbor warnings and their assignment of chores. Each RA has a set of predefined tasks to perform when neighbor warnings are issued and when chores need ... | ```python
class RA:
def __init__(self):
self.neighbor_warnings = 0 # Initialize neighbor warnings count
def inputNeighborWarning(self):
self.neighbor_warnings += 1 # Increment neighbor warnings count
def doChAssign(self):
if self.neighbor_warnings > 0:
# Implement cho... | magicoder | python |
You are tasked with implementing a function to read YAML-based configuration files from a specified folder and its subfolders. The function should return a dictionary containing all the found configuration objects.
You are given the following function signature:
```python
def read_yaml_configs(config_folder: str, con... | ```python
import os
import yaml
def read_yaml_configs(config_folder: str, config, config_objects: dict, secrets: dict) -> dict:
"""
Read all yaml based configuration files from config folder and subfolders and return
dict of all found config objects
:param config_folder: the folder to read from
:pa... | magicoder | python |
You are tasked with implementing a binary tree data structure in Python. The binary tree should support the following operations: creating a new binary tree, inserting a new node, and traversing the tree in different orders.
Your task is to implement the `BinaryTree` class with the following methods:
1. `__init__(self... | ```python
class Node:
def __init__(self, data):
self.data = data
self.left_child = None
self.right_child = None
def insert_left(self, data):
if self.left_child is None:
self.left_child = Node(data)
else:
new_node = Node(data)
new_node.... | magicoder | python |
You are tasked with implementing a Python function that simulates a simple game. The game involves a player navigating through a grid-based world, represented by a 2D list of characters. The player starts at a given position and can move up, down, left, or right within the grid. The goal is to reach a specific target c... | ```python
def navigate_grid(grid, start, target):
rows, cols = len(grid), len(grid[0])
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
def is_valid_move(row, col):
return 0 <= row < rows and 0 <= col < cols and grid[row][col] != 'X'
visited = set()
queue = [start]
while queue:
... | magicoder | python |
You are tasked with implementing a load balancing algorithm for a server pool. The algorithm should select servers from the pool in a round-robin fashion, ensuring that each server is utilized equally. You are given a code snippet that initializes a list of servers and selects a server using a random index. Your task i... | To implement the load balancing algorithm for server selection, you can use the following logic:
```rust
fn select_server(server_list: &mut Vec<PServer>, use_list: &mut Vec<PServer>, detected_times: &mut i32) -> Option<&PServer> {
if server_list.is_empty() {
return None;
}
let index = *detected_ti... | magicoder | rust |
You are tasked with implementing a SIMD (Single Instruction, Multiple Data) operation in a Rust program. SIMD operations allow for parallel processing of data using special CPU instructions, which can significantly improve performance for certain types of computations.
Your task is to write a function that performs a ... | ```rust
use std::arch::x86_64::*;
fn simd_operation(p1: &[f32; 4], p2: &[f32; 4]) -> [f32; 4] {
unsafe {
let p1_ = _mm_loadu_ps(p1.as_ptr());
let p2_ = _mm_loadu_ps(p2.as_ptr());
let b2: __m128 = _mm_dp_ps(p1_, p1_, 0b01110001);
let s: __m128 = _mm_rsqrt_ps(b2);
let bc: __m... | magicoder | rust |
You are tasked with implementing a function that extracts the URLs from a given HTML snippet. The function should take the HTML snippet as input and return a list of unique URLs found within the snippet. A URL is defined as a string that starts with "http://" or "https://" and ends with a non-whitespace character or a ... | ```python
from typing import List
import re
def extract_urls(html: str) -> List[str]:
# Regular expression to match URLs
url_pattern = r'(https?://\S+?)[\s">]'
# Find all matches of URLs in the HTML snippet
urls = re.findall(url_pattern, html)
# Return unique URLs
return list(set(urls))
``` | magicoder | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.